在android studio中遇到RecyclerView问题

时间:2015-12-24 07:46:41

标签: java android xml android-recyclerview

我是android开发的新手。我正在开发一个生成账单的应用程序。我创建了三个活动,即一个是MainActivity,另一个是显示账单活动,带有 RecyclerView 和一个浮动操作按钮,第三个活动用于添加账单,当用户点击第二个活动的FAB按钮时显示。 我正在尝试从活动三获取数据并将其显示在活动二中的recyclerview中,并且我想在单击第三个活动上的添加按钮时执行此操作..每次运行此代码时,应用程序崩溃。 任何帮助将不胜感激。

这是我的DisplayBills活动

public class DisplayBills extends AppCompatActivity {


public Button mAddBtn;
private RecyclerView mRecyclerView;
private CustomRecyclerAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

private EditText mOrder;
private EditText mDate;
private EditText mName;
private EditText mTdsin;
private EditText mTdsout;
private EditText mAmount;

private List<Data> mData = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_bills);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    mAddBtn = (Button) findViewById(R.id.btn_add_bill);

    mAddBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // Initializing views.
            mOrder = (EditText) findViewById(R.id.input_order_no);
            mDate = (EditText) findViewById(R.id.input_date);
            mName = (EditText) findViewById(R.id.input_c_name);
            mTdsin = (EditText) findViewById(R.id.input_tds_in);
            mTdsout = (EditText) findViewById(R.id.input_tds_out);
            mAmount = (EditText) findViewById(R.id.input_amount);
            mRecyclerView = (RecyclerView) findViewById(R.id.rv);

            // If the size of views will not change as the data changes.
            mRecyclerView.setHasFixedSize(true);

            // Setting the LayoutManager.
            mLayoutManager = new LinearLayoutManager(getApplicationContext());
            mRecyclerView.setLayoutManager(mLayoutManager);

            // Setting the adapter.
            mAdapter = new CustomRecyclerAdapter();
            mRecyclerView.setAdapter(mAdapter);
        }

        // Called when add button is clicked.
        public void addItem(View view) {

            // Add data locally to the list.
            Data dataToAdd = new Data(
                    Integer.parseInt(mOrder.getText().toString()),
                    Integer.parseInt(mDate.getText().toString()),
                    mName.getText().toString(),
                    Integer.parseInt(mTdsin.getText().toString()),
                    Integer.parseInt(mTdsout.getText().toString()),
                    Integer.parseInt(mAmount.getText().toString()));
            mData.add(dataToAdd);

            // Update adapter.
            mAdapter.addItem(mData.size() - 1, dataToAdd);
        }
    });


    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(),
                AddNewBill.class);

            // Start DisplayBills Activity
            startActivity(intent);
        }
    });

}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_bills, menu);
        return true;
    }
 }

这是我的DisplayBills XML,它由Coordinator布局包围。

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

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

    <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_add_white_24dp" />

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

这是我的AddNewBills活动

public class AddNewBill extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_new_bill);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

    }
}

这是AddNewBills活动的XML,它也被协调器布局

包围
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
</android.support.design.widget.AppBarLayout>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="?attr/actionBarSize"
    android:orientation="vertical"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:paddingTop="10dp">

    <android.support.design.widget.TextInputLayout
        android:id="@+id/order"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <EditText
            android:id="@+id/input_order_no"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_order"
            android:inputType="number"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/order"
        android:layout_marginTop="4dp">

        <EditText
            android:id="@+id/input_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_date"
            android:inputType="date"/>
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/cusname"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/date"
        android:layout_marginTop="4dp">

        <EditText
            android:id="@+id/input_c_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:hint="@string/hint_cname" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/cusname"
        android:layout_marginTop="4dp">

        <EditText
            android:id="@+id/input_tds_in"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:hint="@string/hint_tdsin" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tin"
        android:layout_marginTop="4dp">

        <EditText
            android:id="@+id/input_tds_out"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:hint="@string/hint_tdsout" />
    </android.support.design.widget.TextInputLayout>

    <android.support.design.widget.TextInputLayout
        android:id="@+id/tamount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/tout"
        android:layout_marginTop="4dp">

        <EditText
            android:id="@+id/input_amount"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="number"
            android:hint="@string/hint_amount" />
    </android.support.design.widget.TextInputLayout>

    <Button android:id="@+id/btn_add_bill"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/btn_add_bill"
        android:background="@color/colorPrimary"
        android:layout_marginTop="40dp"
        android:textColor="@android:color/white"/>

</LinearLayout>

这是我的logcat

    12-24 15:20:02.976 2118-2118/? E/android.os.Debug: failed to load memtrack module: -2
12-24 15:20:43.706 2128-2128/me.yash.basiclogin E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: me.yash.basiclogin, PID: 2128
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{me.yash.basiclogin/me.yash.basicloginmaterialdesign.DisplayBills}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
                                                                      at android.app.ActivityThread.access$800(ActivityThread.java:151)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                      at android.os.Looper.loop(Looper.java:135)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5257)
                                                                      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)
                                                                   Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
                                                                      at me.yash.basicloginmaterialdesign.DisplayBills.onCreate(DisplayBills.java:44)
                                                                      at android.app.Activity.performCreate(Activity.java:5990)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390) 
                                                                      at android.app.ActivityThread.access$800(ActivityThread.java:151) 
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) 
                                                                      at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                      at android.os.Looper.loop(Looper.java:135) 
                                                                      at android.app.ActivityThread.main(ActivityThread.java:5257) 
                                                                      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) 
12-24 15:20:51.659 339-373/system_process E/InputDispatcher: channel 'b1f5347 me.yash.basiclogin/me.yash.basicloginmaterialdesign.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!

1 个答案:

答案 0 :(得分:0)

你的应用程序崩溃是因为你没有定义R.id.btn_add_bill并且你试图在这里添加一个非现有UI元素的监听器时调用Button.setOnClickListener(View.onClickListener):

 mAddBtn = (Button) findViewById(R.id.btn_add_bill); 
 mAddBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //...}});

因此,为了解决您的问题,请在您的活动布局中添加一个带有R.id.btn_add_bill的按钮以显示帐单,或将此代码移至该类,它将解决您的问题。

修改 看来你已经定义了

<Button android:id="@+id/btn_add_bill" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/btn_add_bill" 
    android:background="@color/colorPrimary" 
    android:layout_marginTop="40dp" 
    android:textColor="@android:color/white"/>

但它不在显示账单的布局中,而是在尝试添加其监听器

public class DisplayBills extends AppCompatActivity {

public Button mAddBtn;
private RecyclerView mRecyclerView;
private CustomRecyclerAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

private EditText mOrder;
private EditText mDate;
private EditText mName;
private EditText mTdsin;
private EditText mTdsout;
private EditText mAmount;

private List<Data> mData = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_bills);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    //.. Removed the mAddBtn, since it does not exist in your layout

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(),
                AddNewBill.class);

            // Start DisplayBills Activity
            startActivity(intent);
        }
    });
}

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.display_bills, menu);
        return true;
    }
 }

无论您从上面删除了什么,都需要在其他活动中使用,这些活动实际上在其布局文件中定义了Button。