Sunday, October 8, 2017

Image upload in android studio using Retrofit Json Parsing -


Android Gradle(Module App)











MyResponse.java
-------------------

package com.edupointbd.amirul.fileuploaddemo1;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

/** * Created by Amirul on 08-Oct-17. */
public class MyResponse {

    @SerializedName("error")
    @Expose    private Boolean error;
    @SerializedName("message")
    @Expose    private String message;

    public Boolean getError() {
        return error;
    }

    public void setError(Boolean error) {
        this.error = error;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

}









Api.java
---------------

package com.edupointbd.amirul.fileuploaddemo1;

import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.http.Multipart;
import retrofit2.http.POST;
import retrofit2.http.Part;

/** * Created by Amirul on 08-Oct-17. */
public interface Api {
    //the base URL for our API    //make sure you are not using localhost    //find the ip usinc ipconfig command    String BASE_URL = "http://10.0.2.2/ImageUploadApi/";

    //this is our multipart request    //we have two parameters on is name and other one is description    @Multipart    @POST("Api.php?apicall=upload")
    Call<MyResponse> uploadImage(@Part("image\"; filename=\"myfile.jpg\" ") RequestBody file, @Part("desc") RequestBody desc);

}





==================================== 
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:paddingBottom="@dimen/activity_vertical_margin"    android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    tools:context="com.edupointbd.amirul.fileuploaddemo1.MainActivity">

    <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_centerHorizontal="true"        android:layout_centerVertical="true"        android:text="Upload Image" />
</RelativeLayout>


MainActivity.java
------------------

package com.edupointbd.amirul.fileuploaddemo1;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.CursorLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.File;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class MainActivity extends AppCompatActivity {

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(this,
                Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
                    Uri.parse("package:" + getPackageName()));
            finish();
            startActivity(intent);
            return;
        }

        //adding click listener to button        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override            public void onClick(View view) {
                //opening file chooser                Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, 100);
            }
        });
    }

    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == RESULT_OK && data != null) {
            //the image URI            Uri selectedImage = data.getData();

            //calling the upload file method after choosing the file            uploadFile(selectedImage, "amirul");
        }
    }

    private void uploadFile(Uri fileUri, String desc) {

        //creating a file        File file = new File(getRealPathFromURI(fileUri));

        //creating request body for file        RequestBody requestFile = RequestBody.create(MediaType.parse(getContentResolver().getType(fileUri)), file);
        RequestBody descBody = RequestBody.create(MediaType.parse("text/plain"), desc);

        //The gson builder        Gson gson = new GsonBuilder()
                .setLenient()
                .create();


        //creating retrofit object        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(Api.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .build();

        //creating our api        Api api = retrofit.create(Api.class);

        //creating a call and calling the upload image method        Call<MyResponse> call = api.uploadImage(requestFile, descBody);

        //finally performing the call        call.enqueue(new Callback<MyResponse>() {
            @Override            public void onResponse(Call<MyResponse> call, Response<MyResponse> response) {
                MyResponse myResponse =  response.body();
                if (!response.body().getError()) {
                    Toast.makeText(getApplicationContext(),myResponse.getMessage(), Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Some error occurred...", Toast.LENGTH_LONG).show();
                }
            }

            @Override            public void onFailure(Call<MyResponse> call, Throwable t) {
                Toast.makeText(getApplicationContext(), t.getMessage(), Toast.LENGTH_LONG).show();
            }
        });
    }

    /*    * This method is fetching the absolute path of the image file    * if you want to upload other kind of files like .pdf, .docx    * you need to make changes on this method only    * Rest part will be the same    * */    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        CursorLoader loader = new CursorLoader(this, contentUri, proj, null, null, null);
        Cursor cursor = loader.loadInBackground();
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        String result = cursor.getString(column_index);
        cursor.close();
        return result;
    }
}


============================ 




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