0

I have three list view in Activity A as below

enter image description here

When the submit button is clicked, the text and image path will be saved into MySQL and the image will be stored in PhotoUpload folder.

I'm able to stored 3 text into MySQL but the problem is only one path of the image is saved into MySQL . Between, the image suppose to save inside PhotoUpload but it just save outside the folder !

It totally frustrating !

Activity A

  public void uploadImageAndText(ArrayList<ImageAndText> listItems, final String id) { // Assume id holds value 2 (ts_id)
            JSONArray jsonArray = new JSONArray();
            try {
                for (ImageAndText i : listItems) {
                    JSONObject object = new JSONObject();
                    String type = i.getType();
                    String[] Type = type.split(":");
                    object.put("type", Type[1]);
                    Toast.makeText(getApplicationContext(), Type[1], Toast.LENGTH_LONG).show();
                    String amount = i.getAmount();
                    String[] Amount = amount.split(":");
                    object.put("amount", Amount[1]);
                    String description = i.getDescription();
                    String[] Description = description.split(":");
                    object.put("description", Description[1]);
                    Uri uploadImage = i.getImage();
                    Log.e("Image",uploadImage+"");
                    object.put("image", uploadImage.toString());
                    object.put("ts_id", id);
                    jsonArray.put(object);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            AddStaff ru = new AddStaff(jsonArray);
            ru.execute();

        }

        class AddStaff extends AsyncTask<String, Void, String> {
            ProgressDialog loading;

            JSONArray jsonArray;

            AddStaff(JSONArray jsonArray) {
                this.jsonArray = jsonArray;
            }

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(AddClaims.this, "Please Wait", null, true, true);
            }

            @Override
            protected String doInBackground(String... params) {

                for (int index = 0; index < jsonArray.length(); index++) {
                    try {
                        JSONObject jsonObject = jsonArray.getJSONObject(index);
                        String strUri = jsonObject.getString("image");
                        HashMap<String, String> data = new HashMap<String, String>();
                        data.put("listItems", jsonArray.toString());
                        data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
                        Log.e("AAA",jsonArray.toString());
                        Log.e("String",getStringImage(Uri.parse(strUri)));
                        RequestHandler rh = new RequestHandler();
                        String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
                        return result;
                    } catch (Exception e) {
                    }
                }
                return "";
            }

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


        public String getStringImage(Uri imgUri) {

            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                byte[] imageBytes = baos.toByteArray();
                String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
                return encodedImage;
            } catch (Exception e) {
            }

            return "";
        }
    }

staffBenefit.php

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

        if( !empty( $_POST['listItems'] ) ){

            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";

            $image = $_POST['image'];

            $listItems = json_decode( $_POST['listItems'], true ); 

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

            $id=1;

            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;

            $path=time()."$id.png";
            $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";

            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );

            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'PhotoUpload', '' );
            $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";

            $bytes=file_put_contents( $savepath, base64_decode( $image ) );
            if( !$bytes ){
                echo 'Error saving image';  
            }

            if ( $stmt && $bytes) {
                 foreach( $listItems as $item ){ 

                    $stmt->bind_param('sssss', $item['type'], $item['amount'], $item['description'], $actualpath, $item['ts_id'] );
                    $res=$stmt->execute();
                    if( !$res ) echo 'Query failed with code: '.$stmt->errno;
                } 
            }
            $mysqli->close();
        }
    }
?>

Output

enter image description here

I check the image path and three of them are the same ! And only one image(2.png) saved, and it is outside the PhotoUpload, not inside :(

path problem ? java problem ? or php problem ???

Edited(php)

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

        if( !empty( $_POST['listItems'] ) ){

            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";


            $listItems = json_decode( $_POST['listItems'], true ); 

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

            $id=1;

            $res=$mysqli->query( $sql );
            while( $rs=$res->fetch_object() ) $id=$rs->id;



            $sql="INSERT INTO `staff_benefit` ( `type`, `amount`, `description`, `image`, `ts_id` ) VALUES ( ?, ?, ?, ?, ? )";
            $stmt=$mysqli->prepare( $sql );

            $pathelements=array( realpath( $_SERVER['DOCUMENT_ROOT'] ), 'CRUD', 'UploadPhoto', '' );
            $savepath = realpath( implode( DIRECTORY_SEPARATOR, $pathelements ) ) . "{$id}.png";

            foreach( $listItems as $item ){ 
            $path=time()."$id.png";
            $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";
            $bytes=file_put_contents( $savepath, base64_decode( $item['image'] ) );
            if( !$bytes ){
            echo 'Error saving image';  
             }else{
             $stmt->bind_param('sssss', 
            $item['type'], 
            $item['amount'], 
            $item['description'], 
            $actualpath, 
            $item['ts_id'] );
           $res=$stmt->execute();
        if( !$res ) echo 'Query failed with code: '.$stmt->errno;
    }
} 
            }
            $mysqli->close();
        }

?>

Path

