为什么我会得到Nullpointer异常?

时间:2018-03-19 22:16:18

标签: java android android-recyclerview

我正在尝试通过为RecyclerView分配新的适配器来刷新RecyclerView,但它正在抛出NullPointerException

我创建了一个TabLayout,它有三个标签,当您重新选择第一个标签时,会调用该方法来刷新RecyclerView。但是,我在NullPointerException上获得recyclerViewAdapter.notifyDataSetChanged();。我已在recyclerViewAdapter初始化了onCreateView();,但我仍然得到Exception

编辑:

这是一个片段而非活动,我不能setContentView();。请在投票前或在做任何无用的事情之前阅读问题。

如果我做错了,请提出正确的建议。

具有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);
    }
}

从MainActivity.class调用该方法(重新选择Tab时)。

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)

1 个答案:

答案 0 :(得分:0)

Java提示:当它到达时:

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

使用cunstructor实例化新的Tab:

public Tab1() {

}
Tab类中的

。如你所见,到目前为止,recyclerView尚未初始化。所以recyclelerView实际上是空的!

答案:要正确实现片段,请看一下: https://stackoverflow.com/a/5161143/6094503

您要找的是以下几行:

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

但我认为你需要更多关于片段的研究以及它们如何被添加到活动中(或从中删除)