Android:如何在一个Activity中使用Save按钮单击在Recyclerview Activity中添加CardView项?

时间:2016-02-03 00:36:38

标签: android string button android-recyclerview

我有一个UI屏幕(CardViewActivity),带有一堆EditText行,供用户输入数据。用户完成后,单击UI上的“保存”按钮,将字符串数据输入保存到CardView,然后将其添加到RecyclerView列表中。当我尝试在Recycler活动(ListContactsActivity)中添加“保存”按钮引用(R.id.saveButtonRV)时,应用程序因按钮单击而崩溃。

ListContactsActivity 
...
public class ListContactsActivity extends AppCompatActivity {

    private ListContactsAdapter mContactsAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    final RecyclerView  mRecyclerView;
    ...
    Button saveButton = (Button) findViewById(R.id.saveButtonRV);
    // the below line caused the app to crash with NPE
    saveButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Contact contact = new Contact("", "");
            mContactsAdapter.addItem(contact);
            mRecyclerView.scrollToPosition(0);
        }
    });


CardViewActivity (for user input)
...
public class CardViewActivity extends AppCompatActivity {   

     private ListenerEditText cListenerEditText;
     ...
     public void onClickSave(View v) {
         int stringToDo = cListenerEditText.getText().toString().replace(" ", "").length();
         else if (stringToDo > 0 && stringNotes1 == 0 && stringNotes2 == 0 &&
            stringDueDate == 0 && stringDueTime ==0) {
        cListenerEditText.requestFocus();
        InputMethodManager imm = (InputMethodManager)
                getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(cListenerEditText.getWindowToken(), 0);
        cListenerEditText.clearFocus();
        Button saveButton = (Button)findViewById(R.id.saveButtonRV);
        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               // Can I reference Contact, the adapter and the RecyclerView
               // here to addItem (the CardView with string data) to the 
               // ReyclerView list?
            }
        });
    }
}


xml referencing the saveButtonRV

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/cardviewTwobuttons"
android:orientation="horizontal" >

<Space
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="14" />

<LinearLayout
    android:id="@+id/LinearLayout4"
    android:layout_marginTop="1dp"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="52"
    style="?android:attr/borderlessButtonStyle"
    android:background="@drawable/rect_forbuttons">

    <Button
        android:id="@+id/clearButton"
        android:text="Clear"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start|center"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        style="?android:attr/borderlessButtonStyle"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/clearbutton_rounded"
        android:drawableStart="@drawable/ic_clear_white_24dp"
        android:drawableLeft="@drawable/ic_clear_white_24dp"
        android:paddingStart="2dp"
        android:paddingLeft="2dp"
        android:paddingEnd="2dp"
        android:paddingRight="2dp"
        android:layout_marginEnd="12dp"
        android:layout_marginRight="12dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:onClick="onClickClear"
        android:nextFocusRight="@+id/saveButtonRV"  />

    <Button
        android:id="@+id/saveButtonRV"
        android:text="Save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|center"
        android:textColor="#FFFFFF"
        android:textStyle="bold"
        style="?android:attr/borderlessButtonStyle"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:background="@drawable/savebutton_rounded"
        android:drawableStart="@drawable/ic_save_white_24dp"
        android:drawableLeft="@drawable/ic_save_white_24dp"
        android:layout_marginStart="12dp"
        android:layout_marginLeft="12dp"
        android:layout_marginTop="4dp"
        android:layout_marginBottom="4dp"
        android:onClick="onClickSave"  />

</LinearLayout>

<Space
    android:layout_width="0dp"
    android:layout_height="match_parent"
    android:layout_weight="14" />

来自 ListContactsActivity 的logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.jdw.seventhscreen/com.example.jdw.seventhscreen.ListContactsActivity}: java.lang.NullPointerException
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
                                                                                   at android.app.ActivityThread.access$600(ActivityThread.java:130)
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                                   at android.os.Looper.loop(Looper.java:137)
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4745)
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
                                                                                   at dalvik.system.NativeStart.main(Native Method)
                                                                                Caused by: java.lang.NullPointerException
                                                                                   at com.example.jdw.seventhscreen.ListContactsActivity.onCreate(ListContactsActivity.java:58)
                                                                                   at android.app.Activity.performCreate(Activity.java:5008)
                                                                                   at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                                                                                   at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
                                                                                   at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
                                                                                   at android.app.ActivityThread.access$600(ActivityThread.java:130) 
                                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
                                                                                   at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                                   at android.os.Looper.loop(Looper.java:137) 
                                                                                   at android.app.ActivityThread.main(ActivityThread.java:4745) 
                                                                                   at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                                   at java.lang.reflect.Method.invoke(Method.java:511) 
                                                                                   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786) 
                                                                                   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
                                                                                   at dalvik.system.NativeStart.main(Native Method) 
02-02 23:47:10.529 15871-15871/com.example.jdw.seventhscreen I/Process: Sending signal.   

1 个答案:

答案 0 :(得分:1)

检查ListContactsActivity.java的第58行。这是您错误的来源。

您似乎使用ID R.id.saveButtonRV创建了一个按钮。你说你发布的xml是由cardviewactivity使用的。这意味着,您无法在其他活动中使用R.id.saveButtonRV。这就是您null saveButton ListContactsActivitynull的原因。因此,将onclick侦听器设置为null pointer exception值将导致startActivityForResult()

如果要将数据从一个活动传递到另一个活动,则应使用startActivityForResult()。查看this threadthis documentation/tutorial

基本上,您使用startActivity()代替Intent returnIntent = new Intent(); returnIntent.putExtra(someTag, userInputString); setResult(Activity.RESULT_OK, returnIntent); 。然后在你的CardViewActivity中你需要创建另一个intent然后把字符串放在那个intent对象中,这样做:

ListContactsActivity

然后在onActivityResult中,覆盖List<String>以获取意图中的数据。

由于您没有发布有关您的recyclerview的足够数据,我将假设您对recyclerview的行有一个单独的布局,并且您的recyclerview适配器中有List<String>

获取用户输入并将其传递回包含recyclerview的活动后,您只需将数据添加到recyclerview适配器,很可能是{{1}}。然后检查this有关如何将数据添加到recyclerview的信息。