我尝试使用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();
但错误仍然存在。 debbuger给了我类似的东西:
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
的情况下使用它时,我的代码可以正常工作。
答案 0 :(得分:0)
在ConnectServer类中尝试:
@Override
protected void onPostExecute(Void result) {
Toast.makeText(getApplicationContext(), "fin d'envoi", >Toast.LENGTH_SHORT).show();
}
在活动中尝试此操作:
@Override
public void onClick(View v) {
ConnectServer cs = new ConnectServer();
cs.execute();
}
答案 1 :(得分:0)
事实证明,Eclipse中的 Project->Clean..
有时会解决问题..;)