0

I make an app which upload image from device gallery or from camera. So, the step I use to achieve that, is by uploading the image into my server and give image URL as return value, and then by using ImageSpan I draw the image into EditText.

My scenario works well until step I upload the picture into server, and the server also give imageURL as return value. The problem is when I use that imageURL to draw in EditText, I get android.os.NetworkOnMainThreadException and my app close.

I use AysnTask to upload images into my server and this is the code :

private class UploadFileToServer extends AsyncTask<Void, Integer, String> {

    @Override
    protected void onPreExecute() {
        progressBar.setProgress(0);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... progress) {
        // Making progress bar visible
        progressBar.setVisibility(View.VISIBLE);
        txtPercentage.setVisibility(View.VISIBLE);
        progressBar.setProgress(progress[0]);
        txtPercentage.setText("Uploading... ");
    }

    @Override
    protected String doInBackground(Void... params) {
        return uploadFile();
    }

    @SuppressWarnings("deprecation")
    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(DeveloperKey.FILE_UPLOAD_URL);

        String boundary = "---------------------------This is the boundary";
        httppost.addHeader("entype", "multipart/form-data ; boundary="+ boundary);

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                new ProgressListener() {

                    @Override
                    public void transferred(long num) {
                        publishProgress((int) ((num / (float) totalSize) * 100));
                    }
                });

            File sourceFile = new File(filePath);

            entity.addPart("data", new FileBody(sourceFile));

            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                responseString = EntityUtils.toString(r_entity);                
            } else {
                responseString = "Error occurred! Http Status Code: "+ statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;
    }

    @Override
    protected void onPostExecute(String result) {
        Log.e(TAG, "Response from server: " + result);

        txtPercentage.setVisibility(View.GONE);
        progressBar.setVisibility(View.GONE);

        DrawUploadImage(result); //Part that I use to draw image into EditText
    }

}

and this is the code for DrawUploadImage :

private void DrawUploadImage(String message){

    SplitFile = message.replaceAll("https://articlephoto.s3.amazonaws.com/opini3_question_image/", "");
    int cursorPosition = editor.getSelectionStart();
    editor.getText().insert(cursorPosition, SplitFile);
    SpannableStringBuilder ssb = new SpannableStringBuilder(editor.getText());
    Drawable img = ImageOperations(this, message, SplitFile+".jpg");
    img.setBounds(0, 0, img.getIntrinsicWidth()/2, img.getIntrinsicHeight()/2);
    ssb.setSpan(new ImageSpan(img, ImageSpan.ALIGN_BASELINE), cursorPosition,  cursorPosition+2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    editor.setText(ssb, BufferType.SPANNABLE);
    editor.setSelection(cursorPosition+2);

}

private Drawable ImageOperations(Context ctx, String url, String saveFilename) {
    try {
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

public Object fetch(String address) throws MalformedURLException,IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
}

and this is the log that show error :

enter image description here

I have spend much time try to solve this problem. So, anyone can help me to solve this? Thank you.

cakduro
  • 180
  • 2
  • 13

2 Answers2

0

yes you are running Network operation in main thread that is:

in ImageOperations method :

    Object content = url.getContent();

this is also one kind of network operation try to write this line in first async task only.

Rathan Kumar
  • 2,567
  • 2
  • 17
  • 24
0

try replace

public Object fetch(String address) throws MalformedURLException,IOException {
    URL url = new URL(address);
    Object content = url.getContent();
    return content;
} 

with

        public Object fetch(String address) throws MalformedURLException,IOException {

        Object content=new GetContent().execute(address).get(); 
        return content;
      } 


       class GetContent extends AsyncTask<String, String, Object> {

      @Override
      protected Object doInBackground(String... aurl) {
        URL url = new URL(aurl[0]);
        Object content = url.getContent();
        return content;
     }

 }
raj
  • 2,088
  • 14
  • 23