Friday, 21 September 2018

Android Retrofit Get Example – Fetching JSON from URL

1) Add this dependency on your grdule.build(Module File)

      implementation 'com.squareup.retrofit2:retrofit:2.1.0'
    implementation 'com.google.code.gson:gson:2.6.2'
    implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

2) Add Internet Permission On Manifest.xml File

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

3) Data.class for getting and reading data ()
    

public class Data {
    private String id;
    private String name;
    private String username;
    private String email;


    public Data(String id, String name, String username, String email) {
        this.id = id;
        this.name = name;
        this.username = username;
        this.email = email;
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getUsername() {
        return username;
    }

    public String getEmail() {
        return email;
    }
}


This class property is base upon your JSON data format
my JSON Data  format is 

{
     "id":"1",
     "name" :"Abcd",
      "username":"xyz",
     "email":"abc@xyz.com"
}


4) Api.interface for creating a method

   in retrofit url is define in two parts 
    
    i)  base url (on my code  base url is "https://jsonplaceholder.typicode.com/") 
    
   ii) route (on my code "users" is a route)

   complete url is "https://jsonplaceholder.typicode.com/users"

import java.util.List;

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

public interface Api {

    String BASE_URL = "https://jsonplaceholder.typicode.com/";

    @GET("users")
    Call<List<Data>> getData();
}


5) Get.XML activity layout file

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".Get">

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list_item">

    </ListView>

</RelativeLayout> 

5) Get.java activity java file
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class Get extends AppCompatActivity {

    ListView list_item;

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

        list_item = (ListView)findViewById(R.id.list_item);

        Retrofit get_retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        Api api = get_retrofit.create(Api.class);

        Call<List<Data>> call = api.getData();

        call.enqueue(new Callback<List<Data>>() {
            @Override
            public void onResponse(Call<List<Data>> call, Response<List<Data>> response) {

                //Toast.makeText(getApplicationContext(), String.valueOf(response.body()), Toast.LENGTH_LONG).show();
                List<Data> data = response.body();

                String[] data_arr = new String[data.size()];


                for (int i =0; i< data.size(); i++){
                    data_arr[i] = data.get(i).getId() + "\n"
                            + data.get(i).getName() + "\n" +
                            data.get(i).getUsername() + "\n" +
                            data.get(i).getEmail();
                }

                list_item.setAdapter(
                        new ArrayAdapter<String>(
                                getApplicationContext(),
                                android.R.layout.simple_list_item_1,
                                data_arr
                        )
                );

            }

            @Override
            public void onFailure(Call<List<Data>> call, Throwable t) {
                Toast.makeText(getApplicationContext(), "Error : \n" +t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

}

No comments:

Android Studio - Get Current Latitude And Longitude

1. Add this dependencies in your gradle file     implementation 'com.google.android.gms:play-services-location:18.0.0' 2. Add this p...