无法在未调用Looper.prepare()错误的线程内创建处理程序

时间:2013-11-18 18:14:52

标签: android multithreading looper

我真的砸了我的脑袋,我根本无法让它工作..请它已经超过2天了......我所得到的只是

Can't create handler inside thread that has not called Looper.prepare()

ImgInt.java 

at

UptSr u = new UptSr();

以下是代码:

ImgInt.java(不是完整代码!)

if(arrPath != null)
{   UptSr u = new UptSr();
    u.doItNow(arrPath[i]);
}

UptSr.java

package com.example.allpicsexample;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import org.json.JSONException;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;

public class UptSr extends Activity {

   // TextView messageText;
  //  Button uploadButton;
    int serverResponseCode = 0;
    ProgressDialog dialog = null;

    String upLoadServerUri = null;

    /**********  File Path *************/
    String uploadFilePath = "";
    String uploadFileName = "";
    String extension;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
      //  setContentView(R.layout.activity_main);

        /************* Php script path ****************/
        upLoadServerUri = "http://listtoomarketing.com/dkh.php";

    }

    public void doItNow(String s){
   //   uploadFile(uploadFilePath)
        uploadFilePath = s;
         new Thread(new Runnable() {
             public void run() {
                  runOnUiThread(new Runnable() {
                         public void run() {
                           //  messageText.setText("uploading started.....");
                         }
                     });                     

                  uploadFile(uploadFilePath + "" + uploadFileName);

             }
           }).start();;
    }

    private static final String ALLOWED_CHARACTERS ="0123456789qwertyuiopasdfghjklzxcvbnm";

    private static String getRandomString(final int sizeOfRandomString)
      {
      final Random random=new Random();
      final StringBuilder sb=new StringBuilder();
      for(int i=0;i<sizeOfRandomString;++i)
        sb.append(ALLOWED_CHARACTERS.charAt(random.nextInt(ALLOWED_CHARACTERS.length())));
      return sb.toString();
      }

    public void uploadFile(String sourceFileUri) {

          Log.i("sourcefile", sourceFileUri); 
          String fileName = sourceFileUri;

          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(sourceFileUri);

          if (!sourceFile.isFile()) {

               dialog.dismiss();

               Log.e("uploadFile", "Source File not exist :"
                                   +uploadFilePath + "" + uploadFileName);

               runOnUiThread(new Runnable() {
                   public void run() {
                 //      messageText.setText("Source File not exist :"
                  //             +uploadFilePath + "" + uploadFileName);
                   }
               });

            //   return 0;

          }
          else
          {
               try {

                     // open a URL connection to the Servlet
                   FileInputStream fileInputStream = new FileInputStream(sourceFile);
                   URL url = new URL("http://listtoomarketing.com/dkh.php");

                   // Open a HTTP  connection to  the URL
                   conn = (HttpURLConnection) url.openConnection();
                   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);

                   // Getting file extension
                   String flname = fileName;
                   String filenameArray[] = flname.split("\\.");
                   extension = filenameArray[filenameArray.length-1];
                   flname = flname.substring(0, flname.lastIndexOf('.'));

                   // Generating randon string to append the original filename

                   fileName = flname + "--" + getRandomString(5) + "." + extension;
                   dos.writeBytes("Content-Disposition: form-data; name='uploaded_file';filename=''" + fileName + "" + lineEnd);

                   dos.writeBytes(lineEnd);

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

                   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){

                       runOnUiThread(new Runnable() {
                            public void run() {
                                // Getting current time
                                SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy_HH:mm:ss");
                                String currentDateandTime = sdf.format(new Date());
                                // Getting file created/modified date                               
                                File file = new File(uploadFilePath);
                                Date lastModDate = new Date(file.lastModified());

                                imginfoposter imginfo = new imginfoposter();
                                try {
                                    imginfo.postData(uploadFilePath, extension, currentDateandTime, lastModDate.toString());
                                } catch (JSONException e) {
                                    // TODO Auto-generated catch block
                                    e.printStackTrace();
                                }

                                String msg = "File Upload Completed.\n\n See uploaded file here : \n\n"
                                              +" http://www.androidexample.com/media/uploads/"
                                              +uploadFileName;

                     //           messageText.setText(msg);
                   //             Toast.makeText(UptSr.this, "File Upload Complete.",
                     //                        Toast.LENGTH_SHORT).show();
                            }
                        });               
                   }   

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

              } catch (MalformedURLException ex) {

                  dialog.dismiss(); 
                  ex.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                  //        messageText.setText("MalformedURLException Exception : check script url.");
                  //        Toast.makeText(UptSr.this, "MalformedURLException",
                    //                                          Toast.LENGTH_SHORT).show();
                      }
                  });

                  Log.e("Upload file to server", "error: " + ex.getMessage(), ex); 
              } catch (Exception e) {

                  dialog.dismiss(); 
                  e.printStackTrace();

                  runOnUiThread(new Runnable() {
                      public void run() {
                //          messageText.setText("Got Exception : see logcat ");
                 //         Toast.makeText(UptSr.this, "Got Exception : see logcat ",
                  //                Toast.LENGTH_SHORT).show();
                      }
                  });
                  Log.e("Upload file to server Exception", "Exception : "
                                                   + e.getMessage(), e); 
              }
           //   dialog.dismiss();      
           //   return serverResponseCode;

           } // End else block
         }
}

logcat的:

11-18 23:40:48.459: W/System.err(12223): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
11-18 23:40:48.479: W/System.err(12223):    at android.os.Handler.<init>(Handler.java:121)
11-18 23:40:48.489: W/System.err(12223):    at android.app.Activity.<init>(Activity.java:680)
11-18 23:40:48.489: W/System.err(12223):    at com.example.allpicsexample.UptSr.<init>(UptSr.java:25)
11-18 23:40:48.499: W/System.err(12223):    at com.example.allpicsexample.ImgInt$ImgIntex.doInBackground(ImgInt.java:93)
11-18 23:40:48.499: W/System.err(12223):    at com.example.allpicsexample.ImgInt$ImgIntex.doInBackground(ImgInt.java:1)
11-18 23:40:48.509: W/System.err(12223):    at android.os.AsyncTask$2.call(AsyncTask.java:185)
11-18 23:40:48.509: W/System.err(12223):    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
11-18 23:40:48.519: W/System.err(12223):    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
11-18 23:40:48.529: W/System.err(12223):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
11-18 23:40:48.529: W/System.err(12223):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
11-18 23:40:48.529: W/System.err(12223):    at java.lang.Thread.run(Thread.java:1019)

0 个答案:

没有答案