Thursday , September 16 2021

Upload PDF File to Server in Android with PHP and MySQL – Android Coding by DMTechnolab







import android.os.Bundle;


import android.Manifest;

import android.content.Intent;


import android.database.Cursor;



import android.os.Bundle;

import android.provider.MediaStore;





import android.view.View;

import android.widget.AdapterView;

import android.widget.Button;

import android.widget.EditText;

import android.widget.ImageView;

import android.widget.ListView;

import android.widget.ProgressBar;

import android.widget.Toast;









import net.gotev.uploadservice.MultipartUploadRequest;

import net.gotev.uploadservice.UploadNotificationConfig;



import org.json.JSONArray;

import org.json.JSONException;

import org.json.JSONObject;




import java.util.ArrayList;

import java.util.List;

import java.util.UUID;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {


    //Declaring views

    private Button buttonChoose;

    private Button buttonUpload;


    private EditText editText;


    public static final String UPLOAD_URL = “”;

    public static final String PDF_FETCH_URL = “”;


    ImageView imageView;


    //Image request code

    private int PICK_PDF_REQUEST = 1;


    //storage permission code

    private static final int STORAGE_PERMISSION_CODE = 123;




    //Uri to store the image uri

    private Uri filePath;


    //ListView to show the fetched Pdfs from the server

    ListView listView;


    //button to fetch the intiate the fetching of pdfs.

    Button buttonFetch;


    //Progress bar to check the progress of obtaining pdfs

    ProgressDialog progressDialog;


    //an array to hold the different pdf objects

    ArrayList<Pdf> pdfList= new ArrayList<Pdf>();


    //pdf adapter


    PdfAdapter pdfAdapter;




    protected void onCreate(Bundle savedInstanceState) {




        //Requesting storage permission



        //Initializing views

        buttonChoose = (Button) findViewById(;

        buttonUpload = (Button) findViewById(;


        editText = (EditText) findViewById(;


        //initializing ListView

        listView = (ListView) findViewById(;


        //initializing buttonFetch

        buttonFetch = (Button) findViewById(;


        //initializing progressDialog


        progressDialog = new ProgressDialog(this);


        //Setting clicklistener






        //setting listView on item click listener

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {


            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {



                Pdf pdf = (Pdf) parent.getItemAtPosition(position);

                Intent intent = new Intent();















    * This is the method responsible for pdf upload

    * We need the full pdf path and the name for the pdf in this method

    * */




    public void uploadMultipart() {

        //getting name for the pdf

        String name = editText.getText().toString().trim();


        //getting the actual path of the pdf

        String path = FilePath.getPath(this, filePath);


        if (path == null) {


            Toast.makeText(this, “Please move your .pdf file to internal storage and retry”, Toast.LENGTH_LONG).show();

        } else {

            //Uploading code

            try {

                String uploadId = UUID.randomUUID().toString();


                //Creating a multi part request

                new MultipartUploadRequest(this, uploadId, UPLOAD_URL)

                        .addFileToUpload(path, “pdf”) //Adding file

                        .addParameter(“name”, name) //Adding text parameter to the request

                        .setNotificationConfig(new UploadNotificationConfig())


                        .startUpload(); //Starting the upload


            } catch (Exception exc) {

                Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();






    //method to show file chooser

    private void showFileChooser() {

        Intent intent = new Intent();



        startActivityForResult(Intent.createChooser(intent, “Select Pdf”), PICK_PDF_REQUEST);



    //handling the ima chooser activity result


    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);


        if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

            filePath = data.getData();






    //Requesting permission

    private void requestStoragePermission() {

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)



        if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {

            //If the user has denied the permission previously your code will come to this block

            //Here you can explain why you need this permission

            //Explain here why you need this permission


        //And finally ask for the permission

        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);




    //This method will be called when the user will tap on allow or deny


    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {


        //Checking the request code of our request

        if (requestCode == STORAGE_PERMISSION_CODE) {


            //If permission is granted

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                //Displaying a toast

                Toast.makeText(this, “Permission granted now you can read the storage”, Toast.LENGTH_LONG).show();

            } else {

                //Displaying another toast if permission is not granted

                Toast.makeText(this, “Oops you just denied the permission”, Toast.LENGTH_LONG).show();







    public void onClick(View v) {

        if (v == buttonChoose) {



        if (v == buttonUpload) {










    private void getPdfs() {


        progressDialog.setMessage(“Fetching Pdfs… Please Wait”);;

        StringRequest stringRequest = new StringRequest(Request.Method.POST, PDF_FETCH_URL,


                new Response.Listener<String>() {


                    public void onResponse(String response) {




                        try {

                            JSONObject obj = new JSONObject(response);

                            Toast.makeText(MainActivity.this,obj.getString(“message”), Toast.LENGTH_SHORT).show();


                            JSONArray jsonArray = obj.getJSONArray(“pdfs”);


                            for(int i=0;i<jsonArray.length();i++){


                                //Declaring a json object corresponding to every pdf object in our json Array

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                //Declaring a Pdf object to add it to the ArrayList  pdfList

                                Pdf pdf  = new Pdf();

                                String pdfName = jsonObject.getString(“name”);

                                String pdfUrl = jsonObject.getString(“url”);







                            pdfAdapter=new PdfAdapter(MainActivity.this,R.layout.list_layout, pdfList);






                        } catch (JSONException e) {








                new Response.ErrorListener() {


                    public void onErrorResponse(VolleyError error) {






        RequestQueue request = Volley.newRequestQueue(this);






Source link

About dmtechnolab

Check Also

Simplified Coding

Android ViewModel Unit Test Tutorial – Android Coding by DMTechnolab

Hi guys welcome Android ViewModel Unit Test Tutorial. This post is also part of our …

Leave a Reply

Your email address will not be published. Required fields are marked *