2014-05-04 178 views
1

我試圖從Android應用程序發送數據到服務器....但點擊保存按鈕導致android.os.NetworkOnMainThreadException和應用程序停止。 請任何人都可以幫忙嗎?從Android應用程序發送數據到服務器時發現異常

HttpClient httpclient = new DefaultHttpClient(); 
HttpPost httppost = new HttpPost("http://farahkhan.byethost15.com/try.php"); 
try { 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
     nameValuePairs.add(new BasicNameValuePair("username", "01")); 
     nameValuePairs.add(new BasicNameValuePair("email", signupemailString)); 

     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

     httpclient.execute(httppost); 

     signupemail.setText(""); //reset the message text field 
     Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show(); 
} catch (ClientProtocolException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

回答

0

這種替換代碼:

new Thread(new Runnable() { 

       @Override 
       public void run() { 
        HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://farahkhan.byethost15.com/try.php"); 
       try { 

        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
         nameValuePairs.add(new BasicNameValuePair("username", "01")); 
         nameValuePairs.add(new BasicNameValuePair("email", signupemailString)); 

         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

         httpclient.execute(httppost); 
         runOnUiThread(new Runnable() { 

         @Override 
         public void run() { 
          signupemail.setText(""); //reset the message text field 
         Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show(); 

         } 
        }); 

       } catch (ClientProtocolException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 

       } 
      }).start(); 

,並在您的清單文件添加權限:

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

@ user3561798您應該使用'AsyncTask'。 –

+0

@ user3561798:但AsyncTask更可靠和更乾淨的方式來做這樣的作品 –

+0

@Arash:我也使用過這種方法......但我無法正確接收或處理它......然後我開始像這樣工作...... – Farah

0

添加Internet權限到你的manifest文件

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

之後檢查this answer

+0

它與這個問題無關! –

+0

我已經在manifest中添加權限.. – Farah

相關問題