Thursday, October 19, 2017

Recycler view and card view in andeoid project

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    
android:layout_width="match_parent"    
android:layout_height="wrap_content"    
android:padding="10dp"    >

   

native add start testing








native add end testing

<android.support.v7.widget.CardView        
android:layout_width="match_parent"        
android:layout_height="75dp"        
android:id="@+id/cv"        >

        
<RelativeLayout            
android:layout_width="match_parent"            
android:layout_height="wrap_content"
            >

            
<ImageView                
android:layout_width="wrap_content"                
android:layout_height="75dp"                
android:id="@+id/bookphoto"                
android:src="@drawable/amirul"                
android:layout_alignParentLeft="true"                
android:layout_alignParentTop="true"                
android:layout_marginRight="16dp"               
 />

            
<TextView                
android:layout_width="wrap_content"                
android:layout_height="wrap_content"                
android:id="@+id/bookname"                
android:text="md amirul islam"                
android:layout_toRightOf="@+id/bookphoto"                
android:layout_alignParentTop="true"                
android:textSize="20sp"                
/>
<TextView                
android:layout_width="wrap_content"                
android:layout_height="wrap_content"                
android:id="@+id/booktitle"                
android:text="25 years old"                
android:layout_toRightOf="@+id/bookphoto"                
android:layout_below="@+id/bookname"              
  />

       
</RelativeLayout>

    
</android.support.v7.widget.CardView>

</LinearLayout>
 

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.edupointbd.amirul.ntcbebook.R;
import com.edupointbd.amirul.ntcbebook.adapter.MyAdapter;
import com.edupointbd.amirul.ntcbebook.model.Books;

import java.util.ArrayList;
import java.util.List;

public class AllBooks extends AppCompatActivity {

    RecyclerView recyclerView;
    MyAdapter myAdapter;
    List<Books>booksList;

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

        recyclerView = (RecyclerView)findViewById(R.id.rvbook);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager llm = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(llm);

        booksList = new ArrayList<>();

        myAdapter = new MyAdapter(new Books().getBooksList());
        recyclerView.setAdapter(myAdapter);




    }

}
<?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_all_books"    android:layout_width="match_parent"    android:layout_height="match_parent"    tools:context="com.edupointbd.amirul.ntcbebook.BookList.AllBooks">

    <android.support.v7.widget.RecyclerView        android:id="@+id/rvbook"        android:layout_width="match_parent"        android:layout_height="wrap_content">

    </android.support.v7.widget.RecyclerView>

</RelativeLayout>
package com.edupointbd.amirul.ntcbebook.model;

import com.edupointbd.amirul.ntcbebook.R;

import java.util.ArrayList;
import java.util.List;

/** * Created by Amirul on 18-Oct-17. */
public class Books {
    private String bookName;
   private String bookTitle;
   private int photoId;

    public Books(String bookName, String bookTitle, int photoId) {
        this.bookName = bookName;
        this.bookTitle = bookTitle;
        this.photoId = photoId;
    }

    private List<Books> booksList;

    public Books() {
        initializeData();
    }

    public void initializeData(){
        booksList = new ArrayList<>();
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));
        booksList.add(new Books("bangla","titile of bangla", R.drawable.amirul));

    }

    public String getBookTitle() {
        return bookTitle;
    }

    public String getBookName() {
        return bookName;
    }

    public int getPhotoId() {
        return photoId;
    }

    public List<Books> getBooksList() {
        return booksList;
    }
}

Tuesday, October 17, 2017

Using Icon in android project

import android.content.Context;
import android.graphics.Typeface;

import java.util.Hashtable;

/** * Created by Amirul on 17-Oct-17. */
public class Icon_Manager {
    private static Hashtable<String, Typeface> cached_icons = new Hashtable<>();
    public static Typeface get_icons(String path, Context context){
        Typeface icon = cached_icons.get(path);
        if(icon == null){
            icon = Typeface.createFromAsset(context.getAssets(),path);
            cached_icons.put(path,icon);
        }
        return icon;
    }
}



Source

How we can rate my app - coding android studio

package com.edupointbd.amirul.ntcbebook;

