Wednesday, 27 June 2018

How to use Retrofit to call an API in android. Full example to call any API using Retrofit rx in Android

In this Post i will tell you , how to make a network call in android to GET the data from api using Retrofit .

Do the following steps:-

1. First of all Open your android studio and go to File - New - New Project -Give the project name (whatever u wants i am giving - RetrofitExmp) and then click on - Next -Next -Next -Finish.

2. Now after opening your project click on (here project display mode is - android) app -java -click on your package (com.example.retrofitexmp).

3. Now right click on your app package -New - Package and give name ModelClass.

4. We r using this model class to parse the API data into is , so the model class structure should be match with the api  structure. For this we have to see the response. Here i am using one of the free api link for testing Link is :- https://jsonplaceholder.typicode.com/albums

Note:- before calling Retrofit we needs to add some packages to our app gradle:
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:27.1.1'
compile 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
    // to use retrofit2 notation like @SerializedName("") @Expose    
compile 'com.squareup.retrofit2:retrofit:2.3.0'
compile 'com.squareup.retrofit2:converter-gson:2.3.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'
    // for the using of HttpLoggingInterceptor
compile 'com.squareup.okhttp3:okhttp:3.10.0'
compile 'com.squareup.okhttp3:logging-interceptor:3.10.0'
    // For using AndroidSchedulers for io
compile 'io.reactivex:rxandroid:1.2.1'
compile 'io.reactivex:rxjava:1.3.4'}
5. Now click on ModelClass package and make a new java class with the name of GetAlbumListResponse.java. class will looks like following:-
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;

public class GetALbumListResponse implements Serializable{

    @SerializedName("userId")
    @Expose    
    public int userId;
    
    @SerializedName("id")
    @Expose    
    public int id;

    @SerializedName("title")
    @Expose    
    public String title;


}

6. Now for GET method call , I am creating a interface inside network package with the name of "AppInterface" code are following :-
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;

public interface AppInterface {

    @GET("{albums}")
    Observable<GetALbumListResponse> getAlbumListApi(@Path("albums") String albums);
}

7. Now for Retrofit Network call we have to create another class inside network package code are following  , as i made class (NetworkManager.java):-
public class NetworkManager {

    String url = "https://jsonplaceholder.typicode.com/";

    // make Retrofit network call with api link
    public AppInterface getRetrofitServices(Context context){

        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(httpLoggingInterceptor).build();
        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(url)
                .client(client)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();

        return retrofit.create(AppInterface.class);
    }
}

8. Now  we will call the api make separate class for this with the name of (AppApiControllerClass)code are following :-
import rx.Observable;
import rx.Subscriber;
import rx.Subscription;
import rx.schedulers.Schedulers;
import rx.android.schedulers.AndroidSchedulers;

public class AppApiControllerClass extends NetworkManager {

    public Subscription  getApiSubscription(final Context context, final OnHttpResponseListner listner) {

        final Observable<GetALbumListResponse> observable = getRetrofitServices(context).getAlbumListApi("albums");
        Subscription subscription = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<GetALbumListResponse>() {
                    @Override                    
                    public void onCompleted() {}

                    @Override                    
                    public void onError(Throwable e) {
                    }
                    @Override                    
                    public void onNext(GetALbumListResponse response) {
                        listner.onSuccess(123,response);
                    }
                });
        return subscription;

    }
}
8. Now  in MainActivity.java class we will just call the method to his the api code are following :-
public class MainActivity extends AppCompatActivity implements OnHttpResponseListner{
    Subscription subscription;
    AppApiControllerClass appApiControllerClass;

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

        //call api            appApiControllerClass = new AppApiControllerClass();
        appApiControllerClass.getApiSubscription(MainActivity.this, this);


    }

    @Override    public void onSuccess(int requestCode, GetALbumListResponse response) {
        Toast.makeText(MainActivity.this, response.toString(),Toast.LENGTH_LONG).show();

    }
}
9. Output :-







Monday, 18 June 2018

Display number DecimalFormat after one digit of decimal without round value

1. activity_main.xml:-
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center_vertical"   
 android:orientation="vertical"   
 android:layout_height="match_parent"    
tools:context=".MainActivity">

    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv1"        
android:layout_gravity="center"        
android:gravity="center"/>
    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv2"        
android:layout_gravity="center"        
android:gravity="center"/>
    <TextView        
android:layout_width="match_parent"        
android:layout_height="wrap_content"        
android:text=""        
android:id="@+id/tv3"        
android:layout_gravity="center"        
android:gravity="center"/>

</LinearLayout>
2. MainActivity.java:-
public class MainActivity extends AppCompatActivity {
    TextView tv1,tv2,tv3;
    private String reviews;


    @Override   
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        reviews = "2.97";
        tv1 = (TextView)findViewById(R.id.tv1);
        tv2 = (TextView)findViewById(R.id.tv2);
        tv3 = (TextView)findViewById(R.id.tv3);

        try {
            float f = Float.parseFloat(reviews);
            tv1.setText(String.format("%.1f", f) );
            tv2.setText(reviews.substring(0, reviews.indexOf('.')+2));

            // USED TO FORMAT STRING AFTRE DECIMAL TILL 1 DIGIT WITHOUT ROUNDING THE VALUE            DecimalFormat df = new DecimalFormat(".0");
            df.setRoundingMode(RoundingMode.DOWN);
            String ratingFinal = df.format(f);
            tv3.setText( ratingFinal);

        } catch (Exception e){
            e.printStackTrace();
        }


    }
}
3.Output
3.0
2.9
2.9