Tuesday 9 August 2016

Retrofit Android studio post the data on Server.

We will post the following data.
{
"token":"6536a951423727727c47ed18004e2f30z",
"book_req_category": 1,
"books": [{
    "name": "Flamingo",
    "Class": "12th",
    "medium": "English",
    "is_ncert": 1,
    "publisher_name": "NCERT",
    "type": 0
}]
}


Creating New Project.

Open android studio and create a new project.
File => New => New Project => Configure your new project => Select the form factor yours app will run on => Add an Activity to Mobile => Customize the Activity => Finish.

First we need to add Volley Library to our project.  
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'


Create the Api Client java class in project.
Open app => main => src = ApiClient.java

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Laptop on 8/9/2016.
 */
public class ApiClient {
    private static Retrofit retrofit = null;

    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder().baseUrl("http://books.vevsa.com:7001/")
                    .client(new OkHttpClient())
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}


Create the Response java class in project.
Open app => main => src = Response.java

import com.google.gson.annotations.SerializedName;

/**
 * Created by Laptop on 8/9/2016.
 */
public class Response {
    @SerializedName("log")
    private String log;

    public int getFlag() {
        return flag;
    }

    public void setFlag(int flag) {
        this.flag = flag;
    }

    public String getLog() {
        return log;
    }

    public void setLog(String log) {
        this.log = log;
    }

    @SerializedName("flag")
    private int flag;
}


Create the Interface in project.
Open app => main => src = RetrofitInterface

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Headers;
import retrofit2.http.POST;
/**
 * Created by Laptop on 8/9/2016.
 */

public interface RetrofitInterface {
    //TODO: Please check curly bracket at end point of api name :)
    @POST("req_book_auth/raise_request")
    @Headers("Accept: application/json")
    Call<Response> getAllData(@Body RequestBody params);
}


Create the Java file in project.
Open app => main => src = MainActivity.java

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.HttpURLConnection;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;


public class MainActivity extends AppCompatActivity {

    private ProgressDialog progressDialog;

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

    private void getData() {
        showDialog();
        JSONObject jsonObject = getObject();
        RequestBody body = null;
        if ((jsonObject) != null) {
            Log.i("JSON_DATA", "Json" + jsonObject);
            body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"),
                    (jsonObject).toString());
            RetrofitInterface retrofitInterface = ApiClient.getClient().create(RetrofitInterface.class);
            Call<Response> call = retrofitInterface.getAllData(body);
            call.enqueue(new Callback<Response>() {
                @Override
                public void onResponse(Call<Response> call, retrofit2.Response<Response> response) {
                    closeDialog();
                    Log.i("RESPONSE", "code" + response.code());

                    try {
                        Log.i("RESPONSE", "Flag:::" + response.body().getFlag());
                        Log.i("RESPONSE", "Log:::" + response.body().getLog());
                        if (response.code() == HttpURLConnection.HTTP_OK) {
                            if (response.body().getFlag() == 143) {
                                //     Toast.makeText(getApplicationContext(),"dlkashdsh"+response.body().getLog(),Toast.LENGTH_LONG).show();
                                Log.i("RESPONSE", "Success");
                            } else {
                                Log.i("RESPONSE", "Failure");
                            }

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

                }

                @Override
                public void onFailure(Call<Response> call, Throwable t) {
                    Log.i("RESPONSE", "Error" + t.getMessage());
                    closeDialog();
                }
            });
        } else {
            Log.i("RESPONSE", "Error");
            closeDialog();
        }

    }

    private void showDialog() {
        progressDialog = ProgressDialog.show(MainActivity.this, "", "Loading...");
    }

    private void closeDialog() {
        if (progressDialog != null && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
    }

    private JSONObject getObject() {
        try {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("token", "6536a951423727727c47ed18004e2f30");
            jsonObject.put("book_req_category", 1);
            JSONArray jsonArray = new JSONArray();
            JSONObject object = new JSONObject();
            object.put("name", "Flamingo");
            object.put("Class", "12th");
            object.put("medium", "English");
            object.put("is_ncert", 1);
            object.put("publisher_name", "NCERT");
            object.put("type", 0);
            jsonArray.put(object);
            jsonObject.put("books", jsonArray);
            return jsonObject;
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }

    }
}



Add Internet permission in your manifest
 <uses-permission android:name="android.permission.INTERNET"/>


May this code help you. Thanks!!!!!!

No comments:

Post a Comment