Sun. Dec 16th, 2018

Send images to remote server in android using Volley library

In this tutorial, we will learn, how to send the images to the remote server in an android application using Volley Library. Android app will perform Volley’s POST request to send Images. we are using volley Library because it reduces the complexity to fetch or post images over the network.the main advantage of volley library is, the developer doesn’t need to write lengthy code for accessing the network.We will use WAMP server to communicate with the remote database.

Download APK – [media-downloader media_id=”1482″ texts=”here”]

Download Project – here

Wants to Learn Advanced Android Application development from scratch- Beyond Basics

Step:-1 Configuring Remote Server

  • Download WAMP Server on your PC. Install it and run the Wamp server. if Wamp server logo turns its color to green its ready to use.

  • Now Open the PHPMyAdmin by hitting “http://localhost/phpmyadmin/” in your browser. The username will be “root” and password will be blank. Click “GO”.
  • Create a Database name it “check”, then create a table inside check database. name it images.

  • Table column name will be id, name, email, password as shown in below image.

 

Step:-2 Creating PHP file

  • Open www folder inside C drive > wamp> www.
  • Create a folder inside www. name it “myimage”.
  • Create One more folder where all images from the device will be stored.name it “uploads”
  • Inside user folder, create a file name it index.php.
  • Open Index.php file in Notepad++ Editor. and add the following code inside it.make sure file type must be PHP. and save it.
<?php
 
 if($_SERVER['REQUEST_METHOD']=='POST'){
 
 $image = $_POST['image'];
                
 
$user = "root";
$pass = "";
$host= "localhost";
$dbname="check";
 
$con = mysqli_connect($host,$user,$pass,$dbname);
 
$sql ="SELECT id FROM images ORDER BY id ASC";
 
$res = mysqli_query($con,$sql);
 
$id = 0;
 
 while($row = mysqli_fetch_array($res)){
 $id = $row['id'];
 }
 
 $p = "uploads/$id.png";
 
 $mainpath = "http://192.168.43.87/myimage/$p";
 

 $sql="insert into images(image) values('".$mainpath."');";
 
 
 if(mysqli_query($con,$sql)){
 file_put_contents($p,base64_decode($image));
 echo "Successfully Uploaded";
 }
 
 mysqli_close($con);
 }else{
 echo "Error";
 }

?>

Step 3: – Creating Project & adding Dependencies

Open your Android Studio -> Go to File > New > New project -> Choose BlankActivity > Finish.

Open your app level build.gradle and add following Volley Library dependencies

compile 'com.android.volley:volley:1.0.0'

Step 4: – Add permissions 

  • Add Internet permission in your AndroidManifest.xml file.
<uses-permission android:name="android.permission.INTERNET"/>
  • Add Read/Write External Storage permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

 

Step 5: – Add Layout File

Create or add an XML file inside layout folder name it activity_main.xml. this file contains one Imageview and a Button.

<?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: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.mytrendin.remoteimage.MainActivity">


    <Button
        android:text="Upload Now"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="25dp"
        android:id="@+id/upload"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true" />

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:srcCompat="@mipmap/ic_launcher"
        android:layout_alignParentTop="true"
        android:id="@+id/imageview"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_above="@+id/upload" />
</RelativeLayout>
  • Open Command Prompt and Type “ipconfig” you will get ipv4 Address as shown in below image.

  • In my case server, URL will be
//http://192.168.43.87/path to index.php file

http://192.168.43.87/myimage/index.php

Step 7: –  Create MainActivity.java file

  • Inside MainActivity.java file declare server URL as a string.
String myurl = "http://192.168.43.87/myimage/index.php";
  • Inside MainActivity.java we will check if the version is above or equal to 23. if so ask the user for the permission at runtime. click here for more information about Marshmallow permissions.
if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission()) {
                // Code for above or equal 23 API Oriented Device
                // Your Permission granted already .Do next code
            } else {
                requestPermission();
            }
        }

    }


    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(MainActivity.this, " Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Permission Granted Successfully! ", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied 🙁 ", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }
  • On Image view Click, Phone Gallary will open. for that, we will call showFileChooser Method.
private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }
  • Now in onActivityResult method. we will get the Uri of the image. now Convert that URI to Bitmap.
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                Toast.makeText(this, ""+bitmap, Toast.LENGTH_SHORT).show();
                //Setting the Bitmap to ImageView
                imageview.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
  • Now by Using getStringImage()  method convert that Bitmap to a string.
