Showing posts with label Rest API. Show all posts

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

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

Rest using Retrofit
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. This post is Split into Two Parts.
  1. First Part Contains Architecture of Retrofit and How to create MySQL DB and PHP Scripts for Basic Operations.
  2. Second Part Contains how to perform Retrofit Operations in Android.

Architecture of Retrofit Web Service

We need 3 Things for Complete Retrofit Architecture.
  1. RestAdapter
  2. An Interface with all networking methods and parameters.
  3. Getter Setter Class to save data coming from server.

Project Structure:

Create MySQL DataBase and PHP Scripts.
Following image shows my database structure.

PHP Scripts:

I created db_config.php which contains the script to connect DB.
<?php
/**
* Database config variables
*/
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "");
define("DB_DATABASE", "retrofit_example");

$db = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD,DB_DATABASE);
 
if($db == false){
 echo "No connection";
}                        
?>
I created db_function.php which contains the script to execute queries.
<?php
include("db_config.php");
 
function insertData($name,$age,$mobile,$email){
 global $db;
 $result=mysqli_query($db , "INSERT INTO personal_detail(name,age,mobile,email) VALUES('$name','$age','$mobile','$email')")or die(mysqli_error($db));
 return $result;
}

function displayAll(){
 global $db;
 $result=mysqli_query($db , "SELECT * FROM personal_detail")or die(mysqli_error($db));
 return $result;
}

function deleteData($id){
 global $db;
 $result=mysqli_query($db , "DELETE FROM personal_detail WHERE id = '$id'")or die(mysqli_error($db));
 return $result;
}

function updateData($id,$name,$age,$mobile,$email){
 global $db;
 $result=mysqli_query($db , "UPDATE `personal_detail` SET `name`='$name',`age`='$age', `mobile`='$mobile', `email`='$email' WHERE id = '$id'")or die(mysqli_error($db));
 return $result;
}
?>
I created insertData.php which contains the script to insert data.
<?php
include ('db_function.php');
$response = array();
 
//Getting post data 
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$mobile = $_REQUEST['mobile'];
$email = $_REQUEST['email'];

if (isset($_REQUEST['name']) && isset($_REQUEST['age']) && isset($_REQUEST['mobile']) && isset($_REQUEST['email'])){
 
 $result=insertData($name,$age,$mobile,$email);
 if ($result) {
  $response["success"] = 1;
  $response["message"] = "Successfully saved"; 
  echo json_encode($response);
 } 
 else {
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred."; 
  echo json_encode($response);
 }
} 
else {
 $response["success"] = 0;
 $response["message"] = "Required field(s) is missing";  
 echo json_encode($response);
}
?>
I created displayAll.php which contains the script to display all data from DB.
<?php
include ('db_function.php');
 
$response = array();
$result = displayAll(); 

if(mysqli_num_rows($result)>0) {

 $response["details"] = array();
 while ($row = mysqli_fetch_array($result)){
  $data = array();
  $data["id"]=$row["id"];
  $data["name"]=$row["name"];
  $data["age"]=$row["age"];
  $data["mobile"]=$row["mobile"];
  $data["email"]=$row["email"];
  array_push($response["details"], $data);
 }
  if($result){
   $response["success"] = 1;
   $response["message"] = "Successfully Displayed";
   echo json_encode($response);
  }
  else{
   $response["success"] = 0;
   $response["message"] = "Try Again";
   echo json_encode($response);
  }
}
else {
 // no results found
 $response["success"] = 0;
 $response["message"] = "No Details Found";
 echo json_encode($response);
}
if($db == true){
 mysqli_close($db); //Closing the Connection
}
?>
I created deleteData.php which contains the script to delete a data from DB.
<?php
include ('db_function.php');
$response = array();

//Getting post data 
$id = $_REQUEST["id"];

if(isset($id)){
 
 $result = deleteData($id); 

 if($result){
  $response["success"] = 1;
  $response["message"] = "Successfully Deleted";
  echo json_encode($response);
 }
 else{
  $response["success"] = 0;
  $response["message"] = "Try Again";
  echo json_encode($response);
 }
}
else {
 // no results found
 $response["success"] = 0;
 $response["message"] = "Required Fields are Missing";
 echo json_encode($response);
}
if($db == true){
 mysqli_close($db);
}
?>
I created updateData.php which contains the script to update a data from DB.
<?php
include ('db_function.php');
$response = array();
 
//Getting post data 
$id = $_REQUEST["id"];
$name = $_REQUEST['name'];
$age = $_REQUEST['age'];
$mobile = $_REQUEST['mobile'];
$email = $_REQUEST['email'];

if (isset($id) && isset($name) && isset($age) && isset($mobile) && isset($email)){
 
 $result=updateData($id,$name,$age,$mobile,$email);
 if ($result) {
  $response["success"] = 1;
  $response["message"] = "Successfully updated"; 
  echo json_encode($response);
 } 
 else {
  $response["success"] = 0;
  $response["message"] = "Oops! An error occurred."; 
  echo json_encode($response);
 }
} 
else {
 $response["success"] = 0;
 $response["message"] = "Required field(s) is missing";  
 echo json_encode($response);
}
?>

References:

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

Goto Next Part: