0

I have a UI screen (CardViewActivity) with a bunch of EditText lines for data input for the user. When the user is done they click the "Save" button on the UI to save the string data input to a CardView that is then added to a RecyclerView list. When I tried to add the Save button reference (R.id.saveButtonRV) in the Recycler activity (ListContactsActivity), the app crashed due to the Button click.

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

logcat from ListContactsActivity:

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.   
Evin1_
  • 12,292
  • 9
  • 45
  • 47
AJW
  • 1,578
  • 3
  • 36
  • 77
  • Yes, setContentView() is called in onCreate(). I first put saveButton code in ListContacts Activity and app crashed before realizing I really want to run the click is in the CardViewActivity. See additions above. – AJW Feb 03 '16 at 01:04
  • Are you trying to fix the NPE in ListContactsActivity or get the CardViewActivity saveButton working? Choose one and focus on that... – Daniel Nugent Feb 03 '16 at 01:11
  • My preference is to get the CardViewActivity saveButton working. I can remove the Button and setOnClickListener code in the ListContactsActivity as long as I can figure out a way to add the CardView item to the RecycerView list from the CardViewActivity. – AJW Feb 03 '16 at 01:14
  • Where did you use that layout? CardViewActivity or the other one? – hehe Feb 03 '16 at 01:25
  • CardViewActivity which uses cardviewinput.xml file. That file uses a viewflipper to load the Viewflipper layout that has the saveButtonRv Button. – AJW Feb 03 '16 at 01:28

1 Answers1

1

Check line 58 of ListContactsActivity.java. That is the source of your error.

It seems that you created a button using the id R.id.saveButtonRV. You said that the xml that you posted is used by the cardviewactivity. That means, you cannot use R.id.saveButtonRV in other activities. That's why you got null value for your saveButton in your ListContactsActivity. Thus, setting onclick listener to a null value will result in null pointer exception

If you want to pass data from one activity to another, you should use startActivityForResult(). Check this thread and this documentation/tutorial.

Basically, you use startActivityForResult() instead of startActivity(). Then in your CardViewActivity you need to create another intent then put the string inside that intent object, do it like this:

Intent returnIntent = new Intent();
returnIntent.putExtra(someTag, userInputString);
setResult(Activity.RESULT_OK, returnIntent);

Then in your ListContactsActivity, override onActivityResult to get the data from the intent.

Since you didn't post enough data regarding your recyclerview, I will assume you have a separate layout for the rows of your recyclerview, and that you have a List<String> inside your recyclerview adapter.

After getting the user input, and having it passed back to your activity which contains the recyclerview, you just have to add data to your recyclerview adapter, most likely you have List<String>. And then check this on how to add data to recyclerview.

Community
  • 1
  • 1
hehe
  • 1,294
  • 13
  • 26
  • Yes I realize that now so I will be deleting the Button code lines 57 to 65 in ListContactsActivity. So now I need to figure out how to add the CardView item to the RecycerView list from the CardViewActivity upon clicking the Save button there. – AJW Feb 03 '16 at 01:34
  • Did you figure out how to pass data from one activity to another? – hehe Feb 03 '16 at 01:35
  • No, that's what I'm asking. I think I need to pass the user input string data collected from the CardViewAcitivty and pass it to the ListContactActivity to create the CardView item with the data, and then load the CardView into the RecyclerView list. Not sure how best to achieve. – AJW Feb 03 '16 at 01:39
  • check my edited answer, use `startActivityForResult()`. Check the links that I gave. – hehe Feb 03 '16 at 01:41
  • Ok will do. Using startActivityForResult() the user input data from the CardViewActivity is passed back to the RecyclerView activity? – AJW Feb 03 '16 at 01:46
  • p.s. I do indeed have a separate layout for each item (row) of the RecyclerView. Also, the adapter uses List<> and ArrayList<> for the items. – AJW Feb 03 '16 at 01:49
  • Ok I will read up on the documents you recommended. One question though, I don't use startActivity() anywhere currently, only onCreate for each Activity. What did you mean with your mention of startActivity? – AJW Feb 03 '16 at 02:11
  • Then how are you able to get from `ListContactsActivity` to `CardViewActivity` without using startActivity? – hehe Feb 03 '16 at 02:19
  • Are you saying use startActivityForResult() rather than startActivity() to start the intent to go from CardViewActivity to ListContactsActivity? – AJW Feb 03 '16 at 02:22
  • let me just clarify, you go from `CardViewActivity` to `ListContactsActivity` or the other way around? I mean, which is your starting activity? – hehe Feb 03 '16 at 02:28
  • The starting activity is the RecyclerView list. It creates a blank CardView as the default layout to show the user an example of a CardView. Then the user clicks to get to the CardViewActivity, they enter some data on the EditText lines. Clicking the Save button, I want the user's data to be put into a new CardView and replace the default layout (with the blank CardView) with a new layout that shows the user's CardView with their data. I have all of the code done for switching the layouts, I just need to get the data into the user CardView and onto the RecyclerView list of their CardViews. – AJW Feb 03 '16 at 02:34
  • p.s. now I maybe understand your earlier question. I use startActivity() on a button on the toolbar of the ListContactsActivity file to go to CardViewActivity to get the user input. I want to get that user input data and put it back into a new CardView for the RecyclerView list of the ListContactsActivity. – AJW Feb 03 '16 at 02:45
  • Ok, then you have to use startActivityforResult instead. Then in your ListContactsActivity override onActivityResult. – hehe Feb 03 '16 at 02:46
  • Got it. So let's assume I get the user data to the ListContactsActivity. Am I correct that I will then create the new item for the CardView in ListContactsActivity because I have everything I need there for updating the RecyclerView list? – AJW Feb 03 '16 at 02:54
  • Yes, check the last link that I gave for guide on how to add data in recyclerview. – hehe Feb 03 '16 at 02:57
  • Will do, thanks for your patience and expertise in answering all of my questions. Cheers. – AJW Feb 03 '16 at 02:59