import android.app.Dialog;import android.content.Context;import android.content.Intent;import android.content.SharedPreferences;import android.graphics.Color;import android.net.Uri;import android.view.View;import android.widget.Button;import android.widget.LinearLayout;import android.widget.TextView;
/** * Created by Amirul on 17-Oct-17. */
public class AppRater {
    private final static String APP_TITLE = "app title";// App Name    private final static String APP_PNAME = "com.edupointbd.";// Package Name
    private final static int DAYS_UNTIL_PROMPT = 3;//Min number of days    private final static int LAUNCHES_UNTIL_PROMPT = 3;//Min number of launches
    public static void app_launched(Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("apprater", 0);
        if (prefs.getBoolean("dontshowagain", false)) { return ; }

        SharedPreferences.Editor editor = prefs.edit();

        // Increment launch counter        long launch_count = prefs.getLong("launch_count", 0) + 1;
        editor.putLong("launch_count", launch_count);

        // Get date of first launch        Long date_firstLaunch = prefs.getLong("date_firstlaunch", 0);
        if (date_firstLaunch == 0) {
            date_firstLaunch = System.currentTimeMillis();
            editor.putLong("date_firstlaunch", date_firstLaunch);
        }

        // Wait at least n days before opening        if (launch_count >= LAUNCHES_UNTIL_PROMPT) {
            if (System.currentTimeMillis() >= date_firstLaunch +
                    (DAYS_UNTIL_PROMPT * 24 * 60 * 60 * 1000)) {
                showRateDialog(mContext, editor);
            }
        }

        editor.commit();
    }

    public static void showRateDialog(final Context mContext, final SharedPreferences.Editor editor) {
        final Dialog dialog = new Dialog(mContext);
        dialog.setTitle("Rate " + APP_TITLE);

        LinearLayout ll = new LinearLayout(mContext);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setBackgroundColor(Color.CYAN);

        TextView tv = new TextView(mContext);
        tv.setText( APP_TITLE + ", আপটি ভাল লাগলে ৫ স্টার দিন। ব্যবহার করার জন্য  ধন্যবাদ ");
        tv.setTextColor(Color.parseColor("#FFC100"));
        tv.setTextSize(16F);
        tv.setWidth(240);
        tv.setPadding(4, 0, 4, 10);

        ll.addView(tv);
        ll.setBackgroundResource(R.color.blue_grey);

        Button b1 = new Button(mContext);
        b1.setText("Rate " + APP_TITLE);
        b1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                mContext.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + APP_PNAME)));
                dialog.dismiss();
            }
        });
        ll.addView(b1);

        Button b2 = new Button(mContext);
        b2.setText("Remind me later");

        b2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        ll.addView(b2);

        Button b3 = new Button(mContext);
        b3.setText("No, thanks");
        b3.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (editor != null) {
                    editor.putBoolean("dontshowagain", true);
                    editor.commit();
                }
                dialog.dismiss();
            }
        });
        ll.addView(b3);

        dialog.setContentView(ll);
        dialog.show();
    }
}



Enter code use it one time. 

AppRater.app_launched(this);

Source: StackOverFlow


Wednesday, October 11, 2017

pdf download from server using progressbar in android studio



