Search code examples
javaandroidandroid-fragmentsandroid-tablayoutandroid-bundle

Tablayout bundle in fragment - null object reference


I've used this guide here to make the activity: http://www.androidhive.info/2015/09/android-material-design-working-with-tabs

I have then added an AsyncTask.

I am trying to pass

Activity.java

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFrag(new ProfileFragment(), "Profile");
    viewPager.setAdapter(adapter);
}

class ViewPagerAdapter extends FragmentPagerAdapter {
    private final List<Fragment> mFragmentList = new ArrayList<>();
    private final List<String> mFragmentTitleList = new ArrayList<>();

    public ViewPagerAdapter(FragmentManager manager) {
        super(manager);
    }

    @Override
    public Fragment getItem(int position) {
        return mFragmentList.get(position);
    }

    @Override
    public int getCount() {
        return mFragmentList.size();
    }

    public void addFrag(Fragment fragment, String title) {
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mFragmentTitleList.get(position);
    }
}

@Override
    protected void onPostExecute(String JSON_STRING_GET_ID) {
        try {
            JSONObject jsonResponse = new JSONObject(JSON_STRING_GET_ID);
            JSONArray jsonMainNode = jsonResponse.optJSONArray("server_response");

            for (int i = 0; i < jsonMainNode.length(); i++) {
                JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                get_nav_email = jsonChildNode.optString("email");

                Bundle bundle = new Bundle();
                bundle.putString("p_email", get_nav_email);
                ProfileFragment fragToProfile = new ProfileFragment();
                fragToProfile.setArguments(bundle);

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

ProfileFragment.java:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View myInflatedView = inflater.inflate(R.layout.fragment_profile, container,false);

    String p_email = getArguments().getString("p_email");
    TextView txtTitle = (TextView)myInflatedView.findViewById(R.id.tvUsername2);
    txtTitle.setText(p_email);
    // Inflate the layout for this fragment
    return myInflatedView;
}

Here is the error I get:

1779-1779/com.testing.dev.application E/AndroidRuntime: FATAL EXCEPTION: main
                                                                              Process: com.testing.dev.application, PID: 1779
                                                                              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.os.Bundle.getString(java.lang.String)' on a null object reference
                                                                                  at com.testing.dev.application.fragment.ProfileFragment.onCreateView(ProfileFragment.java:43)
                                                                                  at android.support.v4.app.Fragment.performCreateView(Fragment.java:1974)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1067)
                                                                                  at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1252)
                                                                                  at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
                                                                                  at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                                                  at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:570)
                                                                                  at android.support.v4.app.FragmentPagerAdapter.finishUpdate(FragmentPagerAdapter.java:141)
                                                                                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1177)
                                                                                  at android.support.v4.view.ViewPager.populate(ViewPager.java:1025)
                                                                                  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1545)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.support.design.widget.CoordinatorLayout.onMeasureChild(CoordinatorLayout.java:664)
                                                                                  at android.support.design.widget.CoordinatorLayout.onMeasure(CoordinatorLayout.java:731)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.support.v7.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:135)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1436)
                                                                                  at android.widget.LinearLayout.measureVertical(LinearLayout.java:722)
                                                                                  at android.widget.LinearLayout.onMeasure(LinearLayout.java:613)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5535)
                                                                                  at android.widget.FrameLayout.onMeasure(FrameLayout.java:436)
                                                                                  at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2615)
                                                                                  at android.view.View.measure(View.java:17547)
                                                                                  at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2015)
                                                                                  at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1173)
                                                                                  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1379)
                                                                                  at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1061)
                                                                                  at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5885)
                                                                                  at android.view.Choreographer$CallbackRecord.run(Choreographer.java:767)
                                                                                  at android.view.Choreographer.doCallbacks(Choreographer.java:580)
                                                                                  at android.view.Choreographer.doFrame(Choreographer.java:550)
                                                                                  at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:753)
                                                                                  at android.os.Handler.handleCallback(Handler.java:739)
                                                                                  at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                  at android.os.Looper.loop(Looper.java:135)
                                                                                  at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                                  at java.lang.reflect.Method.invoke(Native Method)
                                                                                  at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
                                                                                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Solution

  • I have an approach you might want to consider here! But of course, it is upon you.

    Create your ViewPagerAdapter class and inside your addFrag() method, you want to pass the value of your email like this:

    private String emailAddress;
    
    public ViewPagerAdapter(FragmentManager manager, String email) {
        super(manager);
        emailAddress = email;
    }
    

    Thta is the constructor of your ViewPagerAdapter which you will create inside your Activity.

    Within the same ViewPagerAdapter class, you will have this method addFrag

    public void addFrag(Fragment fragment, String title) {
        Bundle bundle = new Bundle();
        //important line here to note
        bundle.putString("email", emailAddress);
    
        fragment.setArguments(bundle);
        mFragmentList.add(fragment);
        mFragmentTitleList.add(title);
    }
    

    Now that you are passing the email to the fragment, inside your onAttach method of the fragment, you can extract it and set as a class level variable.

    @Override
    public void onAttach(Context ctx){
        super.onAttach(ctx);
    
    
    
        String emailAddress = getArguments().getInt("email");
    
        //do whatever you need here
    }
    

    If however you want to update the fragment without a user touching the tabs, like later on after the AsyncTask has completed, you can look into using Events.

    You basically let the fragment you want to update subscribe to a new Event from your AsyncTask's onPostExecute method.

    My favorite library is using EventBus

    Which you can simply add to your build.gradle file like this:

    compile 'org.greenrobot:eventbus:3.0.0'
    

    I hope this helps and please let me know if you need any further assistance!