1

Androidアプリからサーバーにデータを送信しようとしています....しかし、クリックして保存ボタンをクリックするandroid.os.NetworkOnMainThreadExceptionと、アプリが停止します。誰でも助けてください。

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();
}
4

2 に答える 2

0

マニフェスト ファイルにインターネット アクセス許可を追加する

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

その後、この回答を確認してください

于 2014-05-04T11:31:20.710 に答える
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" /> 
于 2014-05-04T11:31:08.063 に答える