0

I have an activity which has four fragments. I want to access the variable of an asyncTask from this activity. The variable is instantiated in onPostExecute method of an asyncTask.

I tried to create method in this class and access it in an activity. but I am getting the null object.

No Idea what is going wrong.

AsyncTask

public class GetProfileAsyncTask extends AsyncTask<String, Void, JSONObject> {
    String api;
    JSONObject jsonParams;
    private Context context;
    public static JSONObject profile;

    public GetProfileAsyncTask(Context context) {
        this.context = context;
    }

    @Override
    protected JSONObject doInBackground(String... params) {
        try {
            api = context.getResources().getString(R.string.server_url) + "api/user/getprofile.php";

            jsonParams = new JSONObject();
            String username = params[0];  // params[0] is username
            jsonParams.put("user", username);

            ServerRequest request = new ServerRequest(api, jsonParams);
            return request.sendRequest();
        } catch(JSONException je) {
            return Excpetion2JSON.getJSON(je);
        }
    }  //end of doInBackground

    @Override
    protected void onPostExecute(JSONObject response) {
        super.onPostExecute(response);
        Log.e("ServerResponse", response.toString());
        try {
            int result = response.getInt("result");
            profile = response.getJSONObject("profile");

            String message = response.getString("message");
            if (result == 0 ) {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                //code after getting profile details goes here
            } else {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
                //code after failed getting profile details goes here
            }
        } catch(JSONException je) {
            je.printStackTrace();
            Toast.makeText(context, je.getMessage(), Toast.LENGTH_LONG).show();
        }
    } //end of onPostExecute

    public static JSONObject getProfile()
    {
        return profile;
    }
}

Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setTitle("Profile");

    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);


    setSupportActionBar(toolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            finish();

        }
    });

    profileAsyncTask = new GetProfileAsyncTask(this);

    GetProfileAsyncTask task = new GetProfileAsyncTask(this);

    profile = GetProfileAsyncTask.getProfile();

    task.execute("sid");

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),mTitles,mNumbOfTabs);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager)findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
    mTabs.setDistributeEvenly(true);
    mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tab_scroll_color);
        }
    });

    mTabs.setViewPager( mViewPager);
}

EDIT: Tried this still its null.

How can I access parameters from JSON object?

In asyncTask:

public void onTaskCompleted(JSONObject response) {
    profile = response;
}

Activity:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_profile);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

    toolbar.setTitle("Profile");

    toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);


    setSupportActionBar(toolbar);

    // Create the adapter that will return a fragment for each of the three
    // primary sections of the activity.
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            finish();

        }
    });

    profileAsyncTask = new GetProfileAsyncTask(this);

    GetProfileAsyncTask task = new GetProfileAsyncTask(this);
    task.execute("sid");

    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(),mTitles,mNumbOfTabs);

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager)findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    mTabs = (SlidingTabLayout)findViewById(R.id.tabs);
    mTabs.setDistributeEvenly(true);
    mTabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
        @Override
        public int getIndicatorColor(int position) {
            return getResources().getColor(R.color.tab_scroll_color);
        }
    });

    mTabs.setViewPager( mViewPager);
}

@Override
public void onTaskCompleted(JSONObject response) {
    profile = response;
}

Getting profile object as null. Please help. Thank you.

gevorg
  • 4,835
  • 4
  • 35
  • 52
  • 1
    your asynctask is asynchronous. You can use interface as a callback to the activity – Raghunandan Jun 13 '16 at 18:05
  • just google you find many stackvoerflow answers. here's one https://xelsoft.wordpress.com/2014/11/28/asynctask-implementation-using-callback-interface/ – Raghunandan Jun 13 '16 at 18:07
  • You need a callback to the activity. When the asynctask finished it warn yout activity, then your object profile is not null – Victor Gomes Jun 13 '16 at 18:15
  • could please check the edited code? @Raghunandan –  Jun 13 '16 at 18:26
  • could please check the edited code? @VictorGomes –  Jun 13 '16 at 18:27
  • @user6265109 you call yourInterface.onTaskCompleted on postExecute in AsyncTask? If yes, It's ok for me, so profile is not null. Ok!? – Victor Gomes Jun 13 '16 at 18:36
  • ok i followed this link :http://stackoverflow.com/questions/9963691/android-asynctask-sending-callbacks-to-ui , what to do in an activity? how to get that variable in an activity?@VictorGomes –  Jun 14 '16 at 04:35

1 Answers1

0

Create the field outside the task at the activity level. Update it in onPostExecute.

usajnf
  • 522
  • 3
  • 11
  • ok i followed this link :stackoverflow.com/questions/9963691/… , what to do in an activity? how to get that variable in an activity?@usajnf –  Jun 14 '16 at 04:36