-1

I am trying to refresh a RecyclerView by assigning a new adapter to the RecyclerView but it is throwing a NullPointerException.

I have created a TabLayout which has three tabs and when you reselect the first tab the method is called to refresh the RecyclerView. But, I am getting a NullPointerException on recyclerViewAdapter.notifyDataSetChanged();. I have initialized recyclerViewAdapter in the onCreateView(); but I still get an Exception.

EDIT :

This is a fragment not an Activity, I cannot setContentView();. Please read the question before down voting or doing anything not helpful.

Please suggest a proper way if I am doing it wrong.

Fragment which has the RecyclerView :

Tab1.class :

public class Tab1 extends Fragment {

    private RecyclerView recyclerView;
    private RecyclerViewAdapter recyclerViewAdapter;
    private List<World> worldList;

    private OnFragmentInteractionListener mListener;

    private DBHelper helper;
    private Context myContext;
    private View view;

    @Override
    public void onStart() {

        this.helper = new DBHelper(getContext());
        recyclerViewAdapter = new RecyclerViewAdapter(getContext(), helper.getList());


        super.onStart();
    }



    public Tab1() {

    }



    public void update() {


        recyclerViewAdapter.notifyDataSetChanged();
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {

        this.helper = new DBHelper(getContext());

        this.worldList = new ArrayList<>();
        this.worldList = helper.getList();

        this.recyclerViewAdapter = new RecyclerViewAdapter(getContext(), this.worldList);
        super.onCreate(savedInstanceState);


    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {


        view = inflater.inflate(R.layout.fragment_tab1, container, false);

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        recyclerViewAdapter = new RecyclerViewAdapter(getContext(), worldList);
        recyclerView.setAdapter(recyclerViewAdapter);


        return view;
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {

        void onFragmentInteraction(Uri uri);
    }
}

The method is called from the MainActivity.class(When the Tab is re selected).

MainActivty.class :

public class MainActivity extends AppCompatActivity implements Tab1.OnFragmentInteractionListener, Tab2.OnFragmentInteractionListener, Tab3.OnFragmentInteractionListener {


    DBHelper helper;
    World world;
    Location location;
    GPSTracker tracker;
    RecyclerViewAdapter adapter;
    public static Context CONTEXT = null;

    RecyclerView recyclerView;

    public Tab1 tab1;

    public static final String BROADCAST_ACTION = "e.wolverine2.thewalkingapp";


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

        ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 123);

        CONTEXT = getApplicationContext();
        MessageReciever reciever = new MessageReciever(new Message());

        Intent intent = new Intent(this, MyService.class);
        intent.putExtra("reciever", reciever);
        startService(intent);

        tracker = new GPSTracker(getApplicationContext());
        location = tracker.getLocation();
        helper = new DBHelper(getApplicationContext());
        tab1 = new Tab1();

        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        adapter = new RecyclerViewAdapter(getApplicationContext(), helper.getList());

        final TabLayout tabLayout = (TabLayout) findViewById(R.id.myTabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("LOCATIONS"));
        tabLayout.addTab(tabLayout.newTab().setText("TOTAL DISTANCE"));
        tabLayout.addTab(tabLayout.newTab().setText("CALS"));

        tabLayout.getTabAt(0).setIcon(R.drawable.ic_list);
        tabLayout.getTabAt(1).setIcon(R.drawable.ic_person_pin);
        tabLayout.getTabAt(2).setIcon(R.drawable.ic_fitness_excercise);


        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        //onError();

        final ViewPager viewPager = (ViewPager) findViewById(R.id.myViewPager);
        final PagerAdapter pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
        viewPager.setAdapter(pagerAdapter);


        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {


                if (tab.getPosition() == 0) {

                    Tab1 tab1 = new Tab1();
                    tab1.update();

                }

            }
        });
    }


    public void locationChanged(double longi, double lati) {

        final Location location = new Location("");

        location.setLatitude(lati);
        location.setLongitude(longi);
        world = new World();

        String timeStamp = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss").format(new Date());

        world.setLongitude(location.getLongitude());
        world.setLatitiude(location.getLatitude());
        world.setDate(timeStamp);
        world.setTime(timeStamp);
        world.setLocation("Anonymous");


        helper.addRow(world);


        //tab1.update(getApplicationContext());


    }

    @Override
    public void onFragmentInteraction(Uri uri) {
    }

    public class Message {

        public void displayMessage(int resultCode, Bundle resultData) throws NullPointerException {


            double longi = resultData.getDouble("longitude");
            double lati = resultData.getDouble("latitude");

            locationChanged(longi, lati);

            //Toast.makeText(MainActivity.this, "TOASTY X : " + e.getMessage(), Toast.LENGTH_SHORT).show();
            //Log.v("TOASTY X : ","" + e.getMessage());


        }

    }


    public void onError() {
        helper.onDropTable();
        Toast.makeText(this, "TABLE DROPED!", Toast.LENGTH_SHORT).show();
    }
}

Logcat :

                                                 java.lang.NullPointerException: Attempt to invoke virtual method 'void e.wolverine2.thewalkingapp.RecyclerViewAdapter.notifyDataSetChanged()' on a null object reference
                                                     at e.wolverine2.thewalkingapp.Tab1.update(Tab1.java:57)
                                                     at e.wolverine2.thewalkingapp.MainActivity$1.onTabReselected(MainActivity.java:101)
                                                     at android.support.design.widget.TabLayout.dispatchTabReselected(TabLayout.java:1177)
                                                     at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1136)
                                                     at android.support.design.widget.TabLayout.selectTab(TabLayout.java:1128)
                                                     at android.support.design.widget.TabLayout$Tab.select(TabLayout.java:1427)
                                                     at android.support.design.widget.TabLayout$TabView.performClick(TabLayout.java:1537)
                                                     at android.view.View$PerformClick.run(View.java:23985)
                                                     at android.os.Handler.handleCallback(Handler.java:751)
                                                     at android.os.Handler.dispatchMessage(Handler.java:95)
                                                     at android.os.Looper.loop(Looper.java:154)
                                                     at android.app.ActivityThread.main(ActivityThread.java:6816)
                                                     at java.lang.reflect.Method.invoke(Native Method)
                                                     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1563)
                                                     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1451)
CodeMunky
  • 21
  • 1
  • 4
    Possible duplicate of [Null pointer Exception - findViewById()](https://stackoverflow.com/questions/19078461/null-pointer-exception-findviewbyid) – Joe C Mar 19 '18 at 22:17
  • Please read the Edit and remove your vote . – CodeMunky Mar 19 '18 at 22:34
  • 1
    *Please suggest a proper way if I am doing it wrong.* the right way is to learn about Fragment's lifecycle before using it ... No please, show us where `Tab1.onCreateView` ... – Selvin Mar 19 '18 at 22:40

1 Answers1

0

Java Tip: When it gets here:

Tab1 tab1 = new Tab1();
tab1.update();

A new Tab is instantiated using the cunstructor:

public Tab1() {

}

in your Tab class. as you see the recyclerView is not initialized up to this point.So the recyclerView is actually Null!

Answer: To correctly implement fragment take a look at this: https://stackoverflow.com/a/5161143/6094503

What you looking for is the following lines:

Fragment newFragment = new DebugExampleTwoFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(CONTENT_VIEW_ID, newFragment).commit();

but I think you need more study about fragments and how they're added to (or removed from) an activity

navid
  • 1,022
  • 9
  • 20