URL:- http://www.mocky.io/v2/5b936d6f33000011002061d3
1 ) Create RetrofitClient(Base URL Class)
Notes :
1 ) Require Libraries
1 ) Create RetrofitClient(Base URL Class)
import retrofit2.GsonConverterFactory; import retrofit2.Retrofit; public class RetrofitClient { //http://www.mocky.io/v2/5b936d6f33000011002061d3 public static final String API_BASE_URL = "http://www.mocky.io/v2/"; public static Retrofit retrofit=null; public static Retrofit getApiClient() { if(retrofit==null) { retrofit=new Retrofit.Builder().baseUrl(API_BASE_URL).addConverterFactory(GsonConverterFactory .create()).build(); } return retrofit; } }
2 ) Create Retrofit ApiInterface Class(End URL Class)
import com.example.discusit.complexretrofitdemo.model.Data; import retrofit2.Call; import retrofit2.http.GET; public interface ApiInterface { @GET("5b936d6f33000011002061d3") Call<Data> getData(); }3 ) Create Require Model Class
A) Data
import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import java.util.List; public class Data { @SerializedName("status") @Expose private String status; @SerializedName("message") @Expose private String message; @SerializedName("data") @Expose private List<Datum> data = null; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<Datum> getData() { return data; } public void setData(List<Datum> data) { this.data = data; } }B) Datumimport com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; import java.util.List; public class Datum { @SerializedName("id") @Expose private String id; @SerializedName("name") @Expose private String name; @SerializedName("country") @Expose private String country; @SerializedName("city") @Expose private String city; @SerializedName("mobile") @Expose private List<Mobile> mobile = null; 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 getCountry() { return country; } public void setCountry(String country) { this.country = country; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public List<Mobile> getMobile() { return mobile; } public void setMobile(List<Mobile> mobile) { this.mobile = mobile; } }C) Phoneimport com.google.gson.annotations.Expose;import com.google.gson.annotations.SerializedName; public class Mobile { @SerializedName("android") @Expose private String android; public String getAndroid() { return android; } public void setAndroid(String android) { this.android = android; } }4 ) Recyclerview Adatper Classimport android.content.Context; import android.content.SharedPreferences; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.discusit.complexretrofitdemo.R; import com.example.discusit.complexretrofitdemo.model.Datum; import com.example.discusit.complexretrofitdemo.model.Mobile; import java.util.ArrayList; public class DataAdapter extends RecyclerView.Adapter { private int mViewItem = 1; private String mReminderId; private Context mActivity; private LayoutInflater mLayoutInflater; private SharedPreferences.Editor ReminderId; private ArrayList<Mobile> mArrPhoneModel = new ArrayList<>(); private ArrayList<Datum> mArrContactModel = new ArrayList<>(); public DataAdapter(Context mActivity, ArrayList<Datum> mArrContactModel) { this.mActivity = mActivity; this.mArrContactModel=mArrContactModel; mLayoutInflater = LayoutInflater.from(mActivity); } public DataAdapter(Context mActivity, ArrayList<Datum> mArrContactModel, ArrayList<Mobile> mArrPhoneModel) { this.mActivity = mActivity; this.mArrContactModel=mArrContactModel; this.mArrPhoneModel=mArrPhoneModel; mLayoutInflater = LayoutInflater.from(mActivity); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = mLayoutInflater.inflate(R.layout.row_data, parent, false); return new CustomViewHolder(view); } @Override public int getItemViewType(int position) { return mArrContactModel.get(position) != null ? mViewItem : 0; } @Override public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) { try { final Datum contactModel = mArrContactModel.get(position); ((CustomViewHolder) holder).mTextId.setText(contactModel.getId()); ((CustomViewHolder) holder).mTextName.setText(contactModel.getName()); ((CustomViewHolder) holder).mTextCountry.setText(contactModel.getCountry()); ((CustomViewHolder) holder).mTextCity.setText(contactModel.getCity()); ((CustomViewHolder) holder).mTextMobile.setText(contactModel.getMobile().get(0).getAndroid()); } catch (Exception exception) { Log.e("Error:>>>>>>", String.valueOf(exception)); } } @Override public int getItemCount() { return mArrContactModel.size(); } public static class CustomViewHolder extends RecyclerView.ViewHolder { private TextView mTextId, mTextName,mTextCountry,mTextCity,mTextMobile,mTextHome,mTextOffice; public CustomViewHolder(View view) { super(view); mTextId = (TextView) view.findViewById(R.id.text_row_data_id); mTextName = (TextView) view.findViewById(R.id.text_row_data_name); mTextCountry= (TextView) view.findViewById(R.id.text_row_data_country); mTextCity= (TextView) view.findViewById(R.id.text_row_data_city); mTextMobile= (TextView) view.findViewById(R.id.text_row_data_mobile); } } }6 ) Database Helper Classpublic class DatabaseHelper extends SQLiteOpenHelper { public static final String TABLE_NAME = "notes"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; public static final String COLUMN_COUNTRY = "country"; public static final String COLUMN_CITY = "city"; public static final String COLUMN_MOBILE = "mobile"; // Create table SQL query public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + COLUMN_NAME + " TEXT," + COLUMN_COUNTRY + " TEXT," + COLUMN_CITY + " TEXT," + COLUMN_MOBILE + " TEXT" + ")"; // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "notes_db"; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } // Creating Tables @Override public void onCreate(SQLiteDatabase db) { // create notes table db.execSQL(CREATE_TABLE); } // Upgrading database @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // Drop older table if existed db.execSQL("DROP TABLE IF EXISTS " +TABLE_NAME); // Create tables again onCreate(db); } public void insertContactData(ArrayList<Datum> contactList) { SQLiteDatabase db = getWritableDatabase(); for (Datum contactsModel : contactList) { ContentValues values = new ContentValues(); values.put(COLUMN_NAME,contactsModel.getName()); values.put(COLUMN_COUNTRY,contactsModel.getCountry()); values.put(COLUMN_CITY,contactsModel.getCountry()); values.put(COLUMN_MOBILE,contactsModel.getCountry()); db.insert(TABLE_NAME, null, values); } db.close(); } }
6 ) Main Activity
import android.content.Context;
import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.util.Log; import com.example.discusit.complexretrofitdemo.adapter.DataAdapter; import com.example.discusit.complexretrofitdemo.model.Data; import com.example.discusit.complexretrofitdemo.model.Datum; import com.example.discusit.complexretrofitdemo.webservices.ApiInterface; import com.example.discusit.complexretrofitdemo.webservices.RetrofitClient; import java.io.IOException; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private String mEndUrl; private DataAdapter dataAdapter; private RecyclerView mRecyclerView; private LinearLayoutManager mLinearLayoutManagerList; private String TAG = MainActivity.class.getSimpleName(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setIds(); setLayout(); callDemoAPI(); } //set Ids For The Views private void setIds() { mRecyclerView=findViewById(R.id.recycle_Activity_main); } // Set Layout For Recycler View private void setLayout() { // dataAdapter = new DataAdapter(mActivity,mArrSubFoldersListModel , this); callDemoAPI(); } private void callDemoAPI() { new MainActivity.RetrofitAyncTask().execute(this); } private class RetrofitAyncTask extends AsyncTask<Context, Void, ArrayList<Datum>> { private String TAG = MainActivity.RetrofitAyncTask.class.getSimpleName(); private Context contx; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected ArrayList<Datum> doInBackground(Context... params) { Log.e(TAG, "processing http request in async task using retrofit"); contx = (Context) params[0]; //create service which is implementation of CouponApi interface by passing it to retrofit object ApiInterface couponService = RetrofitClient.getApiClient().create(ApiInterface.class); //call api method which returns call object Call<Data> call = couponService.getData(); try { //call the api synchronously as this is part of back ground thread already with AsncTask Response<Data> rp = call.execute(); return (ArrayList<Datum>) rp.body().getData(); } catch (IOException e) { Log.e(TAG, "error in getting response from service using retrofit"); } return null; } @Override protected void onPostExecute(ArrayList<Datum> result) { super.onPostExecute(result); if (result != null) { Log.e(TAG, "populate recyclerview Linear in UI after response from service using retrofit"); //populate recyclerview grid from retrofit response result DataAdapter couponAdapter = new DataAdapter(contx,result); DataAdapter couponAdapter = new DataAdapter(contx,result); DatabaseHelper sqLiteHelper = new DatabaseHelper(MainActivity.this); sqLiteHelper.insertContactData(result);mRecyclerView.setHasFixedSize(true); mLinearLayoutManagerList = new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.VERTICAL, false); mRecyclerView.setLayoutManager(mLinearLayoutManagerList); mRecyclerView.setAdapter(couponAdapter); } } } }
6 ) Activity Main.XML
<?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=".MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/recycle_Activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"/> </RelativeLayout>
7 )row.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="wrap_content" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_id" tools:text="id" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_name" tools:text="name" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_country" tools:text="country" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_city" tools:text="city" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_mobile" tools:text="mobile" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_home" tools:text="hoem" android:textSize="20sp" android:textStyle="bold" /> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/text_row_data_office" tools:text="office" android:textSize="20sp" android:textStyle="bold" /> </LinearLayout>
Notes :
1 ) Require Libraries
//App Design
implementation 'com.android.support:design:27.1.0'
//AppCompact
implementation 'com.android.support:appcompat-v7:27.1.1'
// Retrofit & OkHttp
implementation 'com.squareup.retrofit2:retrofit:2.0.0-beta3'
implementation 'com.squareup.retrofit2:converter-gson:2.0.0-beta3'
implementation 'com.squareup.okhttp3:okhttp:3.0.0-RC1'
implementation 'com.squareup.okhttp3:logging-interceptor:3.0.0-RC1'
//Recyclerview
implementation 'com.android.support:recyclerview-v7:27.1.1'
// Output
{
"status": "true",
"message": "Data fetched successfully!",
"data": [
{
"id": "1",
"name": "Roger Federer",
"country": "Switzerland",
"city": "Basel",
"mobile": [
{
"android": "Samsung"
}
]
},
{
"id": "2",
"name": "Rafael Nadal",
"country": "Spain",
"city": "Madrid",
"mobile": [
{
"android": "One PLus"
}
]
},
{
"id": "3",
"name": "Novak Djokovic",
"country": "Serbia",
"city": "Monaco",
"mobile": [
{
"android": "Redmi"
}
]
},
{
"id": "4",
"name": "Andy Murray",
"country": "United Kingdom",
"city": "London",
"mobile": [
{
"android": "Gionee"
}
]
},
{
"id": "5",
"name": "Maria Sharapova",
"country": "Russia",
"city": "Moscow",
"mobile": [
{
"android": "RealMe"
}
]
},
{
"id": "6",
"name": "Caroline Wozniacki",
"country": "Denmark",
"city": "Odense",
"mobile": [
{
"android": "Oppo"
}
]
},
{
"id": "7",
"name": "Eugenie Bouchard",
"country": "Canada",
"city": " Montreal",
"mobile": [
{
"android": "Vivo"
}
]
},
{
"id": "8",
"name": "Ana Ivanovic",
"country": "Serbia",
"city": "Belgrade",
"mobile": [
{
"android": "Nokia"
}
]
}
]
}
Comments
Post a Comment