2

I am referring this code in my project..code snippet. Here i can able to upload one image succesfully..Now i have to upload more than one image..How can i do that one..I did some modification for that code..It is Saving only first image.I want different images to be uploaded. Here is what i have changed..

MainActivity (Modified)

package com.example.test;

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

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

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button buttonUpload;
    private Button buttonChoose;
    private Button buttonChoose1;

    private EditText editText;
    private ImageView imageView;
    private ImageView imageView1;

    public static final String KEY_IMAGE = "image";
    public static final String KEY_IMAGE1 = "image1";
    public static final String KEY_TEXT = "name";
    public static final String UPLOAD_URL = "http://oursite/PhotoUploadWithText/upload.php";

    private int PICK_IMAGE_REQUEST = 1;
    private int PICK_IMAGE_REQUEST1 = 2;

    private Bitmap bitmap;
    private Bitmap bitmap1;

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

        buttonUpload = (Button) findViewById(R.id.buttonUpload);
        buttonChoose = (Button) findViewById(R.id.buttonChooseImage);
        buttonChoose1 = (Button) findViewById(R.id.buttonChooseImage1);

        editText = (EditText) findViewById(R.id.editText);
        imageView = (ImageView) findViewById(R.id.imageView);
        imageView1 = (ImageView) findViewById(R.id.imageView1);

        buttonChoose.setOnClickListener(this);
        buttonChoose1.setOnClickListener(this);
        buttonUpload.setOnClickListener(this);
    }

    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);
    }
          private void showFileChooser1() {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST1);
        }

   @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 {
            bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
           // imageView1.setImageBitmap(bitmap1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
        Uri filePath = data.getData();
        try {
            //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
            //imageView.setImageBitmap(bitmap);
            imageView1.setImageBitmap(bitmap1);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    public String getStringImage(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}

    public String getStringImage1(Bitmap bmp){
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
    byte[] imageBytes = baos.toByteArray();
    String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
    return encodedImage;
}


    public void uploadImage(){
        final String text = editText.getText().toString().trim();
        final String image = getStringImage(bitmap);
        final String image1 = getStringImage1(bitmap1);
        class UploadImage extends AsyncTask<Void,Void,String>{
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(MainActivity.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                Toast.makeText(MainActivity.this,s,Toast.LENGTH_LONG).show();
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                HashMap<String,String> param = new HashMap<String,String>();
                param.put(KEY_TEXT,text);
                param.put(KEY_IMAGE,image);
                param.put(KEY_IMAGE1,image1);
                String result = rh.sendPostRequest(UPLOAD_URL, param);
                return result;
            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }


    @Override
    public void onClick(View v) {
        if(v == buttonChoose){
            showFileChooser();
        }
        if(v == buttonUpload){
            uploadImage();
        }
        if(v == buttonChoose1){
            showFileChooser1();
        }
    }
}

upload.php

if($_SERVER['REQUEST_METHOD']=='POST'){

    $image = $_POST['image'];
    $image1 = $_POST['image1'];
    $name = $_POST['name'];

    define('HOST','hostname');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    $sql ="SELECT id FROM uploads ORDER BY id ASC";

    $res = mysqli_query($con,$sql);

    $id = uniqid();

    while($row = mysqli_fetch_array($res)){
            $id = $row['id'];
    }

    $path = "uploads/$id.png";

    $actualpath = "http://oursite/PhotoUploadWithText/$path";

    $sql = "INSERT INTO uploads (image,image1,name) VALUES ('$actualpath','$actualpath','$name')";

    if(mysqli_query($con,$sql)){
        file_put_contents($path,base64_decode($image));
        file_put_contents($path,base64_decode($image1));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);
}else{
    echo "Error";
}

The same image is selected twice..but only one copy is saved in my uploads folder in server.Thanks for code @belal khan..

1

2 Answers 2

2
+50

Please refer to my answer to the question:

Save multiple image into mysql php from android but only one image get inserted

Edit:

In your PHP sript you are overwriting the image upload because you are using the same upload path for both images.

You must make sure the $path value is unique .

Try this script:

<?php

if($_SERVER['REQUEST_METHOD']=='POST'){

    define('HOST','hostname');
    define('USER','username');
    define('PASS','password');
    define('DB','dbname');

    $con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');

    $path = "uploads/".uniqid().".png";
    $path1 = "uploads/".uniqid().".png";

    $actualpath = "http://oursite/PhotoUploadWithText/$path";
    $actualpath1 = "http://oursite/PhotoUploadWithText/$path1";

    $sql = "INSERT INTO uploads (image,image1,name) VALUES ('$actualpath','$actualpath1','$name')";

    if(mysqli_query($con,$sql)){
        file_put_contents($path,base64_decode($image));
        file_put_contents($path1,base64_decode($image1));
        echo "Successfully Uploaded";
    }

    mysqli_close($con);

}else{
    echo "Error";
}
Sign up to request clarification or add additional context in comments.

5 Comments

Its a type mistake. .in my executable file I have different keys. ..but then also same result.
even i changed $actualpath to unique..but only first image is saving in database..
how can i modify your answer answer to work for my problem..?can u please help me..
@meda..How can i modify the above code to insert only one image..i mean with the above code i have to upload two images mandatory..If i am not selecting the second image and press upload..I am getting java.lang.NullPointerException at these lines. bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos); final String image1 = getStringImage1(bitmap1); and uploadimage(); What might be the issue..how to resolve this one..?can u please help me.
@meda..Can u able to look this one..i dont have much rep to comment anywhere..so i am commenting here...how to save multiple checkbox values to different rows to mysql database
2

You can use $id = uniqid(); in order to get different id for the images.

In your java code, change private int PICK_IMAGE_REQUEST1 = 1; to private int PICK_IMAGE_REQUEST1 = 2;

 @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case PICK_IMAGE_REQUEST:
                if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK & null != data) {
                   Uri filePath = data.getData();
    try {
        bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        //bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        imageView.setImageBitmap(bitmap);
    } catch (IOException e) {
        e.printStackTrace();
    }
                }

                break;

            case PICK_IMAGE_REQUEST1:
                if (requestCode == PICK_IMAGE_REQUEST1 && resultCode == RESULT_OK) {
                    Uri filePath = data.getData();
    try {
        //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        bitmap1 = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
        //imageView.setImageBitmap(bitmap);
        imageView1.setImageBitmap(bitmap1);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
    }

7 Comments

In android part i cant able to select different image...if i select one image in imageview by using buttonchoose..the same image is getting selected for imageview1.
why you have 2 showFileChooser? Both images get from gallery ?
used 2 'showFielChooser' bcz i thought it may require to select different images..
Change private int PICK_IMAGE_REQUEST1 = 1; to private int PICK_IMAGE_REQUEST1 = 2;
now two image is selected..but in my database only first is saving..what could be the problem..?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.