java - 来自第二个 Activity 的 Android Asynctask

标签 java android android-asynctask

我正在创建一个 Android 应用程序。首先,我有两个 Activity 。

第一个是登录屏幕,第二个是我的应用程序的主视图,包含列表等。我还有一个远程数据库来从中获取数据,并且我使用 AsyncTask 类来获取此类数据。如果我只执行登录,则效果很好。此外,如果我只执行主视图(向数据库查询数据),它也可以正常工作。

当我执行两个 View 并从第二个 View 调用 asynctask 时,问题就出现了。如果我不从主视图执行 AsyncTask,一切都很好。似乎我无法在主线程之外执行 AsyncTask (我已经阅读了一些相关信息),但我确实找不到解决方案。

这是我的 AsyncTask 代码:

package com.hissacclaim.pfc.hissacclaim;

import android.os.AsyncTask;
import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

class DownloadTask extends AsyncTask<String, Void, JSONArray> {

    private String urlWebService="http://hissacclaim.morwebs.com/";
    private String type=null;
    private String query=null;
    private String columns=null;
    private String colValues=null;
    private String table=null;
    private String condition=null;
    private String user=null;
    private String password=null;
    private String logincode=null;


public int changeUrlMySQL(String url){
    this.urlWebService= url;
    return 1;
}

public int reset(){
    this.urlWebService="http://hissacclaim.morwebs.com/";
    this.type=null;
    this.query=null;
    this.columns=null;
    this.colValues=null;
    this.table=null;
    this.condition=null;
    this.user=null;
    this.password=null;
    return 1;
}

public int login(String user, String password){
    this.type= "login";
    this.user= user;
    this.password= password;
    return 1;
}

public int set_logincode(String code){
    this.logincode= code;
    return 1;
}

public String get_logincode(){
    return this.logincode;
}

public String type_last_petition() {
    return this.type;
}

public int insertRow(String table, String columns, String colValues){
    this.type= "insertRow";
    this.table= table;
    this.columns= columns;
    this.condition= null;
    this.colValues= colValues;
    return 1;
}

public int deleteRow(String table, String columns, String condition, String colValues){
    this.type= "deleteRow";
    this.table= table;
    this.columns= columns;
    this.condition= condition;
    this.colValues= colValues;
    return 1;
}

public int searchByColumn(String table, String columns, String condition, String colValues){
    this.type= "searchByColumn";
    this.table= table;
    this.columns= columns;
    this.condition= condition;
    this.colValues= colValues;
    return 1;
}

public int getTable(String table){
    this.type= "getTable";
    this.table= table;
    this.columns= null;
    this.condition= null;
    this.colValues= null;
    return 1;
}

public int genericQuery(String table, String columns, String condition, String colValues){
    this.type= "genericQuery";
    this.table= table;
    this.columns= columns;
    this.condition= condition;
    this.colValues= colValues;
    return 1;
}


protected JSONArray doInBackground(String... urls) {
    String result = "";
    InputStream is = null;

    try{
        MCrypt mcrypt = new MCrypt();

        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        if(this.type!=null)nameValuePairs.add(new BasicNameValuePair("type",MCrypt.bytesToHex(mcrypt.encrypt(this.type))));
        if(this.logincode!=null)nameValuePairs.add(new BasicNameValuePair("logincode",this.logincode));
        if(this.query!=null)nameValuePairs.add(new BasicNameValuePair("query",this.query));
        if(this.columns!=null)nameValuePairs.add(new BasicNameValuePair("columns",this.columns));
        if(this.colValues!=null)nameValuePairs.add(new BasicNameValuePair("values",this.colValues));
        if(this.table!=null)nameValuePairs.add(new BasicNameValuePair("table",this.table));
        if(this.condition!=null)nameValuePairs.add(new BasicNameValuePair("condition",this.condition));
        if(this.user!=null)nameValuePairs.add(new BasicNameValuePair("user",MCrypt.bytesToHex(mcrypt.encrypt(this.user))));
        if(this.password!=null)nameValuePairs.add(new BasicNameValuePair("password",MCrypt.bytesToHex(mcrypt.encrypt(this.password))));


        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost=null;

        httppost = new HttpPost(this.urlWebService + "dbconnection.php");

        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        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 null;
    }

    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();

        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        return null;
    }


    try{
        JSONArray jArray = new JSONArray(result);
        for(int i=0;i<jArray.length();i++){
            JSONObject json_data = jArray.getJSONObject(i);
            /*Log.i("log_tag","id: "+json_data.getInt("id")+
                            ", name: "+json_data.getString("name")+
                            ", sex: "+json_data.getInt("sex")+
                            ", birthyear: "+json_data.getInt("birthyear")
            );*/
        }
        return jArray;
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
        return null;
    }


}
//This Method is called when Network-Request finished
protected void onPostExecute(String serverData) {
    //textView.setText(serverData);
    System.out.print("FINAL DE DLTASK");

}
}

最佳答案

It seems like I can't execute AsyncTask outside of the main thread (I have read some information about that) but I can't really find a solution.

是的,你是对的 - 你不能在后台线程中执行它,请参阅:

http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...)

“必须在 UI 线程上调用此方法。”

如果您确实需要从后台线程执行异步任务,请考虑使用 runOnUiThread http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) 来执行它。

关于java - 来自第二个 Activity 的 Android Asynctask,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27492083/

相关文章:

java - 如何使 listFooter 不可点击

android - 在 AsyncTask 中保持屏幕明亮

java - netbeans语句stmt问题

java - 使用 struts 加载页面时,JSP 下拉列表默认选择第一个选项

java - 在时间 X 和时间 Y 之间/时间段内查找对象

Android - 两个android版本名称之间的字符串比较

android - 无法集成具有自定义样式的android库

java - Android setOnClickListener 不起作用

php - 从服务器检索数据花费了太多时间

android - 无法连接到远程数据库