2013-06-30 57 views
0

這可能是一個超級簡單的答案,但當我按下按鈕時,我的應用程序崩潰。這方法我嘗試運行按鈕的點擊:如何使按鈕執行此方法

public void postData() { 
    // Create a new HttpClient and Post Header 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

    try { 
     // Add your data 
     List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
     nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     // Execute HTTP Post Request 
     HttpResponse response = httpclient.execute(httppost); 

    } catch (ClientProtocolException e) { 
     // TODO Auto-generated catch block 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
    } 
} 

我確信我有:

<uses-permission android:name="android.permission.INTERNET"></uses-permission> 

,這裏是我的活動主:

<Button 
    android:id="@+id/button1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignLeft="@+id/textView1" 
    android:layout_below="@+id/textView1" 
    android:layout_marginTop="16dp" 
    android:onClick="postData" 
    android:text="Button" /> 

回答

3

的方法的簽名應爲

public void postData(View v) 

另一件事,你不能在主UI線程中執行網絡操作。使用AsyncTask而不是

+1

嗯。打敗我10秒:P +1 –

+0

@RaghavSood在同一時間..爲什麼你刪除,指出當你投票你 – stinepike

+0

我錯過了關於UI線程聯網的問題。你的回答已經有了這些信息。沒有意義複製它:P –

0

您應該使用asynctask網絡相關opearation或創建一個新的線程被發現。

HttpResponse response = httpclient.execute(httppost); 

如果不是,你會NetWorkOnMainThreadException

在點擊按鈕

 new PostData().execute(); 

然後

 class PostData extends AsyncTask<Void,Void,Void> 
     { 
       @Override 
       protected void doInBackground(Void... params) 
       { 
        HttpClient httpclient = new DefaultHttpClient(); 
        HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php"); 

        try { 
         // Add your data 
         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
         nameValuePairs.add(new BasicNameValuePair("id", "12345")); 
         nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!")); 
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
         // Execute HTTP Post Request 
         HttpResponse response = httpclient.execute(httppost); 

         } catch (ClientProtocolException e) { 
         // TODO Auto-generated catch block 
         } catch (IOException e) { 
         // TODO Auto-generated catch block 
         } 
         return null;   
       } 
     }  

欲瞭解更多信息檢查文檔

http://developer.android.com/reference/android/os/AsyncTask.html