Showing posts with label Retrofit. Show all posts

How To Use Retrofit 2 With Android Using Kotlin

Introduction 

Here, I have created a Weather App to demonstrate Retrofit 2 with Kotlin. The same example was created for my previous article “How to Create Weather App Using Retrofit 2 in Android”. You can read my previous article here.

Coding Part 

I have detailed the article in the following sections. 
  1. Creating a new project with Empty activity. 
  2. Setting up the Retrofit HTTP Library and Manifest. 
  3. Implementation of Retrofit with Kotlin.

Step 1 - Creating a new project with Kotlin

  1. Open Android Studio and select "Create new project". 
  2. Name the project as per your wish and tick the "Kotlin checkbox support". 
  3. Then, select your Activity type (For Example - Navigation Drawer Activity, Empty Activity, etc.).
  4. Click the “Finish” button to create a new project in Android Studio.

Step 2 - Setting up the Retrofit HTTP Library and Manifest

The following lines are added to your Kotlin project by default.
dependencies {   
    …  
    implementation 'org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version'  
    implementation 'com.squareup.retrofit2:retrofit:2.0.0'  
    implementation 'com.squareup.retrofit2:converter-gson:2.0.0'
    …  
}
And also, we need to add the INTERNET permissions in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

Step 3 - Implementation of Retrofit with Kotlin

The following API link is used to get the current weather report with respect to the geo-coordinates. The sample API link is here. To know, “How to setting up the Open Weather API”, visit my previous article link. Let's see how to use the link to access the weather data.
  1. Create an interface file named as “WeatherService.kt” and add the following lines in it.
    interface WeatherService {  
        @GET("data/2.5/weather?")  
        fun getCurrentWeatherData(@Query("lat") lat: String, @Query("lon") lon: String, @Query("APPID") app_id: String): Call  
    }
  2. Create a class file named as “WeatherResponse.kt” and add the following lines. Here, we used a Gson Converter and so the JSON response is automatically converted to the respective and the converter will compare the response tree with the serialized name.
    class WeatherResponse {  
      
        @SerializedName("coord")  
        var coord: Coord? = null  
        @SerializedName("sys")  
        var sys: Sys? = null  
        @SerializedName("weather")  
        var weather = ArrayList()  
        @SerializedName("main")  
        var main: Main? = null  
        @SerializedName("wind")  
        var wind: Wind? = null  
        @SerializedName("rain")  
        var rain: Rain? = null  
        @SerializedName("clouds")  
        var clouds: Clouds? = null  
        @SerializedName("dt")  
        var dt: Float = 0.toFloat()  
        @SerializedName("id")  
        var id: Int = 0  
        @SerializedName("name")  
        var name: String? = null  
        @SerializedName("cod")  
        var cod: Float = 0.toFloat()  
    }  
      
    class Weather {  
        @SerializedName("id")  
        var id: Int = 0  
        @SerializedName("main")  
        var main: String? = null  
        @SerializedName("description")  
        var description: String? = null  
        @SerializedName("icon")  
        var icon: String? = null  
    }  
      
    class Clouds {  
        @SerializedName("all")  
        var all: Float = 0.toFloat()  
    }  
      
    class Rain {  
        @SerializedName("3h")  
        var h3: Float = 0.toFloat()  
    }  
      
    class Wind {  
        @SerializedName("speed")  
        var speed: Float = 0.toFloat()  
        @SerializedName("deg")  
        var deg: Float = 0.toFloat()  
    }  
      
    class Main {  
        @SerializedName("temp")  
        var temp: Float = 0.toFloat()  
        @SerializedName("humidity")  
        var humidity: Float = 0.toFloat()  
        @SerializedName("pressure")  
        var pressure: Float = 0.toFloat()  
        @SerializedName("temp_min")  
        var temp_min: Float = 0.toFloat()  
        @SerializedName("temp_max")  
        var temp_max: Float = 0.toFloat()  
    }  
      
    class Sys {  
        @SerializedName("country")  
        var country: String? = null  
        @SerializedName("sunrise")  
        var sunrise: Long = 0  
        @SerializedName("sunset")  
        var sunset: Long = 0  
    }  
      
    class Coord {  
        @SerializedName("lon")  
        var lon: Float = 0.toFloat()  
        @SerializedName("lat")  
        var lat: Float = 0.toFloat()  
    }
  3. Then, open your Activity file and in my case, I have opened my MainActivity.kt file. Then, create Retrofit Builder with Base URL and GsonConverterFactory.
    val retrofit = Retrofit.Builder()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
  4. Then, create a service for Retrofit with your service interface, as shown below.
    val retrofit = Retrofit.Builder()  
    .baseUrl(BaseUrl)  
    .addConverterFactory(GsonConverterFactory.create())  
    .build()
    Here, “getCurrentWeatherData” is an interface function created in the “WeatherService” interface.
  5. Then, create a queue with Weather Response which is used to de-serialize the JSON output of the Open Weather API. The following will show the created queue.
    call.enqueue(object : Callback {  
                override fun onResponse(call: Call, response: Response) {  
                    if (response.code() == 200) {  
                        …  
                    }  
                }  
                override fun onFailure(call: Call, t: Throwable) {  
                    …  
            }  
       })

