Android Retrofit Complete Tutorial - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript Android Retrofit Complete Tutorial - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Thursday, January 18, 2018

Android Retrofit Complete Tutorial

Android Retrofit Complete Tutorial

Android Retrofit Tutorial
Start Android New Project in Android Studio



Then Copy the Retrofit Dependency and paste in build.gradle
From Here : -
    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'
After That click on sync now
. Now gradle downloading dependecy wait few seconds

Now Add the Internet Permission in AndroidManifest.xml


<uses-permission android:name="android.permission.INTERNET"></uses-permission>
Now we are using dummy Api which gives us JSON Array data of post
https://jsonplaceholder.typicode.com/posts



Now we are creating 4 subpackages under your main project packages
1. for modal
2.for retrofit api
3.for activity
4.for adapter.

Lets Start For Modal

Since we are Seeing That Our Modal Response Which had

[
  {
    "userId": 1,
    "id": 1,
    "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
    "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
  },
  {
    "userId": 1,
    "id": 2,
    "title": "qui est esse",
    "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
  },
]
userid
title
id
and body keys under json Array .

Now Lets start Model PostModel.java
PostModel.java



 
package com.sswebtricks.sanjeev.retrofitdemo.model;
import com.google.gson.annotations.SerializedName;
/**
 * Created by sanjeev on 18/1/18.
 */
public class PostModel {
    @SerializedName("userId")
    private String userId;
    @SerializedName("id")
    private String id;
    @SerializedName("title")
    private String title;
    @SerializedName("body")
    private String body;
    public String getUserId() {
        return userId;
    }
    public void setUserId(String userId) {
        this.userId = userId;
    }
    public String getId() {
        return id;
    }
    public void setId(String 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;
    }
}
Now Creating ApiClient.java which is Sending And Receiving Response From Server Here We Use Reftrofit .