package com.edupointbd.amirul.pdfreaderdemo1;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class Testpdf extends AppCompatActivity {

    TextView tv_loading;
    String dest_file_path = "test.pdf";
    int downloadedSize = 0, totalsize;
    String download_file_url = "....................._result.pdf";
    float per = 0;

    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
       // setContentView(R.layout.activity_testpdf);
        tv_loading = new TextView(this);
        setContentView(tv_loading);
        tv_loading.setGravity(Gravity.CENTER);
        tv_loading.setTypeface(null, Typeface.BOLD);
        downloadAndOpenPDF();
    }

    private void downloadAndOpenPDF() {
        new Thread(new Runnable() {
            public void run() {

                try {
                    Uri path = Uri.fromFile(downloadFile(download_file_url));
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(path, "application/pdf");
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                    finish();
                }
                catch (ActivityNotFoundException activityNotFoundException) {
                activityNotFoundException.printStackTrace();

               // throw activityNotFoundException;            } catch (Exception otherException) {
                otherException.printStackTrace();

                throw otherException;
            }
            }
        }).start();

    }

    File downloadFile(String dwnload_file_path) {
        File file = null;
        try {

            URL url = new URL(dwnload_file_path);
            HttpURLConnection urlConnection = (HttpURLConnection) url
                    .openConnection();

            urlConnection.setRequestMethod("GET");
            urlConnection.setDoOutput(true);

            // connect            urlConnection.connect();

            // set the path where we want to save the file            File SDCardRoot = Environment.getExternalStorageDirectory();
            // create a new file, to save the downloaded file            file = new File(SDCardRoot, dest_file_path);

            FileOutputStream fileOutput = new FileOutputStream(file);

            // Stream used for reading the data from the internet            InputStream inputStream = urlConnection.getInputStream();

            // this is the total size of the file which we are            // downloading            totalsize = urlConnection.getContentLength();
            setText("Starting PDF download...");

            // create a buffer...            byte[] buffer = new byte[1024 * 1024];
            int bufferLength = 0;

            while ((bufferLength = inputStream.read(buffer)) > 0) {
                fileOutput.write(buffer, 0, bufferLength);
                downloadedSize += bufferLength;
                per = ((float) downloadedSize / totalsize) * 100;
                setText("Total PDF File size  : "                        + (totalsize / 1024)
                        + " KB\n\nDownloading PDF " + (int) per                        + "% complete");
            }
            // close the output stream when complete //            fileOutput.close();
            setText("Download Complete. Open PDF Application installed in the device.");

        } catch (final MalformedURLException e) {
            setTextError("Some error occured. Press back and try again.",
                    Color.RED);
        } catch (final IOException e) {
            setTextError("Some error occured. Press back and try again.",
                    Color.RED);
        } catch (final Exception e) {
            setTextError(
                    "Failed to download image. Please check your internet connection.",
                    Color.RED);
        }
        return file;
    }

    void setTextError(final String message, final int color) {
        runOnUiThread(new Runnable() {
            public void run() {
                tv_loading.setTextColor(color);
                tv_loading.setText(message);
            }
        });

    }

    void setText(final String txt) {
        runOnUiThread(new Runnable() {
            public void run() {
                tv_loading.setText(txt);
            }
        });

    }

}

Tuesday, October 10, 2017

upload Imge or text by using php and Rest Api... final




FileHandler.php
====================


<?php

class FileHandler
{

    private $con;

    public function __construct()
    {
        require_once dirname(__FILE__) . '/DbConnect.php';

        $db = new DbConnect();
        $this->con = $db->connect();
    }


    public function saveFile($file, $extension, $desc)
    {
        $name = round(microtime(true) * 1000) . '.' . $extension;
        $filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
        move_uploaded_file($file, $filedest);

        $url = $server_ip = gethostbyname(gethostname());

        $stmt = $this->con->prepare("INSERT INTO images (description, image) VALUES (?, ?)");
        $stmt->bind_param("ss", $desc, $name);
        if ($stmt->execute()){
return true;
}
else{
 
   //error !! don't go further
   var_dump($this->db->error);

}
            
        return false;
    }
 public function saveFil($file, $extension, $sname, $phone)
    {
        $name = round(microtime(true) * 1000) . '.' . $extension;
        $filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
        move_uploaded_file($file, $filedest);

        $url = $server_ip = gethostbyname(gethostname());

        $stmt = $this->con->prepare("INSERT INTO image(sname,image,phone) VALUES (?, ?, ?)");
        $stmt->bind_param("sss", $sname, $name,$phone);
        if ($stmt->execute()){
return true;
}
else{
 
   //error !! don't go further
//secho $this->db->error;

}
            
        return false;
    }
//$sname,$email, $phone,$roll,$session,$year,$homedst

 public function saveCSE($file, $extension, $sname, $email, $phone,$roll,$year,$homedst)
    {
        $name = round(microtime(true) * 1000) . '.' . $extension;
        $filedest = dirname(__FILE__) . UPLOAD_PATH . $name;
        move_uploaded_file($file, $filedest);

        $url = $server_ip = gethostbyname(gethostname());

        $stmt = $this->con->prepare("INSERT INTO csestudent(sname,image,email, phone,roll,year,homedst) VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssss", $sname,$name,$email, $phone,$roll,$year,$homedst);
        if ($stmt->execute()){
return true;
}
else{
 
   //error !! don't go further
//echo $this->db->error;

}
            
        return false;
    }
    public function get($phone, $roll)
    {
        $stmt = $this->con->prepare("SELECT phone, roll, image FROM csestudent where phone= $phone || roll= $roll");
        $stmt->execute();
         $stmt->bind_result($phone,$roll,$image);

        $images = array();

        while ($stmt->fetch()) {

            $temp = array();
            $absurl = 'http://' . gethostbyname(gethostname()) . '/ImageUploadApi' . UPLOAD_PATH . $image;
            $temp['phone'] = $phone;
            $temp['roll'] = $roll;
            $temp['image'] = $absurl;
            array_push($images, $temp);
        }

        return $images;
    }
    public function getAllFiles()
    {
        $stmt = $this->con->prepare("SELECT id, description, image FROM images ORDER BY id DESC");
        $stmt->execute();
        $stmt->bind_result($id, $desc, $image);

        $images = array();

        while ($stmt->fetch()) {

            $temp = array();
            $absurl = 'http://' . gethostbyname(gethostname()) . '/ImageUploadApi' . UPLOAD_PATH . $image;
            $temp['id'] = $id;
            $temp['desc'] = $desc;
            $temp['image'] = $absurl;
            array_push($images, $temp);
        }

        return $images;
    }

}

