如何在AsyncTask中放入以下代码

时间:2014-10-12 18:06:50

标签: php android android-asynctask

此代码用于将值传递到php页面并更新数据库中的行 我需要以下代码进入asynctask,以后如何调用它等。我收到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();
    }
}

提前谢谢!

4 个答案:

答案 0 :(得分:0)

Here是关于AsyncTask的好教程。需要连接到后端并获取此类数据的调用

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();

可以放在doInBackground()中,而结果的处理可以在PostExeceute()方法中完成。

答案 1 :(得分:0)

它将类似于以下内容:

public class MyAsyncTask extends AsyncTask<Void, Void, Boolean> {

     protected void onPreExecute() {
     }

     protected Boolean doInBackground(Void param) {
        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());
            return false;
        }

        return true;
     }

     protected void onPostExecute(Boolean result) {
        if(result)
            Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
         else
            Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
     }
将在UI线程上调用

onPreExecuteonPostExecute。这意味着可以创建对话框,祝酒词等......

doInBackground将在新的工作线程上运行。这将运行您的网络代码。 doInBackground会向onPostExecute返回一个布尔值,以指示是否应显示您的吐司。

然后你在按钮上运行它,如下所示:new MyAsyncTask().execute();替换此调用:dbUpdate(up, php);

官方Android文档可以很好地解释它:Android AsyncTask

答案 2 :(得分:0)

异步任务是一个可以在另一个内部调用以在后台线程中发出HTTP请求的类。您的AsyncTask类将被称为 dbUpdate 。如果希望执行AsyncTask中的操作,请在相应的方法或侦听器中包含以下行。

new dbUpdate().execute();

这将在外部类中,现在我们需要为HTTP post请求配置AsyncTask类。创建public class dbUpdate extends AsyncTask<String, String, String, String, String, String>。现在这个课将有三种方法。

@Override
public void onPreExecute() { super.onPreExecute(); }
protected String doInBackground(String... args) { /* more code here */ }
@Override
protected void onPostExecute(Boolean result) {
    super.onPostExecute(result);
    if(result) Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
}

现在,如果您希望在请求之前或之后运行任何代码,请在 onPreExecute onPostExecute 的超级调用之后包含它们EM> 即可。在 doInBackground 中将是您的HTTP请求(以下代码)。您可以创建所有Strings全局变量,以便可以在两个类中修改它们。

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();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://select.garethprice.co.za/update.php?nM=" + nM);
try{
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("name", nM));
    params.add(new BasicNameValuePair("type", tP));
    params.add(new BasicNameValuePair("breed", bR));
    params.add(new BasicNameValuePair("genders", gE));
    params.add(new BasicNameValuePair("issues", iN));
    params.add(new BasicNameValuePair("treatment", tR));
    httppost.setEntity(new UrlEncodedFormEntity(params));
    httpclient.execute(httppost);
} catch (Exception e) {
    Log.e("log_tag", "Error in uploading " + e.toString());
    Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show();
}
return null;

答案 3 :(得分:0)

喜欢这个。这是一个非常简单的实现,但它涵盖了您的情况。

private class YourAsyncTask extends AsyncTask<Void, Void, Boolean>
{    
     @Override
     protected Void doInBackground(Void... arg0)
    {
        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); 

            dbUpdate(up, php);
        }
       catch(Exception e)
       {
           Log.e("log_tag", "Error in uploading " + e.toString());
           Toast.makeText(getBaseContext(), "Error " + e.toString(), Toast.LENGTH_LONG).show(); 
          return false;
       }

        return true;
    }

     @Override
     protected void onPostExecute(Boolean result)
    {
         if (result)
         {
               Toast.makeText(getBaseContext(), "Successfully updated", Toast.LENGTH_LONG).show();
         }
    }
}