borjacastillo
borjacastillo

Reputation: 269

Android Asynctask from second activity

I am creating an Android app. First of all, I have two activities.

The first one is the login screen and the second one is the main view of my app with list and so on. I also have a remote DB to get data from it and I use AsyncTask class to get this kind of data. If I execute only the login, it works fine. Furthermore, if I only execute the main view (querying data to the db) it works fine too.

The problem comes when I execute both views and I call the asynctask from the second one. If I do not execute AsyncTask from the main view, everything is nice. 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.

Here is my AsyncTask code:

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

}
}

Upvotes: 0

Views: 85

Answers (1)

Felipe Silveira
Felipe Silveira

Reputation: 533

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.

Yes, you are right - you can't execute it in a background thread, see:

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

"This method must be invoked on the UI thread."

If you really need an asynctask being executed from a background thread, consider to execute it using runOnUiThread http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

Upvotes: 1

Related Questions