我尝试使用AsyncTask
对象将我的应用程序连接到远程服务器。这是我的代码:
public class ConnectServer extends AsyncTask<Void, Void, Void> {
String IP = "";
InputStream is = null;
JSONObject json_data = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
ArrayList<String> donnees = new ArrayList<String>();
@Override
protected Void doInBackground( Void... params ) {
// TODO Auto-generated method stub
IP = "http://192.168.101.1/fichier.php";
nameValuePairs.add( new BasicNameValuePair( "nom", envois.nom ) );
nameValuePairs.add( new BasicNameValuePair( "prenom", envois.prenom ) );
nameValuePairs.add( new BasicNameValuePair( "nationalite", envois.nationalite ) );
nameValuePairs.add( new BasicNameValuePair( "passeport", envois.passeport ) );
try {
//commandes httpClient
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost( IP );
httppost.setEntity( new UrlEncodedFormEntity( nameValuePairs ) );
HttpResponse response = httpclient.execute( httppost );
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.i( "tag", "depuis json" );
}
catch (Exception e) {
Log.i( "taghttppost", "" + e.toString() );
Toast.makeText( c, e.toString(), Toast.LENGTH_LONG ).show();
}
return null;
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
@Override
protected void onPostExecute( Void result ) {
// TODO Auto-generated method stub
super.onPostExecute( result );
Toast.makeText( getApplicationContext(), "fin d'envoi", Toast.LENGTH_SHORT ).show();
}
}
然后,当我尝试在我的onClick()
方法中调用启动该任务时,如下所示:
public void onClick( View v ) {
// TODO Auto-generated method stub
ConnectServer cs = new ConnectServer();
cs.execute( (Void) null );
}
它不起作用。我用eclipse调试它,我确信错误来自这一行:
cs.execute((Void)null);
我尝试将其替换为
cs.execute();
但错误仍然存在。调试器给了我类似的东西:
Thread [<10> AsyncTask #1] (Suspended (exception RuntimeException))
ThreadPoolExecutor.runWorker(ThreadPoolExecutor$Worker) line: 1086
ThreadPoolExecutor$Worker.run() line: 561
Thread.run() line: 1096
Thread [<12> AsyncTask #2] (Running)
我想补充一点,当我在没有AsyncTask
.