【发布时间】:2014-10-12 18:06:49
【问题描述】:
此代码用于将值传递给 php 页面并更新数据库中的一行 我需要以下代码才能进入异步任务,之后如何调用它等等。我收到 android.os.networkonmainthreadexception 错误。
public void dbUpdate(ArrayList<NameValuePair> data, String php)
{
InputStream iS = null;
try
{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(php);
httppost.setEntity(new UrlEncodedFormEntity(data));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
iS = entity.getContent();
}
catch(Exception e)
{
Log.e("log_tag", "Error in http connection " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
这是我按钮内的代码
public void Update(View v)
{
try
{
String nM = this.Name.getText().toString();
String tP = this.Type.getText().toString();
String bR = this.Breed.getText().toString();
String gE = this.Gender.getText().toString();
String iN = this.Injuries.getText().toString();
String tR = this.Treat.getText().toString();
ArrayList<NameValuePair> up = new ArrayList<NameValuePair>();
up.add(new BasicNameValuePair("name", nM));
up.add(new BasicNameValuePair("type", tP));
up.add(new BasicNameValuePair("breed", bR));
up.add(new BasicNameValuePair("gender", gE));
up.add(new BasicNameValuePair("injuries", iN));
up.add(new BasicNameValuePair("treatment", tR));
String php = "http://select.garethprice.co.za/update.php?nM=" + nM;
dbUpdate(up, php);
Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Log.e("log_tag", "Error in uploading " + e.toString());
Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
}
提前谢谢你!
【问题讨论】:
-
必须是
AsyncTask吗? -
是的,HTTP 请求必须在后台线程中执行,否则它们会在加载时停止 UI 线程中的所有其他操作。最直接的方法是使用 AsyncTask 类。
标签: php android android-asynctask