Cara POST data Login menggunakan Retrofit 2 dan Mendapatkan Respon Respon JSON

Ini adalah postingan di blogspot saya http://www.viyatampaksiring.blogpsot.com, tapi saya posting juga di wordpress saya, agar informasinya menyebar banyak (hehe : jadi bukan plagiat ya :-p)

Berselang satu hari dengan Tutorial GET data menggunakan Retrofit, kali ini saya akan membagikan cara POST data dengan Retrofit. Contoh kasus yang saya gunakan disini yaitu proses login sampe mendapatkan response dari API

Nah hasilnya itu seperti yang terlihat di video diatas. Oke mari kita mulai, apa saya yang diperlukan? bagaimana caranya?. Ikuti saja tutorial ini sampe selesai, niscaya kalian pasti mengerti.

Compile beberapa library dibawah ini di 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'

Dibagian AndroidManifest.xml kalian tampahkan uses permission seperti dibawah ini :

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.putuguna.retrofit2post">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Layout yang diperlukan antara lain :

  1. activity_main.xml > menampilkan tampilan utamanya
  2. item_answer.xml > menampilkan jawaban dari FAQ
  3. item_question.xml > menampilkan pertanyataan dari FAQ

File Java yang diperlukan antara lain :

  1. MainActivity.java > Segala proses Login dan passing di lakukan disini
  2. ApiClient.java > membuat client dan interceptor Retrofit
  3. Inteface ApiService.java > Inisialisasikan method POST retrofit
  4. LoggingInterceptors.java > melihat hasil dari proses di Log
  5. FaqModel.java > untuk menampung response Questions dan Answer
  6. ListFaqModel.java > untuk menampung List array dari FAQ
  7. ExpandAdapter.java > untuk menset question dan answer di Expandable

Kenapa perlu class LoggingInterceptors.java? karena diretrofit akan sulit mendeteksi outputnya (jikalau terjadi error2 tertentu kalian akan kebingungan untuk debugging nya). Makanya perlu class ini

Oya sebelumnya kalian harus tau dl target kalian bentuk JSON nya seperti apa, sehingga akan mudah dalam membuat class modelnya.
Target URL kalian adalah :

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

Dengan required field username dan password

Target Response JSON yang akan kalian dapat bentuknya seperti ini :

{
  "pertanyaan": [
    {
      "q": "Siapa sebenarnya saya?",
      "a": "Saya adalah seorang developer"
    },
    {
      "q": "Bagaimana saya belajar?",
      "a": "Harus belajar dengan tekun"
    },
    {
      "q": "Haruskah saya belajar dengan guru?",
      "a": "Tidak harus, kalian bisa belajar secara online"
    },
    {
      "q": "dimana saya harus belajar online?",
      "a": "ada banyak situs untuk belajar pemrogramana di internet"
    },
    {
      "q": "Bisa kasi saya sebuah contoh?",
      "a": "Ini salah satunya www.w3schools.com"
    },
    {
      "q": "Bahasa pemrograman apa saja yang terdapat disana?",
      "a": "Ada banyak bahasa disana tinggal pilih saja"
    },
    {
      "q": "Kasi saya rekomendasi bahasa yang bagus untuk dipelajari!",
      "a": "Menurut kami bahasa yang saat ini bagus dipelajari yaitu Java"
    },
    {
      "q": "Ada apa dengan Java? Kenapa harus dipelajari?",
      "a": "Ketika Anda mampu mengaplikasikan semua structure didalam Pemrograman Java, Kalian akan merasa lebih mudah ketika pindah bahasa pemrograman"
    }
  ]
}

Selanjutnya kita mulai proses kodingannya, ikuti step-step dibawah ini, pastikan kalian memahaminya ya, karena pemrograman itu bukan hanya sekedar copy and paste saja tapi understanding what you did and wrote.

activity_main.xml

<?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>

item_answer.xml

<?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>

item_questions.xml

<?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>

Selanjutnya, berikut ini adalah source code dari class-class java nya

ApiClient.java

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;
    }
}

Interface ApiService.java

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);
}

class LoggingInterceptor.java

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";
        }
    }
}

Model yang akan menampung object FAQ yaitu FaqModel.java

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;
    }
}

Karena bentuk API yang harus ada List untuk membungkus FaqModel.java, maka saya buatkan class nya yaitu ListFaqModel.java

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;
    }
}

Selanjutnya, saya buat class yang menset data data yang telah didapat bernama ExpandAdapter.java

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;
    }
}

Selanjutnya adalah MainActivity.java yaitu tempat mengimplementasikan semua class dan interface

package com.example.putuguna.retrofit2post;
 
import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.Toast;
 
import com.example.putuguna.retrofit2post.apis.ApiClient;
import com.example.putuguna.retrofit2post.apis.ApiService;
 
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
 
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
 
public class MainActivity extends AppCompatActivity {
 
    private ExpandAdapter adapter;
    private ExpandableListView expandableListView;
    private List<faqmodel> listFaqHeader;
    private HashMap<faqmodel faqmodel=""> listFaqChild;
    private Button btnLogin;
    private EditText username;
    private EditText password;
    private ProgressDialog progressDialog;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        expandableListView = (ExpandableListView) findViewById(R.id.list);
        btnLogin = (Button) findViewById(R.id.btn_login);
        username = (EditText) findViewById(R.id.username);
        password = (EditText) findViewById(R.id.password);
         
        btnLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 
                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("Get My FAQ");
                progressDialog.setMessage("Loading ...");
                progressDialog.show();
 
                prepareData();
 
            }
        });
    }
 
    private void prepareData(){
        listFaqHeader = new ArrayList<>();
        listFaqChild = new HashMap<>();
 
        ApiService apiService = ApiClient.getClient().create(ApiService.class);
        Call<listfaqmodel> call = apiService.postLogin(username.getText().toString(), password.getText().toString());
        call.enqueue(new Callback<listfaqmodel>() {
            @Override
            public void onResponse(Call<listfaqmodel> call, Response<listfaqmodel> response) {
                List<faqmodel> list = response.body().getPertanyaan();
                listFaqHeader = list;
                Log.d("TAG", "VALUE SIZE : " + list.size());
                for(int i=0; i<list .size="" :="" adapter="" ainactivity.this="" all="" expandablelistview.setadapter="" expandadapter="" getquestion="" i="" istfaqmodel="" list.get="" listfaqchild.put="" listfaqchild="" listfaqheader.get="" listfaqheader="" log.d="" onfailure="" password.settext="" progressdialog.dismiss="" public="" username.settext="" verride="" void=""> call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Failed to load data", Toast.LENGTH_LONG).show();
            }
        });
    }
}

Jika sudah selesai dengan semuanya, silakan di jalankan projectnya melalu Android Studio kalian. Harusnya sih baik-baik saja ya, karena saya sebelum posting di blog, saya sudah coba dulu sebelumnya.

—————
Nah, fungsi dari LoggingInterceptors.java bisa kalian lihat di Logcat Android Studio Kalian :

logcrop

Oke, sekian tutorial kali ini, jika ada sesuatu yang ingin ditanyakan silakan tulis komentar kalian. Happy coding! Have fun!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s