Full Code

You can find the full code implementation of the app here.
class MainActivity : AppCompatActivity() {    
    private var weatherData: TextView? = null    
    override fun onCreate(savedInstanceState: Bundle?) {    
        super.onCreate(savedInstanceState)    
        setContentView(R.layout.activity_main)    
        weatherData = findViewById(R.id.textView)    
        findViewById(R.id.button).setOnClickListener { getCurrentData() }    
    }    
    internal fun getCurrentData() {    
        val retrofit = Retrofit.Builder()    
                .baseUrl(BaseUrl)    
                .addConverterFactory(GsonConverterFactory.create())    
                .build()    
        val service = retrofit.create(WeatherService::class.java)    
        val call = service.getCurrentWeatherData(lat, lon, AppId)    
        call.enqueue(object : Callback {    
            override fun onResponse(call: Call, response: Response) {    
                if (response.code() == 200) {    
                    val weatherResponse = response.body()!!    
    
                    val stringBuilder = "Country: " +    
                            weatherResponse.sys!!.country +    
                            "\n" +    
                            "Temperature: " +    
                            weatherResponse.main!!.temp +    
                            "\n" +    
                            "Temperature(Min): " +    
                            weatherResponse.main!!.temp_min +    
                            "\n" +    
                            "Temperature(Max): " +    
                            weatherResponse.main!!.temp_max +    
                            "\n" +    
                            "Humidity: " +    
                            weatherResponse.main!!.humidity +    
                            "\n" +    
                            "Pressure: " +    
                            weatherResponse.main!!.pressure    
    
                    weatherData!!.text = stringBuilder    
                }    
            }    
    
            override fun onFailure(call: Call, t: Throwable) {    
                weatherData!!.text = t.message    
            }    
        })    
    }    
    companion object {    
    
        var BaseUrl = "http://api.openweathermap.org/"    
        var AppId = "2e65127e909e178d0af311a81f39948c"    
        var lat = "35"    
        var lon = "139"    
    }    
}

Reference

  1. https://square.github.io/retrofit/ 
  2. https://openweathermap.org/api 
  3. https://developer.android.com/kotlin/ 
If you have any doubt or need any help, contact me.

Download Code:

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

How to create Weather App using Retrofit 2 in Android

weather

Introduction: 

In this article, we will learn How to create our own weather app using Retrofit 2. There are a lot of providers available to provide weather data. In this tutorial we will use the famous provider “OpenWeatherMap” Api to build our own weather app. 

Coding Part: 

I have detailed the article as in the following steps. 
Step 1: Creating New Project with Empty Activity. 
Step 2: Setting up the Retrofit HTTP Library and Manifest. 
Step 3: Getting App ID from Open Weather API. 
Step 4: Implementation of consumption of Weather API using Retrofit.

Step 1: Creating New Project with Empty Activity.

  1. Creating New Project with Android Studio Open Android Studio and Select Create new project. 
  2. Name the project as your wish and select your activity template.

  3. Click “finish” button to create new project in Android Studio.

Step 2: Setting up the Retrofit Http Library and Manifest