C:\xampp\htdocs\Android\CRUD\UploadPhoto
Tony
  • 2,515
  • 14
  • 38
  • 71
  • I'm confused.. a) you upload 1 image and it will reference this in 3 separate rows in the database? b) or, you upload 3 images and you want there to be 3 separate for each image? – Clay Jan 14 '16 at 09:49
  • @ChrisBanks I have 3 list in my listView. When submit button clicked, they suppose to be saved into MySQL. I upload 3 images but only one image path and image(first image) get saved – Tony Jan 14 '16 at 09:53
  • 1
    @Tony: all images is uploaded in PhotoUpload folder or not? – ρяσѕρєя K Jan 14 '16 at 10:24
  • @ρяσѕρєяK no...I saw 2.png only and it is outside the folder – Tony Jan 14 '16 at 10:42
  • @Tony what are you selecting – meda Jan 14 '16 at 17:33
  • @meda i didn't select anything, I just want to insert – Tony Jan 14 '16 at 17:34
  • 1
    @Tony `SELECT id FROM staff_benefit ORDER BY id ASC` – meda Jan 14 '16 at 17:50
  • @meda I follow [this](https://www.simplifiedcoding.net/android-upload-image-using-php-mysql-android-studio/), the different is I store them using arraylist – Tony Jan 14 '16 at 17:52

1 Answers1

2

First of all you are overwriting the image data in you doInBackground loop.

Second the PHP upload code is not in the loop

JAVA

You should have only one loop, when you build your JSON, put everything you need there

for (ImageAndText i : listItems) {
    JSONObject object = new JSONObject();
    
    String type = i.getType();
    String[] Type = type.split(":");
    String amount = i.getAmount();
    String[] Amount = amount.split(":");
    String description = i.getDescription();
    String[] Description = description.split(":");
    
    //Image
    String image = i.getImage().toString()
    Uri imageUri = Uri.parse(image);
    
    object.put("amount", Amount[1]);
    object.put("type", Type[1]);
    object.put("description", Description[1]);
    object.put("ts_id", id);
    object.put("image", image);
    object.put(Configs.KEY_IMAGE, getStringImage(imageUri));
    
    jsonArray.put(object);
}

Then put the JSON in your hashmap to send

@Override
protected String doInBackground(String... params) {
    try {
        HashMap<String, String> data = new HashMap<String, String>();
        data.put("listItems", jsonArray.toString());
        
        RequestHandler rh = new RequestHandler();
        String result = rh.sendPostRequest(Configs.STAFF_BENEFIT, data);
        return result;
    } catch (Exception e) {
        return "";
    }
}

PHP

The php would change, you won't need $image = $_POST['image'];

You will get the image data from the json $listItems = json_decode( $_POST['listItems'], true );

You would put the upload code in the loop , and insert only on successful upload

foreach( $listItems as $item ){ 
    $path= microtime()."$id.png";
    $actualpath="http://192.168.107.115:80/Android/CRUD/PhotoUpload/$path";
    $bytes=file_put_contents( $savepath, base64_decode( $item['image'] ) );
    if( !$bytes ){
        echo 'Error saving image';  
    }else{
        $stmt->bind_param('sssss', 
        $item['type'], 
        $item['amount'], 
        $item['description'], 
        $actualpath, 
        $item['ts_id'] );
        $res=$stmt->execute();
        if( !$res ) echo 'Query failed with code: '.$stmt->errno;
    }
} 

EDIT:

Full PHP script

<?php
    if( $_SERVER['REQUEST_METHOD']=='POST' ){
        if( !empty( $_POST['listItems'] ) ){
            $listItems = json_decode( $_POST['listItems'], true ); 
            $mysqli = new mysqli("127.0.0.1:3307", "root", "", "androiddb");
            if( $mysqli->connect_errno ) echo "Failed to connect to MySQL";
            $sql="INSERT INTO `staff_benefit` 
                 ( `type`, `amount`, `description`, `image`, `ts_id` ) 
                  VALUES ( ?, ?, ?, ?, ? )";
            if($stmt=$mysqli->prepare($sql )){
                $url="http://192.168.107.115:80/Android/CRUD/PhotoUpload/";
                foreach( $listItems as $item ){ 
                    $image_name = microtime().".png";
                    $save_path = 'PhotoUpload/'.$image_name;
                    $image_url = $url.$image_name;
                    $bytes=file_put_contents($save_path, base64_decode($item['image']));
                    if( !$bytes ){
                        echo 'Error saving image';  
                    }else{
                        $stmt->bind_param('sssss', 
                        $item['type'], 
                        $item['amount'], 
                        $item['description'], 
                        $image_url, 
                        $item['ts_id'] );
                        if( !$res=$stmt->execute()){ 
                            echo 'Query failed with code: '.$stmt->errno;
                        }
                    }
                } 
            }
            $mysqli->close();
        }
    }
?>
meda
  • 45,103
  • 14
  • 92
  • 122
  • I still getting the same result and only the last image get inserted.The image just stored outside the folder – Tony Jan 15 '16 at 01:46
  • @Tony `Log.d("log", "json = " + jsonArray.toString());` what do you see? – meda Jan 15 '16 at 01:47
  • `D/log﹕ json = [{"amount":" ","image":"\/9j\/4AAQSkZJRgABAQAAAQABAAD\/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEB\nAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH\/wAARCAUAAtADASIA\nAhEBAxEB\/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL\/8QAtRAAAgEDAwIEAwUFBAQA\nAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3\nODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWm\n` – Tony Jan 15 '16 at 01:56
  • I can see the image in the folder now, but only one image get saved, and it named 1452823734... – Tony Jan 15 '16 at 02:13
  • @Tony i want to see ur full json produced by the app – meda Jan 15 '16 at 13:53
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100777/discussion-between-meda-and-tony). – meda Jan 15 '16 at 14:28