Tuesday, December 27, 2016

POST Method Using Retrofit 2.0 [Example case : Login Process]

Today i going to share you about how to POST data using retrofit 2.0. The example case that i use here is login process until get the success response.



How the steps? What should be prepared? Let's start!


Compile the several libraries below in your build.gradle (apps):

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'

In your AndroidManifest.xmladd uses permission look like the following:

Create the several layouts :
  1. activity_main.xml > Display the main page
  2. item_answer.xml > Display the aswers of FAQ
  3. item_question.xml > Display the questions of FAQ
Create the several java classes :
  1. MainActivity.java > All the login process and passing value will done here
  2. ApiClient.java > Create the Retrofit's client and interceptors
  3. Inteface ApiService.java > Initialized of retrofit's POST method
  4. LoggingInterceptors.java > To help you see the output of the process in Logcat
  5. FaqModel.java > To store the response of Questions and answers
  6. ListFaqModel.java > To store  list of FAQ
  7. ExpandAdapter.java > To set questions and answers on exapandable

Why we need LoggingInterceptors.java? Because in retrofit we'll difficult to detect the output of the process. If we find an error, it will be hard to debug. So we need this class :

You have to know how the form of the JSON of your target. It used to make us easy to create its model.

Your URL Target :

http://private-fc41f-myprofile2.apiary-mock.com/loginsaya

With required field username dan password

The JSON of the response after you success do login :

Now time to create time the code of the Layouts.

Create new xml file and give it name as activity_main.xml. Paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.putuguna.retrofit2post.MainActivity">
<TextView
android:gravity="center"
android:id="@+id/hello"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello" />
<LinearLayout
android:layout_marginTop="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_below="@id/hello">
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:id="@+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="username"/>
</android.support.design.widget.TextInputLayout>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="password"
android:password="true"
android:id="@+id/password"/>
</android.support.design.widget.TextInputLayout>
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:text="Login"/>
<ExpandableListView
android:layout_marginTop="10dp"
android:id="@+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"></ExpandableListView>
</LinearLayout>
</RelativeLayout>
Create new xml file and give it name as item_answer.xml. Paste the following code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="55dip"
android:orientation="vertical" >
<TextView
android:id="@+id/lblListItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="17dip"
android:paddingTop="5dp"
android:paddingBottom="5dp"
android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />
</LinearLayout>
view raw item_answer.xml hosted with ❤ by GitHub
Create new xml file and give it name as item_questions.xml. Paste the following code :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp">
<TextView
android:id="@+id/lblListHeader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
android:textSize="17dp"
android:textColor="@android:color/black" />
</LinearLayout>
Next, Create all the java classes.

Create new java file and give it name as ApiClient.java. Paste the following code :