In this part, we will see how to setup the library for the project.
  1. Then add the following lines in app level build.gradle file to apply google services to your project.
    dependencies {
        ...
        implementation 'com.squareup.retrofit2:retrofit:2.0.0'
        implementation 'com.squareup.retrofit2:converter-gson:2.0.0' 
    }
  2. Then click “Sync Now” to setup your project.
  3. Don't forget to add the following permission in your manifest file.
    <uses-permission android:name="android.permission.INTERNET"/>

Step 3: Getting App Id from Open Weather Map

  1. Open OpenWeatherMap Site and sign up for free to get your app id.

  2. You can find or create your app id in API Keys tab of the site after logged in. Find the screenshot for your reference.

Step 4: Implementation of consumption of Weather API using Retrofit

The following API link is used to get the current weather report respect to the geo-coordinates. The Sample API link is
https://openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=b6907d289e10d714a6e88b30761fae22
We will see, how to use the link to access the weather data.
  1. Create an interface file named as “WeatherService.java” and add the following lines
    public interface WeatherService {
        @GET("data/2.5/weather?")
        Call getCurrentWeatherData(@Query("lat") String lat, @Query("lon") String lon, @Query("APPID") String app_id);
    }
  2. Create a class file named as “WeatherResponse.java” and add the following lines. We will get the response as json as in the following.
    {
      "coord": {
        "lon": 139,
        "lat": 35
      },
      "sys": {
        "country": "JP",
        "sunrise": 1369769524,
        "sunset": 1369821049
      },
      "weather": [
        {
          "id": 804,
          "main": "clouds",
          "description": "overcast clouds",
          "icon": "04n"
        }
      ],
      "main": {
        "temp": 289.5,
        "humidity": 89,
        "pressure": 1013,
        "temp_min": 287.04,
        "temp_max": 292.04
      },
      "wind": {
        "speed": 7.31,
        "deg": 187.002
      },
      "rain": {
        "3h": 0
      },
      "clouds": {
        "all": 92
      },
      "dt": 1369824698,
      "id": 1851632,
      "name": "Shuzenji",
      "cod": 200
    }
  3. I have used json to java converter in online to generate the Response class and the equivalent java class should be should be shown below.
    public class WeatherResponse {
    
        @SerializedName("coord")
        public Coord coord;
        @SerializedName("sys")
        public Sys sys;
        @SerializedName("weather")
        public ArrayList weather = new ArrayList();
        @SerializedName("main")
        public Main main;
        @SerializedName("wind")
        public Wind wind;
        @SerializedName("rain")
        public Rain rain;
        @SerializedName("clouds")
        public Clouds clouds;
        @SerializedName("dt")
        public float dt;
        @SerializedName("id")
        public int id;
        @SerializedName("name")
        public String name;
        @SerializedName("cod")
        public float cod;
    }
    
    class Weather {
        @SerializedName("id")
        public int id;
        @SerializedName("main")
        public String main;
        @SerializedName("description")
        public String description;
        @SerializedName("icon")
        public String icon;
    }
    
    class Clouds {
        @SerializedName("all")
        public float all;
    }
    
    class Rain {
        @SerializedName("3h")
        public float h3;
    }
    
    class Wind {
        @SerializedName("speed")
        public float speed;
        @SerializedName("deg")
        public float deg;
    }
    
    class Main {
        @SerializedName("temp")
        public float temp;
        @SerializedName("humidity")
        public float humidity;
        @SerializedName("pressure")
        public float pressure;
        @SerializedName("temp_min")
        public float temp_min;
        @SerializedName("temp_max")
        public float temp_max;
    }
    
    class Sys {
        @SerializedName("country")
        public String country;
        @SerializedName("sunrise")
        public long sunrise;
        @SerializedName("sunset")
        public long sunset;
    }
    
    class Coord {
        @SerializedName("lon")
        public float lon;
        @SerializedName("lat")
        public float lat;
    }
    
  4. The SerializedName annotation is used to parsing the server response and their name & type should be same as the Json Response received from the server.
  5. Then initialize Retrofit to call the weather service. The following code snippet will help us to call the service.
    void getCurrentData() {
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BaseUrl)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
            WeatherService service = retrofit.create(WeatherService.class);
            Call call = service.getCurrentWeatherData(lat, lon, AppId);
            call.enqueue(new Callback() {
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    if (response.code() == 200) {
                        WeatherResponse weatherResponse = response.body();
                        assert weatherResponse != null;
    
                        String stringBuilder = "Country: " +
                                weatherResponse.sys.country +
                                "\n" +
                                "Temperature: " +
                                weatherResponse.main.temp +
                                "\n" +
                                "Temperature(Min): " +
                                weatherResponse.main.temp_min +
                                "\n" +
                                "Temperature(Max): " +
                                weatherResponse.main.temp_max +
                                "\n" +
                                "Humidity: " +
                                weatherResponse.main.humidity +
                                "\n" +
                                "Pressure: " +
                                weatherResponse.main.pressure;
    
                        weatherData.setText(stringBuilder);
                    }
                }
    
                @Override
                public void onFailure(@NonNull Call call, @NonNull Throwable t) {
                    weatherData.setText(t.getMessage());
                }
            });
        }
    
    Here we used Gson Converter and so the json response automatically converted to the respective and the converter will compare the response tree with the serialized name.
  6. Our own developed weather app is ready.

