android.os.NetworkOnMainThreadException当显示来自URL的上传图片时

时间:2015-01-22 07:30:25

标签: android android-asynctask image-uploading android-image networkonmainthread

我制作了一个从设备库或相机上传图片的应用。 因此,我用来实现这一目标的步骤是将图像上传到我的服务器并将图像URL作为返回值,然后使用ImageSpan将图像绘制到EditText中。

我的方案很有效,直到第一步将图片上传到服务器,服务器也将imageURL作为返回值。 问题是当我使用imageURL在EditText中绘制时,我得到android.os.NetworkOnMainThreadException并且我的应用程序关闭。

我使用AysnTask将图像上传到我的服务器,这是代码:

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
    }

}

这是 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;
}

这是显示错误的日志:

enter image description here

我花了很多时间尝试解决这个问题。 那么,有谁可以帮我解决这个问题? 谢谢。

2 个答案:

答案 0 :(得分:0)

是的,您正在主线程中运行网络操作:

in ImageOperations method :

    Object content = url.getContent();

这也是一种网络操作尝试仅在第一个异步任务中写入此行。

答案 1 :(得分:0)

尝试替换

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

        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;
     }

 }