In my Android app I have a messages activity that is composed by three tabs (fragments: inbox, sent and deleted). I need to load data (received in JSON format and converted to String) in both tabs, but when I load the fragments app throws NullPointerException in the line where data is put in the bundle. I think that it's because the app hasn't received the information at the moment of its invocation.
To connect with the service provider i am using AsyncHttpTask library. Here is my code:
MessagesActivity.java:
public class MessagesActivity extends AppCompatActivity {
Toolbar toolbar;
ViewPager pager;
MessagesTabAdapter adapter;
SlidingTabLayout tabs;
CharSequence tabsTitles[] = {"Inbox","Sent","Trash"};
int tabsNumber = 3;
JSONObject inbox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.messages_activity);
//Elements initialization
...
adapter = new MessagesTabAdapter(getSupportFragmentManager(), tabsTitles, tabsNumber);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.messages_pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.messages_tabs);
tabs.setDistributeEvenly(true);
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
@Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
public void updateInbox () {
String token = getSharedPreferences("Myapp", Context.MODE_PRIVATE).getString("token", null);
RequestParams params = new RequestParams();
params.add("token", token);
Client.get("get_inbox", params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
inbox = response.getJSONObject("result");
} catch (JSONException e) {
//No messages
inbox = new JSONObject();
}
}
});
}
public class MessagesTabAdapter extends FragmentStatePagerAdapter {
...
//This method return the fragment for the every position in the View Pager
@Override
public Fragment getItem(int position) {
if(position == 0) // if the position is 0 we are returning the First tab
{
Bundle bundle = new Bundle();
bundle.putString("inbox", updateInbox().toString()); //HERE IS MY EXCEPTION!
MessagesInboxTab tab1 = new MessagesInboxTab();
tab1.setArguments(bundle);
return tab1;
}
else if(position == 1) // As we are having 2 tabs if the position is now 0 it must be 1 so we are returning second tab
{
//Here will go the same code as position==0
MessagesSentTab tab2 = new MessagesSentTab();
return tab2;
}
else
{
//Here will go the same code as position==0
MessagesTrashTab tab3 = new MessagesTrashTab();
return tab3;
}
}
...
}
How can I solve?