?>

Api.php
==================

<?php


require_once dirname(__FILE__) . '/FileHandler.php';

$response = array();

if (isset($_GET['apicall'])) {
    switch ($_GET['apicall']) {
        case 'upload':

            if (isset($_POST['desc']) && strlen($_POST['desc']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload = new FileHandler();

                $file = $_FILES['image']['tmp_name'];

                $desc = $_POST['desc'];

                if ($upload->saveFile($file, getFileExtension($_FILES['image']['name']), $desc)) {
                    $response['error'] = false;
                    $response['message'] = 'File Uploaded Successfullly';
                }

            } else {
                $response['error'] = true;
                $response['message'] = 'Required parameters are not available';
            }

            break;
case 'uploadimage':

            if (isset($_POST['sname']) && strlen($_POST['sname']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload = new FileHandler();

                $file = $_FILES['image']['tmp_name'];

                $sname = $_POST['sname'];
                $phone = $_POST['phone'];
          

                if ($upload->saveFil($file, getFileExtension($_FILES['image']['name']), $sname, $phone)) {
                    $response['error'] = false;
                    $response['message'] = 'File Uploaded Successfullly';
                }

            } else {
                $response['error'] = true;
                $response['message'] = 'Required parameters are not available';
            }

            break;
case 'csestu':
//$email, $phone,$roll,$session,$year,$homedst

            if (isset($_POST['sname']) && strlen($_POST['sname']) > 0 && $_FILES['image']['error'] === UPLOAD_ERR_OK) {
                $upload = new FileHandler();

                $file = $_FILES['image']['tmp_name'];

                $sname = $_POST['sname'];
                $email = $_POST['email'];
                $phone = $_POST['phone'];
                $roll = $_POST['roll'];
              
                $year = $_POST['year'];
                $homedst = $_POST['homedst'];
$response['check'] = $email.$phone;

                if ($upload->saveCSE($file, getFileExtension($_FILES['image']['name']), $sname, $email, $phone,$roll,$year,$homedst)) {
                   
   $response['error'] = false;
                    $response['message'] = 'File Uploaded Successfullly';
                }

            } else {
                $response['error'] = true;
                $response['message'] = 'Required parameters are not available';
            }

            break;
//get info from server
case 'checkinfo':
// , $phone,$roll

            if (isset($_POST['phone']) && strlen($_POST['phone']) > 0) {
                $upload = new FileHandler();

                $phone = $_POST['phone'];
                $roll = $_POST['roll'];
                
              
             
  
   $response['error'] = false;
                   $response['message'] = $upload->get($phone,$roll);
           
}
            break;


        case 'getallimages':

            $upload = new FileHandler();
            $response['error'] = false;
            $response['images'] = $upload->getAllFiles();

            break;
default:
                $response['error'] = true;
                $response['message'] = 'sory are not available';
break;
    }
}

echo json_encode($response);

function getFileExtension($file)
{
    $path_parts = pathinfo($file);
    return $path_parts['extension'];
}

?>

====================0===================






Constants.php
================

<?php

define('DB_HOST', 'localhost');
define('DB_USER', 'root');
define('DB_PASS', '');
define('DB_NAME', 'imageupload');

define('UPLOAD_PATH', '/uploads/');

?>

DbConnect.php
===========

<?php

class DbConnect
{
    private $con;

    public function connect()
    {
        require_once dirname(__FILE__) . '/Constants.php';

        $this->con = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);

        if (mysqli_connect_errno()) {
            echo 'Failed to connect ' . mysqli_connect_error();
            return null;
        }



        return $this->con;
    }
}

?>





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" />