This is a simple tutorial on how to implement Retrofit, the REST api in your android application. If you are intending to save the REST data for offline usage, then How to use GreenDao in android studio? is a good read. Make sure you download the complete project.
[wpi_designer_button text=’Download’ link=’https://github.com/arjunsk/android_retrofit’ style_id=’48’ icon=’github’ target=’_blank’]
STEPS
PART 1: Setting up Retrofit REST Data.
In this tutorial, we are considering this json data.
You can host it here: http://myjson.com/
{ "error":false, "carcompanies":[ { "company_name":"Bentley" }, { "company_name":"BMW" }, { "company_name":"Audi" }, { "company_name":"Ford" }, { "company_name":"Fiat" }, { "company_name":"Chevrolet" } ] }
Inorder to format and validate the json, you can use : https://jsonformatter.curiousconcept.com/
PART 2 : Setting up Retrofit in Android Studio
- Add the dependency in your gradle.
compile 'com.squareup.retrofit:retrofit:1.9.0' compile 'com.squareup.okhttp:okhttp:2.5.0' compile 'com.squareup.okhttp:okhttp-urlconnection:2.0.0'
- Add Internet Permission in the AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.codekrypt.retroift"> <uses-permission android:name="android.permission.INTERNET" /> <application
- Now we need to create POJO (Plain Old Java Object or Simple Normal Class ) for our JSON Data.
- Go Here: http://www.jsonschema2pojo.org/
- Add the json data and enter all the details
- Create a new Package in your Android Project and add the downloaded java files into the POJO folder (drag and drop).
com.codekrypt.retroifit > New > Package
- I bileave, you have something like this.
- Create another class called REST.java to handle REST Interface.
package com.codekrypt.retroifit; import com.codekrypt.retroifit.POJO.CarCompanyList_POJO; import retrofit.Callback; import retrofit.http.GET; public class REST { public static String BASEURL="https://api.myjson.com"; public interface api_carCompanies { @GET("/bins/1w1ac") // specify the sub url for the base url void getData(Callback<CarCompanyList_POJO> response); // will give you the json data } }
PART 3: Setting Custom List View Adapter.
I have create a custom list adapter to handle extra fields. ( In case your application is listing more than one data in the list item. )
So let use see the code for custom List view adapter.
list_item.xml
<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.CardView card_view:cardElevation="0dp" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" xmlns:card_view="http://schemas.android.com/tools" android:layout_margin="10dp"> <TextView android:id="@+id/company_name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" /> </android.support.v7.widget.CardView>
gradle dependencies.
compile 'com.android.support:cardview-v7:25.2.0' compile 'com.android.support:appcompat-v7:25.2.0'
adapter.xml
package com.codekrypt.retroifit; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.codekrypt.retroifit.POJO.Carcompany; import java.util.List; public class Adapter extends BaseAdapter { List<Carcompany> companies; Context context; private static LayoutInflater inflater = null; public Adapter(Context mainActivity, List<Carcompany> c) { companies = c; context = mainActivity; inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return companies.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return position; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View listItemView; listItemView = inflater.inflate(R.layout.list_item, null); //Set the name of company in the list item textview TextView name = (TextView) listItemView.findViewById(R.id.company_name); name.setText(companies.get(position).getCompanyName()); return listItemView; } }
PART 4: MainActivity.java (Calling REST)
activity_main.xml ( we have added listview )
<?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.codekrypt.retroifit.MainActivity"> <ListView android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/listView" android:layout_alignParentTop="true" android:layout_alignParentEnd="true" /> </RelativeLayout>
MainActivity.java
package com.codekrypt.retroifit; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.widget.ListView; import com.codekrypt.retroifit.POJO.CarCompanyList_POJO; import com.codekrypt.retroifit.POJO.Carcompany; import java.util.List; import retrofit.Callback; import retrofit.RestAdapter; import retrofit.RetrofitError; import retrofit.client.Response; public class MainActivity extends AppCompatActivity { // NOTE: Global Declaration List<Carcompany> list_car_company; // Hold the list of car companies ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // NOTE : initializing lv=(ListView) findViewById(R.id.listView); restCall(); } //---------------------------------REST-----------------------------------------------------// private void restCall() { //Creating a rest adapter RestAdapter adapter = new RestAdapter.Builder() .setEndpoint(REST.BASEURL) .build(); REST.api_carCompanies api = adapter.create(REST.api_carCompanies.class); //Defining the method api.getData(new Callback<CarCompanyList_POJO>() { @Override public void success( CarCompanyList_POJO car_list_response , Response response) { if (car_list_response != null){ list_car_company = car_list_response.getCarcompanies(); // Takes list of car from Response //Loads List View Adapter arrayAdapter = new Adapter(getBaseContext(), list_car_company); lv.setAdapter(arrayAdapter); } } @Override public void failure(RetrofitError error) { Log.e("Failed to Connect REST",""+error.getCause()); } }); //---------------------*** END REST ***-----------------------------------------------------// } }
That’s it .
When you launch the app, you will be able to see the company names, on the list view.
Reference :
https://www.simplifiedcoding.net/retrofit-android-tutorial-to-get-json-from-server/
https://api.myjson.com/bins/1w1ac
http://stackoverflow.com/questions/25647881/android-asynctask-example-and-explanation
https://blog.robinchutaux.com/blog/a-smart-way-to-use-retrofit/
https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
https://guides.codepath.com/android/Consuming-APIs-with-Retrofit