对recyclerview

时间:2016-10-18 04:13:27

标签: java android android-studio nullpointerexception android-recyclerview

我正在尝试通过点击第一个活动的recyclelerView打开一个包含recyclelerView的活动。但现在,当我点击recyclerView应用程序时,崩溃时会显示以下消息。

  

10-18 09:30:49.912 13018-13018 / in.mumbaitravellers.mtleaders   E / AndroidRuntime:致命例外:主要   过程:in.mumbaitravellers.mtleaders,PID:13018
  java.lang.RuntimeException:无法启动活动   ComponentInfo {in.mumbaitravellers.mtleaders / in.mumbaitravellers.mtleaders.activity.DetailActivity}:   java.lang.NullPointerException:尝试调用虚方法'void   android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)'上   null对象引用
  在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)   在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)   在android.app.ActivityThread.-wrap11(ActivityThread.java)
  在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1354)
  在android.os.Handler.dispatchMessage(Handler.java:102)
  在android.os.Looper.loop(Looper.java:148)
  在android.app.ActivityThread.main(ActivityThread.java:5443)
  at java.lang.reflect.Method.invoke(Native Method)
  在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
  引起:java.lang.NullPointerException:尝试调用虚拟   方法'无效   android.support.v7.widget.RecyclerView.setHasFixedSize(boolean)'上   null对象引用
  在   in.mumbaitravellers.mtleaders.activity.DetailActivity.setupRecycler(DetailActivity.java:120)   在   in.mumbaitravellers.mtleaders.activity.DetailActivity.onCreate(DetailActivity.java:52)   在android.app.Activity.performCreate(Activity.java:6245)
  在   android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1130)   在   android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)   在   android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)   在android.app.ActivityThread.-wrap11(ActivityThread.java)
  在   android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1354)   在android.os.Handler.dispatchMessage(Handler.java:102)
  在android.os.Looper.loop(Looper.java:148)
  在android.app.ActivityThread.main(ActivityThread.java:5443)
  at java.lang.reflect.Method.invoke(Native Method)
  在   com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:728)   在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)       10-18 09:31:13.376 1801-2412 /? E / native:暂停false

java代码如下:

public class DetailActivity extends AppCompatActivity {

private ExpenseAdapter adapter;
private Realm realm;
private LayoutInflater inflater;
private FloatingActionButton fab;
private RecyclerView recycler;

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

    fab = (FloatingActionButton) findViewById(R.id.fab);
    recycler = (RecyclerView) findViewById(R.id.recycler);

    //get realm instance
    this.realm = RealmController.with(this).getRealm();

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    /*String event = getIntent().getStringExtra("eventName");
    TextView tv = (TextView) findViewById(R.id.txt_EventName);
    tv.setText(event);*/

    setupRecycler();

    if (!Prefs.with(this).getPreLoad()) {
        setRealmData();
    }

    // refresh the realm instance
    RealmController.with(this).refresh();
    // get all persisted objects
    // create the helper adapter and notify data set changes
    // changes will be reflected automatically
    setRealmAdapter(RealmController.with(this).getExpenses());

    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            inflater = DetailActivity.this.getLayoutInflater();
            View content = inflater.inflate(R.layout.activity_add_new_expense, null);
            final EditText editExpense = (EditText) content.findViewById(R.id.edtxt_expense);
            final EditText editDescription = (EditText) content.findViewById(R.id.edtxt_description);

            AlertDialog.Builder builder = new AlertDialog.Builder(DetailActivity.this);
            builder.setView(content)
                    .setTitle("Add Expense")
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                            Expense expense = new Expense();

                            expense.setId((int) (RealmController.getInstance().getExpenses().size() + System.currentTimeMillis()));
                            expense.setAmount(editExpense.getText().toString());
                            expense.setDescription(editDescription.getText().toString());

                            realm.beginTransaction();
                            realm.copyToRealm(expense);
                            realm.commitTransaction();

                            adapter.notifyDataSetChanged();
                            // scroll the recycler view to bottom
                            recycler.scrollToPosition(RealmController.getInstance().getExpenses().size() - 1);
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
            AlertDialog dialog = builder.create();
            dialog.show();

        }
    });
}

public void setRealmAdapter(RealmResults<Expense> expenses) {

    RealmExpenseAdapter realmExpenseAdapter = new RealmExpenseAdapter(this.getApplicationContext(), expenses, true);
    adapter.setRealmAdapter(realmExpenseAdapter);
    adapter.notifyDataSetChanged();
}

private void setupRecycler() {
    // use this setting to improve performance if you know that changes
    // in content do not change the layout size of the RecyclerView
    recycler.setHasFixedSize(true);

    // use a linear layout manager since the cards are vertically scrollable
    final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
    layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
    recycler.setLayoutManager(layoutManager);

    // create an empty adapter and add it to the recycler view
    adapter = new ExpenseAdapter(this);
    recycler.setAdapter(adapter);
}

private void setRealmData() {

    ArrayList<Expense> expenses = new ArrayList<>();

    for (Expense e : expenses) {
        // Persist your data easily
        realm.beginTransaction();
        realm.copyToRealm(e);
        realm.commitTransaction();
    }

    Prefs.with(this).setPreLoad(true);
}
}

xml文件如下:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout            xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<include layout="@layout/content_detail" />

<android.support.design.widget.FloatingActionButton
    android:id="@+id/fab"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|end"
    android:layout_margin="@dimen/fab_margin"
    android:src="@drawable/ic_action_add" />
</android.support.design.widget.CoordinatorLayout>

Recycler View Code:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/card_expense"
style="@style/AppTheme.Card.Margins"
android:layout_width="match_parent"
android:layout_height="wrap_content">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/text_amount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="@dimen/margin_small"
        android:paddingBottom="@dimen/margin_normal"
        android:paddingLeft="@dimen/margin_large"
        android:paddingRight="@dimen/margin_large"
        android:paddingTop="@dimen/margin_large"
        android:textColor="#555555"
        android:text="\u20B9"
        android:textSize="40dp"
        android:textStyle="bold" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="25dp"
        android:id="@+id/text_description"
        android:textSize="20dp"/>

</LinearLayout>
</android.support.v7.widget.CardView>

Content Detail.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/recyclerExpense"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:showIn="@layout/activity_detail"
tools:context="in.mumbaitravellers.mtleaders.activity.DetailActivity"
app:layout_behavior="@string/appbar_scrolling_view_behavior" />

代码有什么问题,请帮忙。 提前谢谢!

1 个答案:

答案 0 :(得分:1)

您的问题在于对RecyclerView

的错误搜索

更改您的代码:

recycler = (RecyclerView) findViewById(R.id.recycler);

recycler = (RecyclerView) findViewById(R.id.recyclerExpense);