2014-02-20 105 views
0

我是新来的android编程。所以我正在学习一些教程。我正尝试将图像上传到php服务器。我按照这个教程http://monstercoda.wordpress.com/2012/04/15/android-image-upload-tutorial-part-i/将图片上传到服务器上Android

一切正常,但唯一的问题是我不知道在哪里写这个代码和在哪个方法。

HttpUploader uploader = new HttpUploader(); 
try { 
    String image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();   
} catch (InterruptedException e) { 
    e.printStackTrace(); 
} catch (ExecutionException e) { 
    e.printStackTrace(); 
} 

我试图在我的MainActivity的onCreate方法或我的MainUploader类,但应用程序崩溃写这个代码。如果我不写这个代码的应用程序的作品,但显然我不能够执行完整的功能。

这里我写了这个代码,这会导致应用程序崩溃

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    HttpUploader uploader = new HttpUploader(); 
    try { 
     image_name = uploader.execute(getRealPathFromURI(currImageURI)).get(); 
    } catch (InterruptedException e) { 
     e.printStackTrace(); 
    } catch (ExecutionException e) { 
     e.printStackTrace(); 
    } 
    Button upload_btn = (Button) this.findViewById(R.id.uploadButton); 
} 

请告诉我在哪里我可以把上面的代码。

+0

可以发布堆栈跟踪,即崩溃后得到的错误日志。 – Diffy

回答

1

你不能在onCreate()中运行此代码我猜,因为你还没有你的图片集的URI。 在使用Get Content Intent进行浏览之后,您将获得该URI,因此必须在此之后执行HttpUploader。

的一种可能的解决办法是把那HttpUploader代码到onActivityResult()获得的真实路径后, 所以后:

currImageURI = data.getData();

编辑:在的AsyncTask或Java线程

// To handle when an image is selected from the browser 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
if (resultCode == RESULT_OK) { 
    if (requestCode == 1) { 
    // currImageURI is the global variable I’m using to hold the content: 
     currImageURI = data.getData(); 
     System.out.println(“Current image Path is ----->” + 
         getRealPathFromURI(currImageURI)); 
     TextView tv_path = (TextView) findViewById(R.id.path); 
     tv_path.setText(getRealPathFromURI(currImageURI)); 

     try{ 
      HttpUploader uploader = new HttpUploader(); 
      image_name = uploader.execute(getRealPathFromURI(currImageURI)).get();  
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
} 
} 
+0

非常感谢 – hellosheikh

4

使用后上传

public void onCreate(Bundle icicle) { 
     super.onCreate(icicle); 
     setContentView(R.layout.main); 

     Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.icon);   ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
     bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream); //compress to which format you want. 
     byte [] byte_arr = stream.toByteArray(); 
     String image_str = Base64.encodeBytes(byte_arr); 
     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 

     nameValuePairs.add(new BasicNameValuePair("image",image_str)); 

     Thread t = new Thread(new Runnable() { 

     @Override 
     public void run() { 
       try{ 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://10.0.2.2/Upload_image_ANDROID/upload_image.php"); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
        HttpResponse response = httpclient.execute(httppost); 
        String the_string_response = convertResponseToString(response); 
        runOnUiThread(new Runnable() { 

          @Override 
          public void run() { 
           Toast.makeText(UploadImage.this, "Response " + the_string_response, Toast.LENGTH_LONG).show();       
          } 
         }); 

       }catch(Exception e){ 
         runOnUiThread(new Runnable() { 

         @Override 
         public void run() { 
          Toast.makeText(UploadImage.this, "ERROR " + e.getMessage(), Toast.LENGTH_LONG).show();        
         } 
        }); 
         System.out.println("Error in http connection "+e.toString()); 
       } 
     } 
    }); 
    t.start(); 
    } 

    public String convertResponseToString(HttpResponse response) throws IllegalStateException, IOException{ 

     String res = ""; 
     StringBuffer buffer = new StringBuffer(); 
     inputStream = response.getEntity().getContent(); 
     int contentLength = (int) response.getEntity().getContentLength(); //getting content length….. 
      runOnUiThread(new Runnable() { 

     @Override 
     public void run() { 
      Toast.makeText(UploadImage.this, "contentLength : " + contentLength, Toast.LENGTH_LONG).show();      
     } 
    }); 

     if (contentLength < 0){ 
     } 
     else{ 
       byte[] data = new byte[512]; 
       int len = 0; 
       try 
       { 
        while (-1 != (len = inputStream.read(data))) 
        { 
         buffer.append(new String(data, 0, len)); //converting to string and appending to stringbuffer….. 
        } 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
       try 
       { 
        inputStream.close(); // closing the stream….. 
       } 
       catch (IOException e) 
       { 
        e.printStackTrace(); 
       } 
       res = buffer.toString();  // converting stringbuffer to string….. 

       runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        Toast.makeText(UploadImage.this, "Result : " + res, Toast.LENGTH_LONG).show(); 
       } 
      }); 
       //System.out.println("Response => " + EntityUtils.toString(response.getEntity())); 
     } 
     return res; 
    } 

}

希望这将有助于你的代码...