package com.example.putuguna.retrofit2post.apis;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
/**
* Created by putuguna on 14/06/16.
*/
public class ApiClient {
public static final String BASE_URL ="http://private-fc41f-myprofile2.apiary-mock.com/";
public static Retrofit retrofit = null;
public static Retrofit getClient(){
if(retrofit==null){
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(new LoggingInterceptor()).build();
retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
view raw ApiClient.java hosted with ❤ by GitHub
Create new java file and give it name as ApiService.java. Paste the following code :

package com.example.putuguna.retrofit2post.apis;
import com.example.putuguna.retrofit2post.ListFaqModel;
import retrofit2.Call;
import retrofit2.http.POST;
import retrofit2.http.Query;
/**
* Created by putuguna on 14/06/16.
*/
public interface ApiService {
@POST("/loginsaya")
Call<ListFaqModel> postLogin(@Query("email") String username, @Query("password") String password);
}
view raw ApiService.java hosted with ❤ by GitHub
Create new java file and give it name as LoggingInterceptor.java. Paste the following code :


package com.example.putuguna.retrofit2post.apis;
import android.util.Log;
import java.io.IOException;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
/**
* Created by putuguna on 1/27/2016.
*/
public class LoggingInterceptor implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
long t1 = System.nanoTime();
String requestLog = String.format("Sending request %s on %s%n%s",
request.url(), chain.connection(), request.headers());
//YLog.d(String.format("Sending request %s on %s%n%s",
// request.url(), chain.connection(), request.headers()));
if (request.method().compareToIgnoreCase("post") == 0) {
requestLog = "\n" + requestLog + "\n" + bodyToString(request);
}
Log.d("TAG", "request" + "\n" + requestLog);
Response response = chain.proceed(request);
long t2 = System.nanoTime();
String responseLog = String.format("Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers());
String bodyString = response.body().string();
Log.d("TAG", "response" + "\n" + responseLog + "\n" + bodyString);
return response.newBuilder()
.body(ResponseBody.create(response.body().contentType(), bodyString))
.build();
}
public static String bodyToString(final Request request) {
try {
final Request copy = request.newBuilder().build();
final Buffer buffer = new Buffer();
copy.body().writeTo(buffer);
return buffer.readUtf8();
} catch (final IOException e) {
return "did not work";
}
}
}
Create new java class that will store the object of FAQ, give it name as FaqModel.java. Paste the following code :

package com.example.putuguna.retrofit2post;
import com.google.gson.annotations.SerializedName;
/**
* Created by putuguna on 14/06/16.
*/
public class FaqModel {
@SerializedName("q")
private String question;
@SerializedName("a")
private String answer;
public FaqModel() {
}
public FaqModel(String question, String answer) {
this.question = question;
this.answer = answer;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAnswer() {
return answer;
}
public void setAnswer(String answer) {
this.answer = answer;
}
}
view raw FaqModel.java hosted with ❤ by GitHub
Because the form of the API required List to cover FaqModel.java, so we must create a new class called ListFaqModel.java. Paste the following code :

package com.example.putuguna.retrofit2post;
import com.google.gson.annotations.SerializedName;
import java.util.List;
/**
* Created by putuguna on 14/06/16.
*/
public class ListFaqModel {
@SerializedName("pertanyaan")
private List<FaqModel> pertanyaan;
public ListFaqModel(List<FaqModel> pertanyaan) {
this.pertanyaan = pertanyaan;
}
public ListFaqModel() {
}
public List<FaqModel> getPertanyaan() {
return pertanyaan;
}
public void setPertanyaan(List<FaqModel> pertanyaan) {
this.pertanyaan = pertanyaan;
}
}
After that, create new adapter class. This class will set the the data to the model. Give it name as ExpandAdapter.java. Paste the following code :

package com.example.putuguna.retrofit2post;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.TextView;
import java.util.HashMap;
import java.util.List;
/**
* Created by putuguna on 14/06/16.
*/
public class ExpandAdapter extends BaseExpandableListAdapter {
private Context context;
private List<FaqModel> listDataHeader;
private HashMap<FaqModel, FaqModel> listDataChild;
public ExpandAdapter(Context context, List<FaqModel> listDataHeader, HashMap<FaqModel, FaqModel> listDataChild) {
this.context = context;
this.listDataHeader = listDataHeader;
this.listDataChild = listDataChild;
}
@Override
public int getGroupCount() {
return this.listDataHeader.size();
}
@Override
public int getChildrenCount(int groupPosition) {
return 1;
}
@Override
public Object getGroup(int groupPosition) {
return this.listDataHeader.get(groupPosition);
}
@Override
public Object getChild(int groupPosition, int childPosition) {
return this.listDataChild.get(this.listDataHeader.get(groupPosition));
}
@Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
@Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
@Override
public boolean hasStableIds() {
return false;
}
@Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
FaqModel headerItem = (FaqModel) getGroup(groupPosition);
Holder holder;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.item_question, parent,false);
holder = new Holder();
holder.question = (TextView) convertView.findViewById(R.id.lblListHeader);
convertView.setTag(holder);
}else{
holder = (Holder) convertView.getTag();
}
holder.question.setText(headerItem.getQuestion());
return convertView;
}
@Override
public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) {
FaqModel headerItem = (FaqModel) getGroup(groupPosition);
Holder holder;
if(convertView==null){
convertView = LayoutInflater.from(context).inflate(R.layout.item_json, parent,false);
holder = new Holder();
holder.answer = (TextView) convertView.findViewById(R.id.lblListItem);
convertView.setTag(holder);
}else{
holder = (Holder) convertView.getTag();
}
holder.answer.setText(headerItem.getAnswer());
return convertView;
}
@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
static class Holder{
TextView question;
TextView answer;
}
}
Next is MainActivity.java, paste the following code :

If has done, run your project. Hope it will works well. I have tried before i post here and it running well.

*****
because we use LoggingInterceptors.java, so we can see the process on your Android Studio's logcat.  :


You can clone the real project here GITHUB

OK, That's all about how to do POST using retrofit 2.0. Hope it helps.

Related Posts


EmoticonEmoticon

:)
:(
hihi
:-)
:D
=D
:-d
;(
;-(
@-)
:o
:>)
(o)
:p
:-?
(p)
:-s
8-)
:-t
:-b
b-(
(y)
x-)
(h)