public String getStringImage(Bitmap bitmap){
        Log.i("MyHitesh",""+bitmap);
        ByteArrayOutputStream baos=new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
        byte [] b=baos.toByteArray();
        String temp=Base64.encodeToString(b, Base64.DEFAULT);


        return temp;
    }
  • Now to upload the image to the server we will call the uploaduserimage method. Create RequestQueue which is used to hold the HTTP Requests. pass the context in RequestQueue.

Related:

send data to remote server using android retrofit Library with PHP MySQL

Send data to remote server in android using Volley library

Loading images from Android Glide Library

Periodically send GPS location to Firebase with custom time frame in Android

Send SMS using Intent

RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
  • HTTP Requests where the response is parsed as a  String. For a POST Request, to add the parameter, a MAP Needs to return and getparam() method needs to be overridden. we will add the image to Map in the form of key-value pair inside getparam() method to send the data to remote server.
public void uploaduserimage(){


        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, myurl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.i("Myresponse",""+response);
                Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Mysmart",""+error);
                Toast.makeText(MainActivity.this, ""+error, Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> param = new HashMap<>();

                String images = getStringImage(bitmap);
                Log.i("Mynewsam",""+images);
                param.put("image",images);
                return param;
            }
        };

          requestQueue.add(stringRequest);


    }

 

Final MainActivity.java file

package com.mytrendin.remoteimage;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
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.ImageView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import static android.R.attr.bitmap;

public class MainActivity extends AppCompatActivity {

    Button upload;
    ImageView imageview;
    private static final int PERMISSION_REQUEST_CODE = 1;
    private static final int PICK_IMAGE_REQUEST= 99;
    Bitmap bitmap;
    String myurl = "http://192.168.43.87/myimage/index.php";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        upload = (Button) findViewById(R.id.upload);
        imageview = (ImageView) findViewById(R.id.imageview);
      //  bitmap = BitmapFactory.decodeResource(getResources(), R.id.imageview);

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

                showFileChooser();
            }
        });

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


        if (Build.VERSION.SDK_INT >= 23) {
            if (checkPermission()) {
                // Code for above or equal 23 API Oriented Device
                // Your Permission granted already .Do next code
            } else {
                requestPermission();
            }
        }

    }


    private void requestPermission() {
        if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            Toast.makeText(MainActivity.this, " Please allow this permission in App Settings.", Toast.LENGTH_LONG).show();
        } else {
            ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
        }
    }

    private boolean checkPermission() {
        int result = ContextCompat.checkSelfPermission(MainActivity.this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (result == PackageManager.PERMISSION_GRANTED) {
            return true;
        } else {
            return false;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case PERMISSION_REQUEST_CODE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(MainActivity.this, "Permission Granted Successfully! ", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(MainActivity.this, "Permission Denied 🙁 ", Toast.LENGTH_LONG).show();
                }
                break;
        }
    }


    private void showFileChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri filePath = data.getData();
            try {
                //Getting the Bitmap from Gallery
                bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
                Toast.makeText(this, ""+bitmap, Toast.LENGTH_SHORT).show();
                //Setting the Bitmap to ImageView
                imageview.setImageBitmap(bitmap);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }






    public void uploaduserimage(){


        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, myurl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                Log.i("Myresponse",""+response);
                Toast.makeText(MainActivity.this, ""+response, Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.i("Mysmart",""+error);
                Toast.makeText(MainActivity.this, ""+error, Toast.LENGTH_SHORT).show();

            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String,String> param = new HashMap<>();

                String images = getStringImage(bitmap);
                Log.i("Mynewsam",""+images);
                param.put("image",images);
                return param;
            }
        };

          requestQueue.add(stringRequest);


    }


    public String getStringImage(Bitmap bitmap){
        Log.i("MyHitesh",""+bitmap);
        ByteArrayOutputStream baos=new  ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG,100, baos);
        byte [] b=baos.toByteArray();
        String temp=Base64.encodeToString(b, Base64.DEFAULT);


        return temp;
    }



}

Step 7: –  Run Application 

  • Now run the application and open table inside phpmyadmin you can see that Image records has been saved successfully.

  • Open Folder(C drive > wamp > www > myimage > uploads). you can see uploaded image there.

 

If You are Beginner Learn Android application development from the scratch


If you really liked the article, please subscribe to our YouTube Channel for videos related to this article.Please find us on Twitter and Facebook.

9 thoughts on “Send images to remote server in android using Volley library

  1. Good day ! I’m making my capstone and your tutorial helps me a lot 😉 I just wanna ask how can I go to a new activity after photo being successfully uploaded ? I hope you can help me figure it out , thanks and more power !:)

  2. Thank you brother, but how to retrieve those images, i have been searching for a long time and i found nothing, please help here.

  3. Hello

    It isn’t working with phone’s large size images (>2MB). Also with smaller images it sends 3 copies of the image.

Leave a Reply

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