Skip to main content

Retrofit Android studio post the data on Server.



https://choudhary780.blogspot.com/2016/08/retrofit-android-studio-post-data-on.html


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!!!!!!

Comments

Popular posts from this blog

web2apk

http://web2apk.com/create.aspx Create App   Intro   About   Changes   MalWare ?   Contact   Privacy Useful Links Bluetooth Mini Keyboards Android Mini PC Reset Android URL App Title Icon or

how to retrieve image from sqlite database in android and display in listview

 Android platform provides several ways to store data in our application. 1. SQLite database 2. SharedPreferences etc For our post, we will only work with SQLite database. First and foremost, we need to understand what an SQLite database is? SQLite database  is an open source SQL database that stores data to a text file on a device. It executes SQL Commands to perform a set of functions, that is, create, read, update and delete operations. On my previous post, I showed how to  store data in SQLite database from edit text, retrieve and populate it in a listview . For this post, I will show the SQLite CRUD operations with images from gallery and text from EditText. We need to understand this; images are stored in SQLite database as BLOB data type. A BLOB is a large binary object that can hold a variable amount of data.  Note, we can only store images in the database as BLOB data type. We need to convert our image path to a bitmap then to bytes. Also

Android Bar Chart Using MpAndroidChart Library Tutorial

https://www.numetriclabz.com/android-bar-chart-using-mpandroidchart-library-tutorial/ Android Bar Chart Using MpAndroidChart Library Tutorial Objective In this tutorial we learn how to implement Bar Chart using MpAndroidChart Library in your Android App. Download Source Code       Step 1 Contents ·        1  Introduction ·        2  Creating Bar chart o    2.1  Create a new Project o    2.2  Adding library in Project o    2.3  Create Layout o    2.4  To Plot Bar Chart §   2.4.1  Initialize the graph id §   2.4.2  Creating a Dataset §   2.4.3  Defining X-axis labels §   2.4.4  Set the data §   2.4.5  Add the description to the chart §   2.4.6  Run your App §   2.4.7  Set the color §   2.4.8  Adding Animations o    2.5  To plot grouped bar chart §   2.5.1  Creating Dataset o    2.6  Get the best of Android plus exclusive deals and freebies in your inbox!