Full Code:

You can find the full code implementation of the app here.
public class MainActivity extends AppCompatActivity {

    public static String BaseUrl = "http://api.openweathermap.org/";
    public static String AppId = "2e65127e909e178d0af311a81f39948c";
    public static String lat = "35";
    public static String lon = "139";

    private TextView weatherData;

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

        weatherData = findViewById(R.id.textView);

        Typeface typeface = Typeface.createFromAsset(getAssets(), "Lato-Bold.ttf");
        FontUtils fontUtils = new FontUtils();
        fontUtils.applyFontToView(weatherData, typeface);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getCurrentData();
            }
        });
    }

    void getCurrentData() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BaseUrl)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        WeatherService service = retrofit.create(WeatherService.class);
        Call call = service.getCurrentWeatherData(lat, lon, AppId);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                if (response.code() == 200) {
                    WeatherResponse weatherResponse = response.body();
                    assert weatherResponse != null;

                    String stringBuilder = "Country: " +
                            weatherResponse.sys.country +
                            "\n" +
                            "Temperature: " +
                            weatherResponse.main.temp +
                            "\n" +
                            "Temperature(Min): " +
                            weatherResponse.main.temp_min +
                            "\n" +
                            "Temperature(Max): " +
                            weatherResponse.main.temp_max +
                            "\n" +
                            "Humidity: " +
                            weatherResponse.main.humidity +
                            "\n" +
                            "Pressure: " +
                            weatherResponse.main.pressure;

                    weatherData.setText(stringBuilder);
                }
            }

            @Override
            public void onFailure(@NonNull Call call, @NonNull Throwable t) {
                weatherData.setText(t.getMessage());
            }
        });
    }

}
To know more about Retrofit and Open Weather API
  1. https://openweathermap.org/api
  2. https://square.github.io/retrofit/

Download Code

You can download the full source code of the article in GitHub. If you like this article, do star the repo in GitHub. Hit like the article.

Upload File to Server using Retrofit in Android

Upload file using Retrofit
Hello friends, In this post, I will show you how to upload Image/Video/Any Files to the Server in Android using Retrofit 2. In Retrofit 2 Image or any type of files will be uploaded as Multipart. The File is received using php.

This Code is Updated with Multiple File Upload.

Upload Single File

Web Part:

Create a PHP file named as upload_image.php and paste the following lines.
<?php
$target_dir = "uploads/";
$target_file_name = $target_dir .basename($_FILES["file"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file"])) 
{
   if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file_name)) 
   {
     $success = true;
     $message = "Successfully Uploaded";
   }
   else 
   {
      $success = false;
      $message = "Error while uploading";
   }
}
else 
{
      $success = false;
      $message = "Required Field Missing";
}
$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Project Structure

Create a new Project in Android Studio with the required Specifications.

Codes:

AndroidManifest.xml
Don't forget to add the following permission in your manifest file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
build.gradle
Open your app level build.gradle file add the following lines.
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0' 
    // dependency for Retrofit 2
    compile 'com.squareup.retrofit2:retrofit:2.0.0'
    compile 'com.squareup.retrofit2:converter-gson:2.0.0'
}
AppConfig.java
Create AppConfig.java and replace it with the following lines
class AppConfig {

