LayoutInflater inside AsyncTask onPostExecute method

407 views Asked by At

I'm using drawerLayout inside NavDrawer fragment.

Every time when tab selected, I perform AsyncTask to get data.

This app is not realtime, that's why I always request data from server.

I want to edit some of the parts of the Layout.

public void onTabSelected(TabLayout.Tab tab) {
  if (tab.getPosition() == 0) {
    GetProfileTask getProfileTask = new GetProfileTask();
    getProfileTask.execute();
  } else if (tab.getPosition() == 1) {
    GetGames getGames = new GetGames();
    getGames.execute();
  }

  viewPager.setCurrentItem(tab.getPosition());
}

Inside AsyncTask (this is what I've tried)

protected void onPostExecute(String result) {
  try {
    JSONObject jObject = new JSONObject(result);
    JSONObject profilObject = jObject.getJSONObject("Profil");

    if (profilObject != null) {
      email = profilObject.getString("email");
      bankName = profilObject.getString("bName");
      bankAccountName = profilObject.getString("bAccName");
      bankAccNum = profilObject.getString("bAccNum");

      LayoutInflater inflater = getActivity().getLayoutInflater();
      View v = inflater.inflate(R.layout.fragment_home_tab1, null);

      TextView un = (TextView) v.findViewById(R.id.profile_username);
      un.setText(profilObject.getString("username"));
    }
  } catch (JSONException e) {
    e.printStackTrace();
  }
}

If I am doing it wrong. Please recommend how should I do it. Sorry, I am new in android.

Any help would be appreciated. Thanks.

2

There are 2 answers

0
yanivtwin On

Try using loopj or something of sort instead of asynctask , the server calls will work much better :

https://github.com/loopj/android-async-http

Other than that on post i would just change fragment and make fragments for each situation

you can use this as a refrence :

http://www.survivingwithandroid.com/2013/04/android-fragment-transaction.html

I think those will make your life a lot easier, enjoy.

2
Matt On

Please avoid doing that: you will end with unexpected behavior!

To make async http calls please use an async http library like Volley!

Using that lib you will manage your UI/App-state (filling label, drop down menu, etc) directly inside a callback fired when the HTTP response will arrive to your phone/app!