Sending and Returning variables from a separate asyncTask in a separate java class

Asked

Viewed 56 times

1

I am developing a program that consists of inserting variables, processing them through an Asynctask in a separate java class called backgroundWorker and returning values, according to the drawing below:

Fluxograma mainsactivity asynctask

I know it is possible to do this in Mainactivity itself, but I would like to know if there is any way to process the data in the separate backgroundWorker and return only the results to Mainactivity?

I have a code that I have done so far, I searched but I couldn’t find a way to send more than one Return.

Mainactivity.java

public void lerbground(){
BackgroundWorker backgroundWorker = new BackgroundWorker(this);

String pais = "Brasil"; 
int peso = 90; 
double altura = 1.81;
boolean estudante = true; 

backgroundWorker.execute(pais, peso, altura, estudante);
}

backgroundWorker.java

public class BackgroundWorker extends AsyncTask<String,Void,String> {
    Context context;

    String result_nacionalidade = null;
    String result_peso = null;
    String result_altura = null;
    String result_estudante = null;
    BackgroundWorker (Context ctx) {context = ctx;}

@Override
protected String doInBackground(String... params) {

    String pais = params[0];
    int peso = params[1];
    double altura = params[2];
    boolean estudante = params[3];


//VERIFICAÇÃO DE DADOS 1
if (pais == "Brasil") {
    result_nacionalidade = "nacional";
}
else{
    result_nacionalidade = "estrangeiro";
}

//VERIFICAÇÃO DE DADOS 2
if (peso >= 70) {
    result_peso = "pesado";
}
else{
    result_peso = "leve";
}

//VERIFICAÇÃO DE DADOS 3
if (altura >= 1.70) {
    result_altura = "alto";
}
else{
    result_altura = "baixo";
}

//VERIFICAÇÃO DE DADOS 4
if (estudante) {
    result_estudante = "é estudante";
}
else{
    result_estudante = "não estudante";
}

    return null;
}

@Override
protected void onPreExecute() {

    }

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

//GOSTARIA QUE a backgroundWorker conseguisse enviar e que a MainActivity conseguisse receber os resultados:

//result_nacionalidade
//result_peso
//result_altura
//result_estudante

         }
    }

@Override
protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

Another thing I doubt is whether it would be correct the way I parameterized the variables? Inserçao de variaveis na asynctask

From now on I’d appreciate it if someone could help me.

  • If you cannot return the separate fields, join them all in one object and return that object.

  • @Piovezan, thank you for the reply I understood. But then, after this, if I want to separate the object in Mainactivity, it will only be possible through string processing?

  • 1
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.