    private static String BASE_URL = "http://mushtaq.16mb.com/";
    static Retrofit getRetrofit() {
        return new Retrofit.Builder()
                .baseUrl(AppConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
}
ApiConfig.java
Create ApiConfig.java and replace it with the following lines
interface ApiConfig {
    @Multipart
    @POST("retrofit_example/upload_image.php")
    Call uploadFile(@Part MultipartBody.Part file, @Part("file") RequestBody name);
}
ServerResponse.java
Create ServerResponse.java and replace it with the following lines. The Data Names are same as the Names in PHP(for example success and message)
class ServerResponse {

    // variable name should be same as in the json response from php
    @SerializedName("success")
    boolean success;
    @SerializedName("message")
    String message;

    String getMessage() {
        return message;
    }

    boolean getSuccess() {
        return success;
    }

}
activity_main.xml
Create activity_main.xml and Paste the following lines
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:scrollbars="none"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ImageView
            android:id="@+id/preview"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:scaleType="centerCrop"
            android:src="@drawable/placeholder" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="horizontal">

            <Button
                android:id="@+id/pick_img"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="Pick Image" />

            <Button
                android:id="@+id/pick_vdo"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:layout_weight="1"
                android:text="Pick Video" />

        </LinearLayout>

        <Button
            android:id="@+id/upload"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload" />

        <TextView
            android:id="@+id/filename1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 1: " />

        <TextView
            android:id="@+id/filename2"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:padding="5dp"
            android:text="FileName 2: " />

        <Button
            android:id="@+id/uploadMultiple"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Upload Multiple" />
    </LinearLayout>
</ScrollView>

Function to upload file:

// Uploading Image/Video
private void uploadFile() {
    progressDialog.show();

    // Map is used to multipart the file using okhttp3.RequestBody    File file = new File(mediaPath);

    // Parsing any Media type file    RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
    MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
    RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

    ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
    Call call = getResponse.uploadFile(fileToUpload, filename);
    call.enqueue(new Callback() {
    @Override        
    public void onResponse(Call call, Response response) {
            ServerResponse serverResponse = response.body();
            if (serverResponse != null) {
                if (serverResponse.getSuccess()) {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(getApplicationContext(), serverResponse.getMessage(),Toast.LENGTH_SHORT).show();
                }
            } else {
                assert serverResponse != null;
                Log.v("Response", serverResponse.toString());
            }
            progressDialog.dismiss();
        }

        @Override        
        public void onFailure(Call call, Throwable t) {

        }
    });
}

Upload Multiple Files

To Upload Multiple files, I made some changes as in the following.
Create a PHP file named as upload_multiple_files.php and paste the following lines.
<?php
 
$target_dir = "uploads/";
$target_file_name1 = $target_dir.basename($_FILES["file1"]["name"]);
$target_file_name2 = $target_dir.basename($_FILES["file2"]["name"]);
$response = array();

// Check if image file is a actual image or fake image
if (isset($_FILES["file1"])&&isset($_FILES["file2"])) 
{
 if (move_uploaded_file($_FILES["file1"]["tmp_name"], $target_file_name1)
  && move_uploaded_file($_FILES["file2"]["tmp_name"], $target_file_name2)) 
 {
  $success = true;
  $message = "Successfully Uploaded";
 }
 else 
 {
  $success = false;
  $message = "Error while uploading";
 }
}
else 
{
 $success = false;
 $message = "Required Field Missing";
}

$response["success"] = $success;
$response["message"] = $message;
echo json_encode($response);

?>

Function to upload multiple file:

Add the following code to upload multiple files in your activity/fragment
// Uploading Image/Video
 private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }
ApiConfig.java
Add the following interface for uploading multiple files in ApiConfig.java
@Multipart
@POST("retrofit_example/upload_multiple_files.php")
Call <serverresponse> uploadMulFile(@Part MultipartBody.Part file1, @Part MultipartBody.Part file2);

Full Source Code

Create MainActivity.java and Paste the following lines
This Code is Updated with Multiple File Upload.
public class MainActivity extends AppCompatActivity {

    Button btnUpload, btnMulUpload, btnPickImage, btnPickVideo;
    String mediaPath, mediaPath1;
    ImageView imgView;
    String[] mediaColumns = {MediaStore.Video.Media._ID};
    ProgressDialog progressDialog;
    TextView str1, str2;

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

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("Uploading...");

