Cara Get Data JSON menggunakan Retrofit 2

Tutorial ini juga berasal dari postingan di blogspot saya http://www.viyatampaksiring.blogspot.com, alasannya ya sama seperti dipostingan sebelumnya agar informasinya cepat nyebar, bukan plagiat ya

Untuk tutorial kali ini, saya akan mebagikan cara bagaimana mengambil data API dengan Retrofit 2 :

Tambahkan Library yang akan digunakan di built.gradle (app) pada Android Studio Anda.

    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'

Tambahkan uses permission di AndroidManifest.xml

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

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

 

Selanjutkan buat tampilan layout yang akan digunakan, masuk ke res/layout/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.retrofit2.MainActivity">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:id="@+id/hello"
        android:text="Hello there, i trying to get my profile with Retrofit 2" />

    <Button
        android:layout_below="@+id/hello"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/getprofile"
        android:text="Get Profile"/>


    <LinearLayout
        android:gravity="center"
        android:layout_marginTop="20dp"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/getprofile"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/idprofile"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/nameprofle"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/jobprofile"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/ageprofle"/>
    </LinearLayout>

</RelativeLayout>

Untuk bagian file java, ada beberapa hal yang diperlukan (versi style kodingan saya ya)

  1. Class ApiClient.java > implementasi client retrofit
  2. Interafce ApiService.java > implementasi method GET retrofit
  3. Class Profile.java > tempat menampung data yang didapat (object)
  4. Class MainActivity.java > implementasi semuanya

Sebelum memulai kita harus tau dl target URL yang akan kita tuju apa. Di tutorial kali ini Target URL kita adalah

http://private-fc41f-myprofile2.apiary-mock.com/myself?id=1

URL tersebut akan di split menjadi 3 bagian yaitu

  1. http://private-fc41f-myprofile2.apiary-mock.com/
    
  2. myself
    
  3. id=1
    

     

Untuk Lebih jelasnya nanti perhatikan saja di setiap penulisan kode.

Buat class dengan Nama ProfileModel.java

package com.example.putuguna.retrofit2.models;

import com.google.gson.annotations.SerializedName;

/**
 * Created by putuguna on 14/06/16.
 */
public class Profile {
    @SerializedName("id")
    private String id;
    @SerializedName("name")
    private String name;
    @SerializedName("job")
    private String job;
    @SerializedName("age")
    private String age;

    public Profile(String id, String name, String job, String age) {
        this.id = id;
        this.name = name;
        this.job = job;
        this.age = age;
    }

    public Profile() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getJob() {
        return job;
    }

    public void setJob(String job) {
        this.job = job;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }
}

Kemudian selanjutnya buat class ApiClient.java

package com.example.putuguna.retrofit2.apis;

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){
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }

        return retrofit;
    }
}

 

Lanjut buat Interface ApiService.java

package com.example.putuguna.retrofit2.apis;

import com.example.putuguna.retrofit2.models.Profile;

import retrofit2.Call;
import retrofit2.http.GET;
import retrofit2.http.Query;

/**
 * Created by putuguna on 14/06/16.
 */
public interface ApiService {
    @GET("myself")
    Call getMyProfile(@Query("id") String id);
}

 

Dan class yang terakhir yaitu MainActivity.java

package com.example.putuguna.retrofit2;

import android.app.ProgressDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.example.putuguna.retrofit2.apis.ApiClient;
import com.example.putuguna.retrofit2.apis.ApiService;
import com.example.putuguna.retrofit2.models.Profile;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    private Button getData;
    private TextView id;
    private TextView name;
    private TextView job;
    private TextView age;
    private ProgressDialog progressDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getData = (Button) findViewById(R.id.getprofile);
        id = (TextView) findViewById(R.id.idprofile);
        name = (TextView) findViewById(R.id.nameprofle);
        job = (TextView) findViewById(R.id.jobprofile);
        age = (TextView) findViewById(R.id.ageprofle);


        getData.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                progressDialog = new ProgressDialog(MainActivity.this);
                progressDialog.setTitle("Get My Prole");
                progressDialog.setMessage("Loading ...");
                progressDialog.show();

                getProfile();
            }
        });
    }

    private void getProfile(){
        ApiService apiService = ApiClient.getClient().create(ApiService.class);

        Call call = apiService.getMyProfile("1");
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                progressDialog.dismiss();
                Profile p = response.body();

                id.setText(p.getId());
                name.setText(p.getName());
                job.setText(p.getJob());
                age.setText(p.getAge());
            }

            @Override
            public void onFailure(Call call, Throwable t) {
                progressDialog.dismiss();
                Toast.makeText(MainActivity.this, "Failed to load", Toast.LENGTH_LONG).show();
            }
        });
    }
}

 

Jika sudah semuanya, tinggal di running saja melalu Android Studio kalian

Oke demikian tutorial kali ini, semoga membantu kalian semua, happy coding!!

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