0

hello im using Android Studio an im trying to retrieve a json from a class with asynctask but i can retrieve the data obtained to the main thread if if create a getter to obtaind data variable it's null and i get an error in runtime can you help me please?

this is the code:

(mainactivity)

Tarea tarea= new Tarea(URL_DATA,Request.toString(),this);
tarea.execute();
texto.setText((CharSequence) tarea.getData());

(class)

public class Tarea extends AsyncTask {
    ProgressDialog progressDialog;
    String MyURL,MJson;
    volatile String data="";


    public String getData() {
        return data;
    }

    public Tarea(String myURL, String mJson, Context contexto) {
        this.contexto = contexto;
        this.MJson=mJson;
        this.MyURL=myURL;

    }

    Context contexto;
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressDialog=new ProgressDialog(contexto);
        progressDialog.setMessage("Buscando Paqueterias, por favor espera un momento...");
        progressDialog.show();
    }

    @Override
    protected Object doInBackground(Object[] objects) {

        if(MyURL!=null&&MJson!=null) {
            try {
                URL url = new URL(MyURL.toString());
                HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                JSONObject MyJson = new JSONObject(MJson);
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                os.writeBytes(MyJson.toString());
                os.flush();
                os.close();
                //Log.i("Status",String.valueOf(conn.getResponseCode()));
                //Log.i("MSG", conn.getResponseMessage());
                InputStream in = conn.getInputStream();
                InputStreamReader inputStreamReader = new InputStreamReader(in);
                int inputStreamData = inputStreamReader.read();
                while (inputStreamData != -1) {
                    char current = (char) inputStreamData;
                    inputStreamData = inputStreamReader.read();
                    data += current;

                }

            } catch (Exception e) {
                e.printStackTrace();
            }
            progressDialog.dismiss();
        }else {
            Log.i("Error...","Alguna de las variables MyURL o MJson esta vacia...");
        }
        return data;
    }

    @Override
    protected void onPostExecute(Object o) {
        super.onPostExecute(o);

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.i("REs",data);


    }
}

i can print the LOG but i cant send it to the mainactivity to manupulate the json

ColdFire
  • 6,764
  • 6
  • 35
  • 51
  • Use a Callback interface . See [How to Define Callbacks in Android?](https://stackoverflow.com/questions/3398363/how-to-define-callbacks-in-android). – ADM May 03 '18 at 03:41

1 Answers1

0

You can do this with the help of callback approach.

Steps

 1. Create an interface
 2. Create an inner class on activity implement that interface.
 3. Pass the instance of inner class to "Tarea" constructor.
 4. Use constructor variable to communicate with activity.

You can also do the with different approach by overriding onPostExecute.

Use below code..

Tarea tarea= new Tarea(URL_DATA,Request.toString(),this) {
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
    }
};
Saurabh Khare
  • 1,227
  • 13
  • 24