Android Upload Image Using Retrofit Library Part 2 || Upload Image to Server

 

Android Upload Image Using Retrofit Library Part 1 || Upload Image to Server

Upload Image Using Retrofit Library :

In continuation to previous tutorial we will be dealing with client side i.e., android app development using the fields specified in the database.

Add retrofit to your project

We need to add retrofit library dependency’s and also check for the latest version and update the dependency’s accordingly.

dependencies {
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
}

 

activity_main.xml

Create a simple UI, so that a user can select a image and the selected image is displayed using a image view also allow user to give a name for the image so that we can save image with the name.

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="20dp"
    tools:context="retrieve.android.com.retrofituploadimage.MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true" />

    <EditText
        android:id="@+id/imgTitle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imageView"
        android:layout_marginTop="20dp"
        android:hint="enter title" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/imgTitle"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp">

        <Button
            android:id="@+id/selectImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Select Image" />

        <Button
            android:id="@+id/uploadImg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_toRightOf="@+id/selectImg"
            android:text="Upload Image" />

    </RelativeLayout>

</RelativeLayout>

 

ApiClient.java

Create a retrofit api client and specify the Base url, Retrofit configurations for Upload Image using Retrofit Library.

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

/**
 * Created by Android on 2/17/2018.
 */

public class ApiClient {

    private static final String BaseUrl = "http://10.0.3.2/ImageUpload/";
    private static Retrofit retrofit;

    public static Retrofit getApiClient() {

        retrofit = new Retrofit.Builder().baseUrl(BaseUrl).
                addConverterFactory(GsonConverterFactory.create()).build();

        return retrofit;
    }
}

 

ApiInterface.java

Api interface with the post parameters include key values.

In the interface we can declare post an get methods to fetch or insert data using json api links.

Also we configure the methods using a model class so that the data is parsed through them and we can use the data directly in our code.

In this example we have used POST parameter to which we have sent image name as title and image path to the respective fields.

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

/**
 * Created by Android on 2/17/2018.
 */

public interface ApiInterface {

    @FormUrlEncoded
    @POST("upload.php")
    Call<Img_Pojo> uploadImage(@Field("image_name") String title, @Field("image") String image);
}

 

Img_Pojo.java

A Pojo file for handling key values and response from the server.

We can generate model classes automatically by making use of json array, its a faster method and also efficient way to parse large json array and also to avoid arrays.

 

import com.google.gson.annotations.SerializedName;

/**
 * Created by Android on 2/17/2018.
 */

public class Img_Pojo {


    @SerializedName("image_name")
    private String Title;

    @SerializedName("image")
    private String Image;


    @SerializedName("response")
    private String Response;

    public String getResponse() {
        return Response;
    }
}

 

MainActivity.java

Initialize all the views required for Upload Image using Retrofit Library

 

imageView = findViewById(R.id.imageView);
selectImg = findViewById(R.id.selectImg);
uploadImg = findViewById(R.id.uploadImg);
imgTitle = findViewById(R.id.imgTitle);

 

Select image from the gallery

private void selectImage() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, IMAGE);
}

 

Convert the selected image we are using JPEG compress format with maintaining a 100 % compress rate but in real time it may reduce to attain storage constraints.

 

private String convertToString()
{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
    byte[] imgByte = byteArrayOutputStream.toByteArray();
    return Base64.encodeToString(imgByte,Base64.DEFAULT);
}

 

After selecting image bind it to image view using onActivityResult

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode== IMAGE && resultCode==RESULT_OK && data!=null)
    {
        Uri path = data.getData();

        try {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

finally upload the image and fetch the response

 

private void uploadImage(){

    String image = convertToString();
    String imageName = imgTitle.getText().toString();
    ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
    Call<Img_Pojo> call = apiInterface.uploadImage(imageName,image);

    call.enqueue(new Callback<Img_Pojo>() {
        @Override
        public void onResponse(Call<Img_Pojo> call, Response<Img_Pojo> response) {

            Img_Pojo img_pojo = response.body();
            Log.d("Server Response",""+img_pojo.getResponse());

        }

        @Override
        public void onFailure(Call<Img_Pojo> call, Throwable t) {
        Log.d("Server Response",""+t.toString());
 }
 });

}

 

Full code :

Providing full code for Upload Image using Retrofit Library

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends AppCompatActivity {

    Bitmap bitmap;
    ImageView imageView;
    Button selectImg,uploadImg;
    EditText imgTitle;
    private  static final int IMAGE = 100;

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

        imageView = (ImageView) findViewById(R.id.imageView);
        selectImg = (Button) findViewById(R.id.selectImg);
        uploadImg = (Button) findViewById(R.id.uploadImg);
        imgTitle = (EditText) findViewById(R.id.imgTitle);


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

                selectImage();

            }
        });

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

                uploadImage();

            }
        });

    }


    private void selectImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(intent, IMAGE);
    }

    private String convertToString()
    {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
        byte[] imgByte = byteArrayOutputStream.toByteArray();
        return Base64.encodeToString(imgByte,Base64.DEFAULT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode== IMAGE && resultCode==RESULT_OK && data!=null)
        {
            Uri path = data.getData();

            try {
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(),path);
                imageView.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadImage(){

        String image = convertToString();
        String imageName = imgTitle.getText().toString();
        ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
        Call<Img_Pojo> call = apiInterface.uploadImage(imageName,image);

        call.enqueue(new Callback<Img_Pojo>() {
            @Override
            public void onResponse(Call<Img_Pojo> call, Response<Img_Pojo> response) {

                Img_Pojo img_pojo = response.body();
                Log.d("Server Response",""+img_pojo.getResponse());

            }

            @Override
            public void onFailure(Call<Img_Pojo> call, Throwable t) {
                Log.d("Server Response",""+t.toString());

            }
        });

    }

}

 

AndroidManifest.xml

Declare internet permission in manifest file to Upload Image using Retrofit Library

<uses-permission android:name="android.permission.INTERNET"/>

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="retrieve.android.com.retrofituploadimage">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

 

[/et_pb_text][et_pb_text admin_label=”Text” background_layout=”light” text_orientation=”left” use_border_color=”off” border_color=”#ffffff” border_style=”solid”]

Output

The below picture depicts the process of Android Upload Image Using Retrofit Library view

Upload Image Retrofit Library

 

If you have any query in this tutorial on Upload Image Retrofit Library do let us know in the comment section below.If you like this tutorial do like and share us for more interesting updates.

Show Buttons
Hide Buttons
Read previous post:
Android Upload Image Using Retrofit Library Part 1 || Upload Image to Server

In this blog on Android Upload Image Using Retrofit Library we will discuss hoe to upload a image onto server...

Close