0

I have an MainActivity class. one Login class which extends AsyncTask. after execute Login class, it will return JSONObject to MainActivity like:

AsyncTask<Void, Void, JSONObject> getData = (new Login()).execute();

Now how can I separate data from getData?

my returned JOSNObject will looks like:

{"FirstName":"A","LastName":"B","ID":"09","Cell":"0123456789","Email":"abc@yahoo.com"}

or do I need to handle these in different way?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115

2 Answers2

1

You can try this on doInBackground:

JSONObject json = new JSONObject(StringResponse);

String FirstName = json.getString("FirstName");
String LastName = json.getString("LastName");
String ID = json.getString("ID");
String Cell= json.getString("Cell");
String Email= json.getString("Email");

Now you have data separate on differents strings.

Aspicas
  • 4,498
  • 4
  • 30
  • 53
  • I know this procedure but I want to get data in my MainActivity class instead – user5296685 Oct 08 '15 at 17:09
  • You can save that strings on `ArrayList` and past Array to another `Activity`, using...for example...a `Bundle and Intent` or `SharedPreferences` – Aspicas Oct 08 '15 at 17:16
  • ok thanks, if I follow your first solution then I need to start one activity from the Login class. I googled but unable to get solution for that. can you please try to solve my prob ? – user5296685 Oct 09 '15 at 04:34
  • You can make a `Splash Screen` search on google about that, it's easy. Tell me if you have any problem. =) – Aspicas Oct 09 '15 at 06:17
0

To pass data from AsyncTask to your Activity you can create a call back method.

  1. First create a Interface

    public interface OnTaskCompleteListener{
      public void onTaskCompleted(JsonObject jsonobj);  
    }
    
  2. Then implement and override its method in Activity

    public class MainActivity extends Activity implements OnTaskCompleteListener{
      @Override
      public void OnTaskCompleted(JsonObject jsonobj)
      {
    
      }
    
  3. And lastly pass data from your AsyncTask

    public class Login extends AsyncTask<Void, Void, JSONObject>{ 
    private OnTaskCompleteListener listener;
    
    public Login(OnTaskCompleteListener listener){
        this.listener=listener;
    }
    protected void onPostExecute(JsonObject obj){
        listener.onTaskCompleted(obj);
    }
    }
    

    I hope this is what you wanted. You can refer this question in case of doubts:

    android asynctask sending callbacks to ui

Community
  • 1
  • 1
Vikas Mane
  • 789
  • 1
  • 6
  • 14