        btnUpload = (Button) findViewById(R.id.upload);
        btnMulUpload = (Button) findViewById(R.id.uploadMultiple);
        btnPickImage = (Button) findViewById(R.id.pick_img);
        btnPickVideo = (Button) findViewById(R.id.pick_vdo);
        imgView = (ImageView) findViewById(R.id.preview);
        str1 = (TextView) findViewById(R.id.filename1);
        str2 = (TextView) findViewById(R.id.filename2);

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

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

        btnPickImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 0);
            }
        });

        // Video must be low in Memory or need to be compressed before uploading...
        btnPickVideo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Video.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(galleryIntent, 1);
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == 0 && resultCode == RESULT_OK && null != data) {

                // Get the Image from data
                Uri selectedImage = data.getData();
                String[] filePathColumn = {MediaStore.Images.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                mediaPath = cursor.getString(columnIndex);
                str1.setText(mediaPath);
                // Set the Image in ImageView for Previewing the Media
                imgView.setImageBitmap(BitmapFactory.decodeFile(mediaPath));
                cursor.close();

            } // When an Video is picked
            else if (requestCode == 1 && resultCode == RESULT_OK && null != data) {

                // Get the Video from data
                Uri selectedVideo = data.getData();
                String[] filePathColumn = {MediaStore.Video.Media.DATA};

                Cursor cursor = getContentResolver().query(selectedVideo, filePathColumn, null, null, null);
                assert cursor != null;
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

                mediaPath1 = cursor.getString(columnIndex);
                str2.setText(mediaPath1);
                // Set the Video Thumb in ImageView Previewing the Media
                imgView.setImageBitmap(getThumbnailPathForLocalFile(MainActivity.this, selectedVideo));
                cursor.close();

            } else {
                Toast.makeText(this, "You haven't picked Image/Video", Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
        }

    }

    // Providing Thumbnail For Selected Image
    public Bitmap getThumbnailPathForLocalFile(Activity context, Uri fileUri) {
        long fileId = getFileId(context, fileUri);
        return MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(),
                fileId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
    }

    // Getting Selected File ID
    public long getFileId(Activity context, Uri fileUri) {
        Cursor cursor = context.managedQuery(fileUri, mediaColumns, null, null, null);
        if (cursor.moveToFirst()) {
            int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Video.Media._ID);
            return cursor.getInt(columnIndex);
        }
        return 0;
    }

    // Uploading Image/Video
    private void uploadFile() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);

        // Parsing any Media type file
        RequestBody requestBody = RequestBody.create(MediaType.parse("*/*"), file);
        MultipartBody.Part fileToUpload = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
        RequestBody filename = RequestBody.create(MediaType.parse("text/plain"), file.getName());

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadFile(fileToUpload, filename);
        call.enqueue(new Callback<serverresponse>() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }

    // Uploading Image/Video
    private void uploadMultipleFiles() {
        progressDialog.show();

        // Map is used to multipart the file using okhttp3.RequestBody
        File file = new File(mediaPath);
        File file1 = new File(mediaPath1);

        // Parsing any Media type file
        RequestBody requestBody1 = RequestBody.create(MediaType.parse("*/*"), file);
        RequestBody requestBody2 = RequestBody.create(MediaType.parse("*/*"), file1);

        MultipartBody.Part fileToUpload1 = MultipartBody.Part.createFormData("file1", file.getName(), requestBody1);
        MultipartBody.Part fileToUpload2 = MultipartBody.Part.createFormData("file2", file1.getName(), requestBody2);

        ApiConfig getResponse = AppConfig.getRetrofit().create(ApiConfig.class);
        Call<serverresponse> call = getResponse.uploadMulFile(fileToUpload1, fileToUpload2);
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call<serverresponse> call, Response<serverresponse> response) {
                ServerResponse serverResponse = response.body();
                if (serverResponse != null) {
                    if (serverResponse.getSuccess()) {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), serverResponse.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                } else {
                    assert serverResponse != null;
                    Log.v("Response", serverResponse.toString());
                }
                progressDialog.dismiss();
            }

            @Override
            public void onFailure(Call<serverresponse> call, Throwable t) {

            }
        });
    }

}

Download Code:

You can download the full source from the following Github link. If you Like this tutorial, Please star it in Github.
    
Download From Github

Post your doubts and comments in the comments section.  

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: