1

Getting Response as Response ID 525295 is not served in this process

 RequestQueue queue = Volley.newRequestQueue(HomeScreen.this);

//Create your body
  JSONObject jsonRequest = new JSONObject();
            try {
                jsonRequest.put("photo_one", byteArrayToHexString(imageByteArray1));
                jsonRequest.put("photo_two", byteArrayToHexString(imageByteArray2));
                jsonRequest.put("photo_three", byteArrayToHexString(imageByteArray3));
                jsonRequest.put("product_titile", mTitle.getText().toString());
                jsonRequest.put("product_description", mDiscription.getText().toString());
                jsonRequest.put("location", mAddress.getText().toString());
                jsonRequest.put("name", mPername.getText().toString());
                jsonRequest.put("mobile", mPerMobile.getText().toString());
            } catch (JSONException e) {
                Log.i("Exception", e.toString());
            }

            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, URL, jsonRequest, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.v("Response", response.toString());
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.v("Error", error.getMessage());
                }
            }){
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();

                    headers.put("Content-Type", "application/json; charset=utf-8");

                    return headers;
                }
            };

                //Add request to queue
                queue.add(jsonObjectRequest);

@NonNull
private static String byteArrayToHexString (byte[] a) {
    StringBuilder sb = new StringBuilder(a.length * 2);
    for (byte b : a)
        sb.append(String.format("%02x", b & 0xff));
    return sb.toString();
}

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

    if (resultCode == RESULT_OK && data != null) {
        filePaths = data.getStringArrayListExtra(FilePickerConst.KEY_SELECTED_MEDIA);
        Spacecraft s;
        ArrayList<Spacecraft> spacecrafts = new ArrayList<>();
        //Uri filePath = data.getData();
        try {
            for (String path : filePaths) {
                s = new Spacecraft();
                s.setName(path.substring(path.lastIndexOf("/") + 1));
                Log.v("image", path);
                s.setUri(Uri.fromFile(new File(path)));
                spacecrafts.add(s);
                //bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), Uri.parse(path));
            }
            gv.setAdapter(new CustomAdapter(this, spacecrafts));
            Toast.makeText(HomeScreen.this, "Total = " + String.valueOf(spacecrafts.size()), Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            e.printStackTrace();
        }

        imageString = filePaths.get(0);
        Log.v("newimagestring",imageString);
        imageString2 = filePaths.get(1);
        Log.v("newimagestring",imageString2);
        imageString3 = filePaths.get(2);
        Log.v("newimagestring",imageString3);


        File image1 = new File(imageString);
        BitmapFactory.Options bmOptions1 = new BitmapFactory.Options();
        Bitmap bitmap1 = BitmapFactory.decodeFile(image1.getAbsolutePath(),bmOptions1);
        ByteArrayOutputStream stream1 = new ByteArrayOutputStream();
        bitmap1.compress(Bitmap.CompressFormat.PNG, 100, stream1);
        imageByteArray1 = stream1.toByteArray();

        File image2 = new File(imageString2);
        BitmapFactory.Options bmOptions2 = new BitmapFactory.Options();
        Bitmap bitmap2 = BitmapFactory.decodeFile(image2.getAbsolutePath(),bmOptions2);
        ByteArrayOutputStream stream2 = new ByteArrayOutputStream();
        bitmap2.compress(Bitmap.CompressFormat.PNG, 100, stream2);
        imageByteArray2 = stream2.toByteArray();

        File image3 = new File(imageString3);
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap3 = BitmapFactory.decodeFile(image3.getAbsolutePath(),bmOptions);
        ByteArrayOutputStream stream3 = new ByteArrayOutputStream();
        bitmap3.compress(Bitmap.CompressFormat.PNG, 100, stream3);
        imageByteArray3 = stream3.toByteArray();

    }
}

This is the Response,

D/QcrilMsgTunnelSocket: Response ID 525295 is not served in this process. D/QcrilMsgTunnelSocket: Response ID 525295 is not served in this process. W/Analytics-Core-ConfigServer: HttpResponse is empty. W/Analytics-Core-ConfigServer: HttpResponse is empty. D/QcrilMsgTunnelSocket: Response ID 525295 is not served in this process. D/com.xiaomi.common.Network: Http POST Response Code: 503

R.H
  • 318
  • 2
  • 12
  • Instead of send images array in single key(variable) – Piyush Aug 17 '17 at 07:39
  • @Piyush As I mentioned earlier, I am still beginner, it would be helpful if you send program or link where i can understand what you said. – R.H Aug 17 '17 at 07:45

4 Answers4

0

here is a Trick you can do!

  1. when you are selecting image one by one Upload it at that time and save the response Path.
  2. now attach the path to the JSON you are sending.

  3. ultimately you gonna save url in Database.

xbadal
  • 1,284
  • 2
  • 11
  • 24
  • I mentioned earlier, I am still beginner, it would be helpful if you send program or link where i can understand what you said – R.H Aug 17 '17 at 08:28
0

First download httpmime-4.1-beta1.jar file then add it as library. see here

Now declare ArrayList<Filepath> filepath = new ArrayList<>(); in your Activity and paste the below code

Note: filepath will hold your Imagepaths.

class ImageUploadTask extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showProgressDialog();
        }

        @Override
        protected String doInBackground(String... param) {
            try {
                HttpClient httpClient = new DefaultHttpClient();
                HttpContext localContext = new BasicHttpContext();
                HttpPost httpPost = new HttpPost(url);
                final String basicAuth = "Basic " + Base64.encodeToString("admin:123456".getBytes(), Base64.NO_WRAP);
                httpPost.setHeader("Authorization", basicAuth);
                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                ArrayList<Filepath> filepath = mCarApplication.getArrayListForImagePath();
//                for (int i = 0; i < filepath.size(); i++) {
//                    System.out.println("!!path " + filepath.get(i).getFilepath());
//                    entity.addPart("file" + String.valueOf(i), new FileBody(new File(filepath.get(i).getFilepath())));
//                }

                entity.addPart("file1", new FileBody(new File(filepath.get(0).getFilepath())));
                if (filepath.size() >= 2) {
                    entity.addPart("file2", new FileBody(new File(filepath.get(1).getFilepath())));
                }
                if (filepath.size() >= 3) {
                    entity.addPart("file3", new FileBody(new File(filepath.get(2).getFilepath())));
                }
                if (filepath.size() >= 4) {
                    entity.addPart("file4", new FileBody(new File(filepath.get(3).getFilepath())));
                }
                if (filepath.size() >= 5) {
                    entity.addPart("file5", new FileBody(new File(filepath.get(4).getFilepath())));
                }
                if (filepath.size() >= 6) {
                    entity.addPart("file6", new FileBody(new File(filepath.get(5).getFilepath())));
                }
                entity.addPart("user_id", new StringBody(application.getUserid()));


                httpPost.setEntity(entity);

                HttpResponse response;
                response = httpClient.execute(httpPost);
                resEntity = response.getEntity();


                final String response_str = EntityUtils.toString(resEntity);
                Log.e("!!TAG12", "Response " + response_str);
                return response_str;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }



        @Override
        protected void onPostExecute(String sResponse) {
            dismissProgressDialog();
            if (sResponse != null) {
                // Your code

            }
        }
    }
new ImageUploadTask().execute(); call it when you want to upload files.

your Filepath class should be:

public class Filepath {
    private String filepath;
    private int position;

    public Filepath(String filepath, int position) {
        this.filepath = filepath;
        this.position = position;
    }

    public void setFilepath(String filepath) {
        this.filepath = filepath;
    }

    public String getFilepath() {
        return this.filepath;
    }

    public void setPosition(int position) {
        this.position = position;
    }

    public int getPosition() {
        return this.position;
    }

}
user7439667
  • 144
  • 8
0

Why don't you try to encrypt your image as a byte array, and send it as a string to your server using a HTTP POST method with JSON body ?

To encrypt your image use:

Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageByteArray1 = stream.toByteArray();

Then create your JSON string, something like:

{ 
  "photo_one":byteArrayToHexString(imageByteArray1), 
  "photo_two":byteArrayToHexString(imageByteArray2),
  "photo_three":byteArrayToHexString(imageByteArray3),
  "product_title":"PRODUCT_TITLE",
  "product_description":"PRODUCT_DESCRIPTION",
  "location":"LOCATION",  
  "name":"NAME",
  "mobile":"MOBILE",
  ...
}

Where the method byteArrayToHexString converts the byte array to HEX string:

    public static String byteArrayToHexString(byte[] a) {
        StringBuilder sb = new StringBuilder(a.length * 2);
        for(byte b: a)
            sb.append(String.format("%02x", b & 0xff));
        return sb.toString();
    }

Now, HTTP POST the JSON body to your web service. There are many methods but the easier one is using the Volley library and it is done like this:

    RequestQueue queue = Volley.newRequestQueue(this);

    //Create your body
    JSONObject jsonRequest = new JSONObject();

    try {
        jsonRequest.put("photo_one", byteArrayToHexString(imageByteArray1));
        ...
    } catch (JSONException e) {
        Log.i("Exception", e.toString())
    }

    url = "YOUR_URL";
    //Create your request
    StringRequest postRequest = new StringRequest(Request.Method.POST, url, body, new Response.Listener<String>() 
    {
        @Override
        public void onResponse(String response) {
            // response
            Log.d("Response", response);
        }
    }, 
    new Response.ErrorListener() 
    {
         @Override
         public void onErrorResponse(VolleyError error) {
             // error
             Log.d("Error.Response", response);
       }
    }
    ) {     
    @Override
        public Map<String, String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers = new HashMap<String, String>();

            headers.put("Content-Type", "application/json; charset=utf-8");

            return headers;
        }
    };

    //Add request to queue
    queue.add(postRequest);

Finally, when you get back your data simply decode the byte array into a Bitmap as:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

EDIT 1:

To use the voley library simply add this line to your APP build.gradle in the dependencies section:

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

EDIT 2:

To convert the image file from a path use the following:

File image = new File(YOUR_PATH_TO_IMAGE);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);

Hope it helps :)

kodartcha
  • 1,063
  • 12
  • 23
  • Thanks for reply. I choose 3 images in single press of button and paste it in gridview. So in activity for result i get 3 filepaths. But how to pass those here Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher); – R.H Aug 17 '17 at 09:19
  • Check the EDIT 2 on my answer. – kodartcha Aug 17 '17 at 09:28
  • EDIT 2 modified again! – kodartcha Aug 17 '17 at 09:33
  • So, now i have to call Edit 2 program 3 times and store it in byte[] imageByteArray1 = stream.toByteArray(); right? – R.H Aug 18 '17 at 06:07
  • I tried, but don't know what i am doing wrong, for clarification i cannot put the code here in comments, so how to show you the code? – R.H Aug 18 '17 at 06:52
0

I faced exactly the same problem and then used a library to solve this. it's very easy. Only two steps:

  • Add library to the project

    compile 'net.gotev:uploadservice:3.0'
    
  • This code for sending data:

     try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(getApplicationContext(), uploadId, APIAddresses.save_record_url)
                .addFileToUpload(ImagePath1, "photo_one")
                .addFileToUpload(ImagePath2, "photo_two")
                .addFileToUpload(ImagePath3, "photo_three")
                .addParameter("product_title","title")
                .addParameter("product_description","description)
                .addParameter("location","location)
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(2)
                .setDelegate(new UploadStatusDelegate() {
                    @Override
                    public void onProgress(UploadInfo uploadInfo) {
                        progressDialog.show();
                    }
    
                    @Override
                    public void onError(UploadInfo uploadInfo, Exception exception) {
    
                    }
    
                    @Override
                    public void onCompleted(UploadInfo uploadInfo, ServerResponse serverResponse) {
                        progressDialog.dismiss();
                        finish();
                        System.out.println(serverResponse);
    
                    }
    
                    @Override
                    public void onCancelled(UploadInfo uploadInfo) {
    
                    }
                })
                .startUpload();
    
    
    } catch (Exception exc) {
        UtilityMethods.showToast(this,exc.getMessage());
    }
    

The code is very simple and self-explanatory, so I don't think i need to explain how is it working. Add as many images and parameters. Give it a try, vote it up if it works. I don't have the link to the library now. You can search on google may be you find it.

Good luck!

The Bat
  • 1,085
  • 1
  • 13
  • 31
  • Thanks for reply,I may bit sound silly for you but I Still have some doubts, String uploadId = UUID.randomUUID().toString(); ---- What is this sentence used for? And where do I need to put URL? – R.H Aug 18 '17 at 06:11
  • @R.H Okay.. so if you see the third line, it has 3 parameters. `new MultipartUploadRequest(getApplicationContext(), uploadId, APIAddresses.save_record_url) ` The first parameter is context, second is uploadid (the answer for your first doubt) and third is url (the answer for your second doubt) – The Bat Aug 18 '17 at 12:54