Langsung ke konten utama

How to Perform Rest API using Retrofit in Android (Part-2)

How to Perform Rest API using Retrofit in Android

In this post, I will show you How to use Retrofit in Android. Retrofit is a new born baby of web services such as AsyncTask, JSONParsing and Volley.In Previous Part, I showed the PHP Scripts to perform basic CRUD operations. In this part, Contains the informations about how to perform Retrofit Operations in Android.

Project Structure:

Create New Project in Android Studio with blank activity as in the following.

We need Retrofit Library for working with that. 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.

Download jar

AndroidManifest.xml

Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>

AppConfig.class

Create AppConfig.class and replace it with the following code.It is used as helper class for web services
package androidmads.example.retrofitexample.helper;

import com.google.gson.JsonElement;

import retrofit.Callback;
import retrofit.client.Response;
import retrofit.http.Field;
import retrofit.http.FormUrlEncoded;
import retrofit.http.GET;
import retrofit.http.POST;

public class AppConfig {

public interface insert {
@FormUrlEncoded
@POST("/personal_details/insertData.php")
void insertData(
@Field("name") String name,
@Field("age") String age,
@Field("mobile") String mobile,
@Field("email") String email,
Callback<Response> callback);
}

public interface read {
@GET("/personal_details/displayAll.php")
void readData(Callback<JsonElement> callback);
}

public interface delete {
@FormUrlEncoded
@POST("/personal_details/deleteData.php")
void deleteData(
@Field("id") String id,
Callback<Response> callback);
}

public interface update {
@FormUrlEncoded
@POST("/personal_details/updateData.php")
void updateData(
@Field("id") String id,
@Field("name") String name,
@Field("age") String age,
@Field("mobile") String mobile,
@Field("email") String email,
Callback<Response> callback);
}
}

activity_main.xml

Create activity_main.xml and replace it with the following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
android:padding="@dimen/activity_vertical_margin"
tools:context="example.retrofit.MainActivity">

<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/name_hint"
android:inputType="textPersonName" />

<EditText
android:id="@+id/age"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/age_hint"
android:inputType="number" />

<EditText
android:id="@+id/mobile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/mob_no_hint"
android:inputType="phone" />

<EditText
android:id="@+id/mail"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:hint="@string/mail_hint"
android:inputType="textEmailAddress" />

<Button
android:gravity="center"
android:id="@+id/insert"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ins_hint" />

<Button
android:gravity="center"
android:id="@+id/retrieve"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/read_hint" />

</LinearLayout>

MainActivity.class

Create MainActivity.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import androidmads.example.retrofitexample.helper.AppConfig;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class MainActivity extends AppCompatActivity {

String BASE_URL = "http://192.168.1.32";

EditText edt_name, edt_age, edt_mobile, edt_mail;
Button btn_insert, btn_display;

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

edt_name = (EditText) findViewById(R.id.name);
edt_age = (EditText) findViewById(R.id.age);
edt_mobile = (EditText) findViewById(R.id.mobile);
edt_mail = (EditText) findViewById(R.id.mail);
btn_insert = (Button) findViewById(R.id.insert);
btn_display = (Button) findViewById(R.id.retrieve);

btn_insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
insert_data();
}
});

btn_display.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(),DisplayData.class);
startActivity(i);
}
});
}

public void insert_data() {

RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();

AppConfig.insert api = adapter.create(AppConfig.insert.class);

api.insertData(
edt_name.getText().toString(),
edt_age.getText().toString(),
edt_mobile.getText().toString(),
edt_mail.getText().toString(),
new Callback() {
@Override
public void success(Response result, Response response) {

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);

JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");

if(success == 1){
Toast.makeText(getApplicationContext(), "Successfully inserted", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(getApplicationContext(), "Insertion Failed", Toast.LENGTH_SHORT).show();
}

} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}

@Override
public void failure(RetrofitError error) {
Toast.makeText(MainActivity.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}

return super.onOptionsItemSelected(item);
}
}

DisplayData.class

Create DisplayData.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.JsonElement;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import androidmads.example.retrofitexample.helper.AppConfig;
import androidmads.example.retrofitexample.helper.ListViewAdapter;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class DisplayData extends AppCompatActivity {

String BASE_URL = "http://192.168.1.32";

ListView details_list;
ListViewAdapter displayAdapter;
ArrayList id = new ArrayList<>();
ArrayList name = new ArrayList<>();
ArrayList age = new ArrayList<>();
ArrayList mobile = new ArrayList<>();
ArrayList email = new ArrayList<>();

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

details_list = (ListView) findViewById(R.id.retrieve);
displayAdapter = new ListViewAdapter(getApplicationContext(), id, name, age, mobile, email);
displayData();

details_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long ids) {
Intent i = new Intent(getApplicationContext(),UpdateData.class);
i.putExtra("id",id.get(position));
i.putExtra("name",name.get(position));
i.putExtra("age",age.get(position));
i.putExtra("mobile",mobile.get(position));
i.putExtra("email", email.get(position));
startActivity(i);

}
});

