滑动刷新布局可提供空指针异常

时间:2019-07-01 06:33:58

标签: java android swiperefreshlayout

我有一个SwipeRefreshLayout,它给出了空指针异常。我尝试了多种方法来解决问题,但没有任何效果。我不确定我正在做什么样的

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">

<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swiperefresh"
    android:layout_height="match_parent"
    android:layout_width="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</android.support.v4.widget.SwipeRefreshLayout>

</RelativeLayout>

活动中的Java代码

 RecyclerView recyclerView;
 LinearLayoutManager linearLayoutManager;
 private SwipeRefreshLayout mSwipeRefreshLayout;

  @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mSwipeRefreshLayout = findViewById(R.id.swiperefresh);
    recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

     mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            loadDataFromServer();
        }
    });


 }

日志中的错误:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.datapanel/com.example.datapanel.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout$OnRefreshListener)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3229)
    at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1926)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:6981)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1445)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.SwipeRefreshLayout.setOnRefreshListener(android.support.v4.widget.SwipeRefreshLayout$OnRefreshListener)' on a null object reference

0 个答案:

没有答案