ApiClient.java
package com.sswebtricks.sanjeev.retrofitdemo.api;
/**
 * Created by sanjeev on 18/1/18.
 */
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class ApiClient {
    public static final String BASE_URL = "https://jsonplaceholder.typicode.com/";
    private static Retrofit retrofit = null;
    public static Retrofit getClient() {
        if (retrofit==null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
Now Defining The Api End Point Which Contain Information About where we sending request And What keys we passed .
Each endpoint specifies an annotation of the HTTP method (GET, POST, etc.) and the parameters of this method can also have special annotations (@Query, @Path, @Body .)

Take a look to other annotations:
@Path – this will be replace under url method like (post/{id}) id will be replaced by value
@Query – this is key pair value under our methods for calling api like

@Body – We generally use this for json body passing
@Header – Contain Header information
Like content-type,Authorization etc



ApiInterface.java
package com.sswebtricks.sanjeev.retrofittutorial.api;

import com.sswebtricks.sanjeev.retrofittutorial.model.ItemsModel;
import com.sswebtricks.sanjeev.retrofittutorial.model.PostModel;

import java.util.List;

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

/**
 * Created by sanjeev on 18/1/18.
 */

public interface ApiInterface {
    @GET("posts")
    Call<List<PostModel>> get_post();
    //requesting json array that why i take inside list
}
Now Creating Layout (activity_main.xml)



 
<android .support.constraint.constraintlayout="" android:layout_height="match_parent" android:layout_width="match_parent" tools:context="com.sswebtricks.sanjeev.retrofitdemo.activity.MainActivity" 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">
<gridview android:horizontalspacing="0dp" android:id="@+id/gridview" android:layout_height="match_parent" android:layout_width="match_parent" android:numcolumns="1" android:scrollbars="horizontal" android:stretchmode="columnWidth" android:verticalspacing="0dp">
</gridview>
</android>
Now (grdiitem.xml)

 
<android .support.v7.widget.cardview="" android:clickable="true" android:foreground="?android:attr/selectableItemBackground" android:id="@+id/cards" android:layout_height="500dp" android:layout_margin="10dp" android:layout_weight="1" android:layout_width="match_parent" card_view:cardcornerradius="5dp" card_view:cardelevation="5dp" card_view:cardusecompatpadding="true" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:card_view="http://schemas.android.com/apk/res-auto">
    <relativelayout android:layout_height="match_parent" android:layout_width="match_parent">
        <imageview android:adjustviewbounds="true" android:id="@+id/img" android:layout_gravity="top" android:layout_height="wrap_content" android:layout_width="wrap_content" android:src="@drawable/nature"/>
    <textview android:id="@+id/title" android:layout_below="@id/img" android:layout_height="wrap_content" android:layout_width="match_parent" android:padding="5dp" android:text="2" android:textcolor="@color/white" android:textsize="20dp"/>
    <textview android:fontfamily="serif" android:id="@+id/body" android:layout_below="@id/title" android:layout_height="wrap_content" android:layout_margintop="20dp" android:layout_width="wrap_content" android:padding="5dp" android:shadowcolor="#fff" android:text="Total" android:textcolor="#fff" android:textsize="15dp" android:textstyle="bold"/>
    </relativelayout>
</android>
Now Adapter For adding our griditem.xml in activity_main.xml

Adapter includes the modal and our layout file and model information which model data append in our layout file.



MyAdapter.java
package com.sswebtricks.sanjeev.retrofitdemo.adapter;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.CardView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.sswebtricks.sanjeev.retrofitdemo.R;
import com.sswebtricks.sanjeev.retrofitdemo.model.ItemModal;
import java.util.ArrayList;
import java.util.List;
/**
 * Created by sanjeev on 18/1/18.
 */
public class MyAdapter extends BaseAdapter {
    private List mItems = new ArrayList();
    private final LayoutInflater mInflater;
    public MyAdapter(Context context, List items) {
        mInflater = LayoutInflater.from(context);
        mItems=items;
    }
    @Override
    public int getCount() {
        return mItems.size();
    }
    @Override
    public ItemModal getItem(int i) {
        return mItems.get(i);
    }
    @Override
    public long getItemId(int i) {
        return i;
    }
    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        View v = view;
        TextView title;
        TextView body;
        ImageView imageView;
        CardView cardView;
        if (v == null) {
            v = mInflater.inflate(R.layout.griditem, viewGroup, false);
            v.setTag(R.id.title, v.findViewById(R.id.title));
            v.setTag(R.id.body, v.findViewById(R.id.body));
            v.setTag(R.id.cards,v.findViewById(R.id.cards));
            v.setTag(R.id.img,v.findViewById(R.id.img));
        }
        title = (TextView) v.getTag(R.id.title);
        body = (TextView) v.getTag(R.id.body);
        cardView=(CardView)v.getTag(R.id.cards);
        imageView=(ImageView)v.getTag(R.id.img);
        ItemModal item = getItem(i);
        title.setText(item.title);
        body.setText(item.body);
        imageView.setImageResource(R.drawable.nature);
        cardView.setCardBackgroundColor(item.colors);
        return v;
    }

}
And A Modal ItemModal.java





It includes the information of our data like title and body
package com.sswebtricks.sanjeev.retrofitdemo.model;
/**
 * Created by sanjeev on 18/1/18.
 */
public class ItemModal {
    public final String title;
    public final String body;
    public int colors;
    public ItemModal(String title, String body,int colors) {
        this.title = title;
        this.body= body;
        this.colors=colors;
    }
}
Now Our Final MainActivity.java


 
It conatin api interface which implement here and adapter first we take response from server the appending in our list then we update the adpter for new data.
package com.sswebtricks.sanjeev.retrofittutorial.activity;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.GridView;
import android.widget.Toast;

import com.sswebtricks.sanjeev.retrofittutorial.R;
import com.sswebtricks.sanjeev.retrofittutorial.adapter.MyAdapter;
import com.sswebtricks.sanjeev.retrofittutorial.api.ApiClient;
import com.sswebtricks.sanjeev.retrofittutorial.api.ApiInterface;
import com.sswebtricks.sanjeev.retrofittutorial.model.ItemsModel;
import com.sswebtricks.sanjeev.retrofittutorial.model.PostModel;

import java.util.ArrayList;
import java.util.List;

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

public class MainActivity extends AppCompatActivity {
    GridView gridView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        gridView=(GridView)findViewById(R.id.gridview);
        CallApi();
    }
    public void CallApi(){
        ApiInterface apiInterface=ApiClient.getRetrofit().create(ApiInterface.class);
        Call<List<PostModel>> call=apiInterface.get_post();
        call.enqueue(new Callback<List<PostModel>>() {
            @Override
            public void onResponse(retrofit2.Call<List<PostModel>> call, Response<List<PostModel>> response) {

                List<PostModel> list=response.body();
                List<ItemsModel> mlist=new ArrayList<ItemsModel>();
                for (int i=0;i<List.size();i++){
                    mlist.add(new ItemsModel(list.get(i).getTitle(),list.get(i).getBody()));
                }
                MyAdapter myAdapter=new MyAdapter(getApplicationContext(),mlist);
                gridView.setAdapter(myAdapter);
            }

            @Override
            public void onFailure(retrofit2.Call<List<PostModel>> call, Throwable t) {
                Toast.makeText(getApplicationContext(),"Error Fetching ",Toast.LENGTH_SHORT);
            }
        });

    }
}
Also put a image image file in drawble folder named “nature.jpg”

Now Our Final App Look Like this.





 Complete Offline Docs And Project

Docs : - Retrofit Tutorial 

Project : - Download Project

Video Tutorial

No comments:

Post a Comment

Post Top Ad