Tutorials, Free Online Tutorials,It Challengers provides tutorials and interview questions of all technology like java tutorial, android, java frameworks, javascript, core java, sql, php, c language etc. for beginners and professionals.

Breaking

Retrofit Android Example

Today we are going to look at another awesome library Retrofit to make the http calls. Retrofit is denitely the better alternative to volley in terms of ease of use, performance, extensibility and other things. It is a type-­safe REST client for Android built by Square. Using this tool android developer can make all network stuff much more easier. As an example, we are going to download some json and show it in RecyclerView as a list.

 Follow those steps:-

1.Add the permission to access internet in the AndroidManifest.xml file.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="demo.mukesh.app.com.myapplication">

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

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

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

    </application>

</manifest>

2.Open build.gradle and add Retrofit, Gson dependencies

dependencies {

    implementation 'com.android.support:recyclerview-v7:27.1.1'
//retrofit, gson
    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'
}

First, we need to know what type of JSON response we will be receiving
 

 3.Creating Model Class


public class Test {
    @SerializedName("userId")
    @Expose
    private Integer userId;
    @SerializedName("id")
    @Expose
    private Integer id;
    @SerializedName("title")
    @Expose
    private String title;
    @SerializedName("body")
    @Expose
    private String body;

    public Integer getUserId() {
        return userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public Integer getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }
}


4. Let’s see how our APIInterface.java class looks like

public interface APIInterface {

    @GET("posts")
    Call<ArrayList<Test>> getALLData();
}

5.Create APIClient.java Setting Up the Retrofit Interface
 
public class APIClient {
    private static String BASE_URL="https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {

        retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                //.client(client)
                .build();

        return retrofit;
    }

}

 
6. MyAdapter.java
 
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private Context context;
    private ArrayList<Test> arrTest;

    public MyAdapter(Context context, ArrayList<Test> arrTest) {
        this.context = context;
        this.arrTest = arrTest;

    }

    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_items, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        Test test= arrTest.get(position);
        holder.title.setText(test.getTitle());
        holder.desc.setText(test.getBody());

    }

    @Override
    public int getItemCount() {
        return arrTest.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView title,desc;

        public MyViewHolder(View itemView) {
            super(itemView);
            title=(TextView)itemView.findViewById(R.id.tvTitle);
            desc=(TextView)itemView.findViewById(R.id.tvDesc);
        }
    }
}
 
7.MainActivity.java
public class MainActivity extends AppCompatActivity {
    private ArrayList<Test> arrTest;
    private Activity activity;
    private RecyclerView recyclerView;
    private MyAdapter adapter;

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

    private void callAPI() {
        APIInterface apiInterface = APIClient.getClient().create(APIInterface.class);
        Call<ArrayList<Test>> call = apiInterface.getALLData();
        call.enqueue(new Callback<ArrayList<Test>>() {
            @Override
            public void onResponse(Call<ArrayList<Test>> call, Response<ArrayList<Test>> response) {
                arrTest = response.body();
                initRecycler();
            }

            @Override
            public void onFailure(Call<ArrayList<Test>> call, Throwable t) {

            }
        });
    }

    private void initRecycler() {
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        LinearLayoutManager mLayout = new LinearLayoutManager(activity);
        recyclerView.setLayoutManager(mLayout);
        adapter = new MyAdapter(activity, arrTest);
        recyclerView.setAdapter(adapter);
    }
}
 


No comments:

Post a Comment