2013-06-30 52 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