2013-05-14 36 views
0

所以,我有這裏的代碼: 這並不真正的工作,我得到的應用程序已停止,問題是,之前,當我在家裏嘗試這個工作就好了...現在它不! 我不知道這裏有什麼問題,請有人看看並告訴我? 謝謝..問題在httpost應用程序停止

public class MainActivity extends Activity { 

    EditText msgTextField; 
    Button sendButton; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

      //make message text field object 
      msgTextField = (EditText) findViewById(R.id.msgTextField); 
      //make button object 
      sendButton = (Button) findViewById(R.id.sendButton); 
     } 

     public void send(View v) 
     { 
      //get message from message box 
      String msg = msgTextField.getText().toString(); 

      //check whether the msg empty or not 
      if(msg.length()>0) { 
       HttpClient httpclient = new DefaultHttpClient(); 
       HttpPost httppost = new HttpPost("http://192.168.10.28/app/app1.php"); 

       try { 
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
         nameValuePairs.add(new BasicNameValuePair("id", "01")); 
         nameValuePairs.add(new BasicNameValuePair("message", msg)); 
         httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
         httpclient.execute(httppost); 
         msgTextField.setText(""); //reset the message text field 
         Toast.makeText(getBaseContext(),"Sent",Toast.LENGTH_SHORT).show(); 
       } catch (ClientProtocolException e) { 
        e.printStackTrace(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } else { 
       //display message if text field is empty 
       Toast.makeText(getBaseContext(),"All fields are required",Toast.LENGTH_SHORT).show(); 
      } 
     } 

    } 

在這裏,我有Manifes.xml

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
    package="com.example.form" 
    android:versionCode="1" 
    android:versionName="1.0" > 

    <uses-sdk 
     android:minSdkVersion="8" 
     android:targetSdkVersion="17" /> 
    <uses-permission android:name="android.permission.INTERNET" /> 

    <application 
     android:allowBackup="true" 
     android:icon="@drawable/ic_launcher" 
     android:label="@string/app_name" 
     android:theme="@style/AppTheme" > 
     <activity 
      android:name="com.example.form.MainActivity" 
      android:label="@string/app_name" > 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 
    </application> 

</manifest> 

回答

0

你正在做一些不會被UI線程調用的東西。您可以創建一個AsyncTask來執行此類操作。有關更多信息,請參閱this

+0

我很新這個.. coudl你請幫我實施它在我的代碼? – alandr 2013-05-14 09:01:57

0

每一個阻塞調用必須從UI Thread不同的線程中運行。您正在獲得NetworkOnMainThreadException。使用ThreadAsyncTask。閱讀here