2014-02-20 145 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; 
    } 

}

希望這將有助於你的代碼...