不幸的是,应用程序关闭了AsyncTask中的FATAL EXCEPTION

时间:2014-03-14 07:28:18

标签: java android android-asynctask

我试图将图像从我的应用程序上传到php服务器。 上传过程正常但上传后#34;不幸的是App Closes"我不明白问题出在哪里。

从我的片段类I调用im_up.execute(path)并实现了一个名为AsyncResponse的接口,它有一个processFinish(String output)方法将数据从AsyncTask传递到我的片段类

public class UploadImage extends AsyncTask<Void, Void, String> {
    int serverResponseCode = 0;
    ProgressDialog dialog = null;
    public AsyncResponse delegate=null;
    String path;
    public UploadImage(String pathUri,Context mcontext) {
        // TODO Auto-generated constructor stub
        path=pathUri;
        ctx=mcontext;
        dialog = ProgressDialog.show(ctx,"Loading","Plaease Wait",true);

    }

    protected String doInBackground(Void... params) {
        // TODO Auto-generated method stub
        String upLoadServerUri = "http://www.pinnacle2k14.com/letsmeet/upload.php";
        String fileName =path;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;  
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024; 
        File sourceFile = new File(path); 
        if (!sourceFile.isFile()) {
         Log.e("uploadFile", "Source File Does not exist");
         return "0";
        }
            try { // open a URL connection to the Servlet
             FileInputStream fileInputStream = new FileInputStream(sourceFile);
             URL url = new URL(upLoadServerUri);
             conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
             conn.setDoInput(true); // Allow Inputs
             conn.setDoOutput(true); // Allow Outputs
             conn.setUseCaches(false); // Don't use a Cached Copy
             conn.setRequestMethod("POST");
             conn.setRequestProperty("Connection", "Keep-Alive");
             conn.setRequestProperty("ENCTYPE", "multipart/form-data");
             conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
             conn.setRequestProperty("uploaded_file", fileName); 
             dos = new DataOutputStream(conn.getOutputStream());

             dos.writeBytes(twoHyphens + boundary + lineEnd); 
             dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
             dos.writeBytes(lineEnd);

             bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size

             bufferSize = Math.min(bytesAvailable, maxBufferSize);
             buffer = new byte[bufferSize];

             // read file and write it into form...
             bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

             while (bytesRead > 0) {
               dos.write(buffer, 0, bufferSize);
               bytesAvailable = fileInputStream.available();
               bufferSize = Math.min(bytesAvailable, maxBufferSize);
               bytesRead = fileInputStream.read(buffer, 0, bufferSize);               
              }

             // send multipart form data necesssary after file data...
             dos.writeBytes(lineEnd);
             dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

             // Responses from the server (code and message)
             serverResponseCode = conn.getResponseCode();
             String serverResponseMessage = conn.getResponseMessage();

             Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
             if(serverResponseCode == 200){
                 Log.i("response", "File Upload complete");
                 //Toast.makeText(getActivity(), "File Upload Complete.", Toast.LENGTH_SHORT).show();


             }    

             //close the streams //
             fileInputStream.close();
             dos.flush();
             dos.close();

        } catch (MalformedURLException ex) {  
            dialog.dismiss();  
            ex.printStackTrace();
            Log.i("response", "MalformedURLException");
            //Toast.makeText(getActivity(), "MalformedURLException", Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
        } catch (Exception e) {
            dialog.dismiss();  
            e.printStackTrace();
            Log.i("response", e.toString());
            //Toast.makeText(getActivity(), "Exception : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e);  
        }
        dialog.dismiss();       
        //return serverResponseCode;  

        return "hello";
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
            dialog.dismiss();
        delegate.processFinish(result);

    }

}
片段中的

UploadImage up_im=new UploadImage(getRealPathFromURI(path),getActivity());
                up_im.delegate=this;
                up_im.execute();

2 个答案:

答案 0 :(得分:1)

问题是 dialog.dismiss()行。你无法从并行线程触摸Android UI。它应该只在UI线程中完成,即主线程。

&#34;不要从UI线程外部访问Android UI工具包&#34;

将该行移至onPostExecute()或从那里删除。

答案 1 :(得分:1)

你应该在onPostExecute()方法中删除你的对话框。

dialog.dismiss();


@Override
protected void onPostExecute(String result) {
    // TODO Auto-generated method stub
    super.onPostExecute(result);
    dialog.dismiss();
    delegate.processFinish(result);
}

你刚刚声明了你的变量

 ProgressDialog dialog = null;

我看不出它已被初始化。所以按

初始化它
dialog = ProgressDialog.show(getActivity(),"Loading","Plaease Wait",true);

更新:

制作全局变量

 Context ctx;

现在从

更改构造函数
  public UploadImage(String pathUri) {
    // TODO Auto-generated constructor stub
    path=pathUri;
  }

   public UploadImage(Context mContext ,String pathUri) {
    // TODO Auto-generated constructor stub
    ctx = mContext;
    path = pathUri;

   }

现在将此ctx变量传递给ProgressDialog上下文,以便更改

   dialog = ProgressDialog.show(ctx,"Loading","Plaease Wait",true);