details_list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener(){
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long ids) {
delete(id.get(position));
return true;
}
});
}

public void displayData() {

RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();

AppConfig.read api = adapter.create(AppConfig.read.class);
api.readData(new Callback() {
@Override
public void success(JsonElement result, Response response) {

String myResponse = result.toString();
Log.d("response", "" + myResponse);
try {
JSONObject jObj = new JSONObject(myResponse);
int success = jObj.getInt("success");
if (success == 1) {
JSONArray jsonArray = jObj.getJSONArray("details");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jo = jsonArray.getJSONObject(i);
id.add(jo.getString("id")); name.add(jo.getString("name")); age.add(jo.getString("age")); mobile.add(jo.getString("mobile")); email.add(jo.getString("email"));
details_list.setAdapter(displayAdapter);
} else {
Toast.makeText(getApplicationContext(), "No Details Found", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
Log.d("exception", e.toString());
}
}

@Override
public void failure(RetrofitError error) {
Log.d("Failure", error.toString());
Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}

public void delete(String id){

RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();

AppConfig.delete api = adapter.create(AppConfig.delete.class);
api.deleteData(
id,
new Callback() {
@Override
public void success(Response result, Response response) {

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);

JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");

if(success == 1){
Toast.makeText(getApplicationContext(), "Successfully deleted", Toast.LENGTH_SHORT).show();
recreate();
} else{
Toast.makeText(getApplicationContext(), "Deletion Failed", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}

@Override
public void failure(RetrofitError error) {
Toast.makeText(DisplayData.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);

}

}

ListViewAdapter.class

Create ListViewAdapter.class and replace it with the following code
package androidmads.example.retrofitexample.helper;

import android.annotation.SuppressLint;
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 java.util.ArrayList;

import androidmads.example.retrofitexample.R;

public class ListViewAdapter extends BaseAdapter {

private final Context context;
private final ArrayList id;
private final ArrayList name;
private final ArrayList age;
private final ArrayList mobile;
private final ArrayList email;
LayoutInflater layoutInflater;

public ListViewAdapter(Context ctx, ArrayList id, ArrayList name, ArrayList age,
ArrayList mobile, ArrayList email) {
this.context = ctx;
this.id = id;
this.name = name;
this.age = age;
this.mobile = mobile;
this.email = email;

}

@Override
public int getCount() {
return id.size();
}

@Override
public Object getItem(int position) {
return position;
}

@Override
public long getItemId(int position) {
return position;
}

@SuppressLint("ViewHolder")
@Override
public View getView(final int position, View view, ViewGroup parent) {

Holder holder = new Holder();
layoutInflater = (LayoutInflater) context.getSystemService
(Context.LAYOUT_INFLATER_SERVICE);

view = layoutInflater.inflate(R.layout.list_item, null);
holder.txt_name=(TextView)view.findViewById(R.id.name);
holder.txt_age=(TextView)view.findViewById(R.id.age);
holder.txt_mobile=(TextView)view.findViewById(R.id.mobile);
holder.txt_mail=(TextView)view.findViewById(R.id.mail);

holder.txt_name.setText(name.get(position));
holder.txt_age.setText(age.get(position));
holder.txt_mobile.setText(mobile.get(position));
holder.txt_mail.setText(email.get(position));

return view;
}

static class Holder {
TextView txt_name,txt_age,txt_mobile,txt_mail;
}
}

UpdateData.class

Create UpdateData.class and replace it with the following code
package androidmads.example.retrofitexample;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.JsonElement;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

import androidmads.example.retrofitexample.helper.AppConfig;
import androidmads.example.retrofitexample.helper.ListViewAdapter;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;

public class UpdateData extends AppCompatActivity {

String BASE_URL = "http://192.168.1.32";

EditText edt_name, edt_age, edt_mobile, edt_mail;
Button btn_update;

String id, name, age, mobile, email;

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

edt_name = (EditText) findViewById(R.id.name);
edt_age = (EditText) findViewById(R.id.age);
edt_mobile = (EditText) findViewById(R.id.mobile);
edt_mail = (EditText) findViewById(R.id.mail);
btn_update = (Button) findViewById(R.id.update);

Intent i = getIntent();
id = i.getStringExtra("id");
name = i.getStringExtra("name");
age = i.getStringExtra("age");
mobile = i.getStringExtra("mobile");
email = i.getStringExtra("email");

edt_name.setText(name);
edt_age.setText(age);
edt_mobile.setText(mobile);
edt_mail.setText(email);

btn_update.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

// "id" is used as a reference for modification in Data
update_data(id);

}
});

}

public void update_data(String id) {

RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(BASE_URL) //Setting the Root URL
.build();

AppConfig.update api = adapter.create(AppConfig.update.class);
api.updateData(
id,
edt_name.getText().toString(),
edt_age.getText().toString(),
edt_mobile.getText().toString(),
edt_mail.getText().toString(),
new Callback() {
@Override
public void success(Response result, Response response) {

try {

BufferedReader reader = new BufferedReader(new InputStreamReader(result.getBody().in()));
String resp;
resp = reader.readLine();
Log.d("success", "" + resp);
JSONObject jObj = new JSONObject(resp);
int success = jObj.getInt("success");

if (success == 1) {
Toast.makeText(getApplicationContext(), "Successfully updated", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),DisplayData.class));
finish();
} else {
Toast.makeText(getApplicationContext(), "Update Failed", Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
Log.d("Exception", e.toString());
} catch (JSONException e) {
Log.d("JsonException", e.toString());
}
}

@Override
public void failure(RetrofitError error) {
Toast.makeText(UpdateData.this, error.toString(), Toast.LENGTH_LONG).show();
}
}
);
}

}

References:

  1. MakeInfo:Retrofit Android Tutorial
  2. Retrofit Android Example

Download Full Source Code

Download Code

Komentar

Postingan populer dari blog ini

FlatBuffers Android Tutorial

FlatBuffers is an efficient cross platform serialization library for C++, Java, C#, Go, Python and JavaScript. It was originally created at Google for game development and other performance-critical applications. FlatBuffers is Open Source (Apache license V2) and available on GitHub . It's currently used by:   Cocos2d-x , the open source mobile game engine and used to serialize the game data. Facebook uses it for client-server communication in the Android app (see the article) . Fun Propulsion Labs at Google in most of libraries and games. Solution overview  The schema will be defind in JSON format, then it will be converted to FlatBuffer format outside the application The Java classes of the Data model will be generated manually using flatc (FlatBuffer compiler) Step 1: Build FlatBuffers Download the source code in Google’s flatbuffers repository .  The build process is described on Google's documentation FlatBuffers Building .  On MacOS for example: Open the xcode proje

QR-Code Generator - Library

In this Post, I introduce my new Gradle Library. This Library is used to Generate QR Code Automatically for our specified input. How to Import the Library: Gradle: compile 'androidmads.library.qrgenearator:QRGenearator:1.0.0' Permission: <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> How to use this Library: After importing this library, use the following lines to use this library. The following lines are used to generated the QR Code // Initializing the QR Encoder with your value to be encoded, type you required and Dimension QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension); try { // Getting QR-Code as Bitmap bitmap = qrgEncoder.encodeAsBitmap(); // Setting Bitmap to ImageView qrImage.setImageBitmap(bitmap); } catch (WriterException e) { Log.v(TAG, e.toString()); } Save QR Code as Image // Save with location, value, bitmap returned and type of Image(JPG/PNG). QRGSaver.save(s

Download file using Okio in Android

Okio is a library that complements java.io and java.nio to make it much easier to access, store, and process your data. Simply Okio is a modern I/O API for Java.  In this post, we will see how to download image or any file using Okio. Okio is component for OkHttp Coding Part Create a new project in Android Studio. Add following dependencies to your  app-level  build.gradle  file. compile 'com.squareup.okhttp3:okhttp:3.6.0' Don't forget to add the following permission in your AndroidManifest.xml <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> Implementation Paste the following code in your Activity and Here, I have kept as MainActivity.java public void downloadImg(View view) { try { Request request = new Request.Builder() .url(imageLink) .build(); new OkHttpClient().newCall(request).enqueue(new Callback() { @Override public void onFail