public class MainActivity extends Activity {
private EditText edtMsg;
private Button btnEnvoyer;
private String resultat=null;
InputStream is=null;
StringBuilder sb=null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edtMsg=(EditText)findViewById(R.id.edtMsg);
btnEnvoyer=(Button)findViewById(R.id.btnEnvoyer);
}
public void envoyerMessage(View v){
HttpClient client=new DefaultHttpClient();
HttpPost post=new HttpPost("http://10.0.2.2/Envoi/applicationEnvoi.php");
String msg=edtMsg.getText().toString();
if(msg.length()>0) {
try {
List<NameValuePair> donnees = new ArrayList<NameValuePair>(1);
donnees.add(new BasicNameValuePair("message", msg));
post.setEntity(new UrlEncodedFormEntity(donnees));
client.execute(post);
edtMsg.setText("");
Toast.makeText(this, "Message Envoyé",Toast.LENGTH_SHORT).show();
} catch(ClientProtocolException e) {
e.printStackTrace();
} catch(IOException e){
e.printStackTrace();
}
} else
Toast.makeText(this,"Ce champs ne peut etre vide",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
答案 0 :(得分:2)
您需要使用thread
或Asynctask
进行与网络相关的操作。
client.execute(post);// post should be executed on a thread.
由于您在主线程上执行此操作,因此您可能会获得NetworkOnMainThreadException
(对于后蜂窝版本)。
http://developer.android.com/reference/android/os/AsyncTask.html