Hello warriors How are you guys ? hope all of you are busy in coding..Today i am going to tell you How to use Retrofit in Android . New born baby of web services or new networking library called Retrofit.
I hope all of you are familier with older methods to get response from server ..if you are not then don't worry everything is set here for you in Retrofit. But I will suggest you to go and check older methods. lets make a short summary of older methods.In older architecture of web services things were devided in three parts:
But in Retrofit You have nothing to do Everything is automatic. Its like a joke but its true buddy.
Everything is set for you in Retrofit. Now Lets implement Retrofit in our code. I am going to make a simple example to fetch data from Weather API and i will show some data of Weather to Text View.
First of all I have created an Simple Architecture of Retrofit Example, I hope you will like it.
Steps are very simple as you can see in above picture. We need 3 Things for Complete Retrofit Architecture.
So time to start coding. Open your Android studio and create new project with Blank Activity like below image.
We Will need 2 Library for Retrofit working.
- AsyncTask to do all background task
- HttpClient or HttpurlConnection to do networking task
- JsonParser Class to parse data comes from server
But in Retrofit You have nothing to do Everything is automatic. Its like a joke but its true buddy.
Everything is set for you in Retrofit. Now Lets implement Retrofit in our code. I am going to make a simple example to fetch data from Weather API and i will show some data of Weather to Text View.
First of all I have created an Simple Architecture of Retrofit Example, I hope you will like it.
Steps are very simple as you can see in above picture. We need 3 Things for Complete Retrofit Architecture.
- RestAdapter
- An Interface with all networking methods and parameters. i.e, RestInterface
- POJO class to save data coming from server (known as Getter Setter Class)
So time to start coding. Open your Android studio and create new project with Blank Activity like below image.
We Will need 2 Library for Retrofit working.
- Retrofit Library
- OKHttp Library
- For Android Studio you just need to paste below line of code under dependency of build.gradle file.
compile 'com.squareup.retrofit:retrofit:1.9.0'
- For eclipse users download jar file from below link and add to you project.
Now we will add Another library called Okhttp to our project
- For Android Studio you just need to paste below line of code under dependency of build.gradle file.
compile 'com.squareup.okhttp:okhttp:2.4.0'
- For eclipse users download jar file from below link and add to you project.
Now Sync your project after adding both library. You can see both library in my build.gradle file in below picture:
And Now we will Add Internet Permission to our Manifest file as you can see in below picture:
Now we will make all POJO of JSON data coming from server in my case i am using a whether API
http://api.openweathermap.org/data/2./weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0
You can see JSON data by open this link CurrentWheatherApi . its looks like below picture.
How to Make POJO class in Retrofit by Most Easiest Way :
- Visit JsonSchema2pojo.org - This is Official website to Convert JSON Data into POJO class. Just You have to Copy Paste all the Codes.
- Open JsonSchema2pojo its looks like below picture.
Paste your JSON data in box at left side. check source type JSON and Annotation style Gson. Click on preview and you will see all pojo class are created like below.
You can define class name for callback or by default it is Example.java in my case name of call back class is Model. copy all class and paste into your project I will suggest you to make a Different Package for all POJO class like my project.
Things Related to pojo class are done. Now we will move to our MainActivity. First go to your main.xml file and create some textview to show data. here is my xml file.
<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=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txt_city"
android:layout_width="wrap_content"
android:layout_margin="30dp"
android:layout_height="wrap_content"
android:text="City" />
<TextView
android:id="@+id/txt_status"
android:layout_width="wrap_content"
android:layout_margin="30dp"
android:layout_height="wrap_content"
android:text="Status" />
<TextView
android:id="@+id/txt_humidity"
android:layout_width="wrap_content"
android:layout_margin="30dp"
android:layout_height="wrap_content"
android:text="Humidity" />
<TextView
android:id="@+id/txt_press"
android:layout_width="wrap_content"
android:layout_margin="30dp"
android:layout_height="wrap_content"
android:text="Pressure" />
</LinearLayout>
</RelativeLayout>
Now we will make RestAdapter object and will set our url to endpoint for that we will save our url into a string and pass that string to setEndPint parameter like below code.
String url = "http://api.openweathermap.org/data/2.5";
//making object of RestAdapter
RestAdapter adapter = new RestAdapter.Builder().setEndpoint(url).build();
Now we will create an Interface for all http methods and parameter so go to your package and create an Interface in my case i have created RestInterface. add below code to interface.
public interface RestInterface {
@GET("/weather?q=London,uk")
void getWheatherReport(Callback<Model>cb);
}
here getWheatherReport is method to get whether report and Model is pojo class to store response coming from server and
/weather?q=London,uk
is end part of url you can see at starting of post.
Now you are done with interface. everything is approximately done now we will create an object of this interface in MainActivity like below code.
//Creating Rest Services
RestInterface restInterface = adapter.create(RestInterface.class);
Now call getWhetherReport method with Callback like below. one more thing make CallBack of Retrofit not of java you can see When you will type by pressing ctrl+space.
//Calling method to get whether report
restInterface.getWheatherReport(new Callback<Model>() {
@Override
public void success(Model model, Response response) {
city.setText("city :"+model.getName());
status.setText("Status :"+model.getWeather().get(0).getDescription());
humidity.setText("humidity :"+model.getMain().getHumidity().toString());
pressure.setText("pressure :"+model.getMain().getPressure().toString());
}
@Override
public void failure(RetrofitError error) {
String merror = error.getMessage();
}
});
YO we have completed our code dude here is MainActivity.java
package androidwarriors.retrofitexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import androidwarriors.retrofitexample.POJO.Model;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
public class MainActivity extends AppCompatActivity {
TextView city, status, humidity, pressure;
String url = "http://api.openweathermap.org/data/2.5";
@Override
Screenshot of above example:
0 comments: