1

I have a listview which opens a new single itemview activity when clucked on each list item . Inside the singleitemview activity i have a favorites button which adds the list item that opened the singleitemview activity to my favorites activity using sharedpreferences.. To pass the listitem clicked I use jackson library to convert respective listitem to json string and use putextra via intent into singleitemview activity . Then I convert back the json string to listitem object in singleitemview and use it to add to favorites

But now when i click the favorite button in singleitemview the app crashes and after reopening the app the listutem is added to my favorites activity

Here is the code

onitemclicklistener of my list activity

    @Override
public void onItemClick(AdapterView<?> parent, View view, int position,
                        long id) {

                            ObjectMapper mapper = new ObjectMapper();
                            Product pro = productListAdapter.getItem(position);
    try
    {
        String jsonInString = mapper.writeValueAsString(pro);
        Intent intent = new Intent(activity.getApplicationContext(), SingleItemView.class);
        intent.putExtra("selected item", jsonInString);

        startActivity(intent);
    }
    catch (JsonProcessingException e)
    {//something went wrong
          } 



}

singleitemview.java

public class SingleItemView extends Activity
 {
ProductListAdapter padaptr;
SharedPreference sharedPreference;

List<Product> products = null;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    // TODO: Implement this method
    super.onCreate(savedInstanceState);
    setContentView(R.layout.singleitem);
    sharedPreference = new SharedPreference();
    padaptr = new ProductListAdapter(SingleItemView.this, products);



    Button btn = (Button) findViewById(R.id.singleitemButton1);
    btn.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v){

            Bundle extras = getIntent().getExtras();
            String jsonObj = extras.getString("selected item");
            ObjectMapper mapper = new ObjectMapper();

            try
            {
                Product pro = mapper.readValue(jsonObj, Product.class);

                       //the fav image present on evry list item
                ImageView button = (ImageView) findViewById(R.id.imgbtn_favorite);
                if (checkFavoriteItem(pro)) {

                    sharedPreference.removeFavorite(SingleItemView.this, pro);
                    button.setTag("no");
                    button.setImageResource(R.drawable.heart_grey);
                    Toast.makeText(SingleItemView.this,
                                   SingleItemView.this.getResources().getString(R.string.remove_favr),
                                   Toast.LENGTH_SHORT).show();
                } else {
                    sharedPreference.addFavorite(SingleItemView.this, pro);
                    Toast.makeText(SingleItemView.this,
                                   SingleItemView.this.getResources().getString(R.string.add_favr),
                                   Toast.LENGTH_SHORT).show();

                    button.setTag("yes");
                    button.setImageResource(R.drawable.heart_red);
                }
            }
            catch (IOException e)
            {};





        }



            private boolean checkFavoriteItem(Product checkProduct) {
                boolean check = false;
                List<Product> favorites = sharedPreference.getFavorites(getApplicationContext());
                if (favorites != null) {
                    for (Product product : favorites) {
                        if (product.equals(checkProduct)) {
                            check = true;
                            break;
                        }
                    }
                }
                return check;
            }
    });
    }


}

the line pointing nullpointer eception log cat is

                        button.setTag("yes");

singleitem.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="#A25550"
    android:gravity="center">

    <Button
        android:layout_height="wrap_content"
        android:text="Addcto fav"
        android:layout_width="wrap_content"
        android:id="@+id/singleitemButton1"/>

    <TextView
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:layout_width="wrap_content"
        android:id="@+id/singleitemTextView1"/>

</LinearLayout>

list item xml

<?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/product_list_item_bg"
android:descendantFocusability="blocksDescendants" >

<RelativeLayout
    android:id="@+id/pdt_layout_item"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" >

    <TextView
        android:id="@+id/txt_pdt_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="6dp" />

    <TextView
        android:id="@+id/txt_pdt_price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt_pdt_name"
        android:padding="6dp" />

    <TextView
        android:id="@+id/txt_pdt_desc"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/txt_pdt_price"
        android:padding="6dp" />

    <ImageView
        android:id="@+id/imgbtn_favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/txt_pdt_desc"
        android:layout_alignParentRight="true"
        android:layout_marginRight="3dp"
        android:background="@null"
        android:contentDescription="@string/favorites" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_below="@+id/pdt_layout_item"
    android:background="@color/view_divider_color" />

  </RelativeLayout>

my logcat

01-27 17:29:19.777 14852 14852 E   AndroidRuntime FATAL EXCEPTION: main
01-27 17:29:19.777 14852 14852 E   AndroidRuntime java.lang.NullPointerException
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at com.mycompany.myapp.SingleItemView$100000000.onClick(SingleItemView.java:62)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.view.View.performClick(View.java:4452)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.widget.Button.performClick(Button.java:148)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.view.View$PerformClick.run(View.java:18428)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.os.Handler.handleCallback(Handler.java:725)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.os.Handler.dispatchMessage(Handler.java:92)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.os.Looper.loop(Looper.java:176)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at android.app.ActivityThread.main(ActivityThread.java:5365)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at java.lang.reflect.Method.invokeNative(Native Method)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at java.lang.reflect.Method.invoke(Method.java:511)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
01-27 17:29:19.777 14852 14852 E   AndroidRuntime at dalvik.system.NativeStart.main(Native Method)
01-27 17:29:20.316 17044 17044 D   AndroidRuntime Calling main entry com.android.commands.am.Am
user5524159
  • 553
  • 5
  • 16

4 Answers4

1

First of all in click event initializing view by findViewById is not a good approach. Initialize it outside of click event.

Second your Button is not initializing properly, that's why it's getting null.

Sayem
  • 4,891
  • 3
  • 28
  • 43
  • Thanx very much for that advice So i initializeed the button outside click event but still the same problem . How shall i solve ir – user5524159 Jan 27 '16 at 12:22
  • can you post your singleitem.xml file? in that xml file is there any id exist as "imgbtn_favorite" ? – Sayem Jan 27 '16 at 12:24
  • the image button exists in list item of list view not in single item view – user5524159 Jan 27 '16 at 12:26
  • my assumption is right. you can not initialize any view which does not exist in your activity. in "SingleItemView" activity you inflated "singleitem.xml" which does not contains your expected view. Thats why when he tries to find "imgbtn_favorite" in "SingleItemView" , it finds nothing. so you are getting null. Read some article about data passing between activity. it will help. – Sayem Jan 27 '16 at 12:32
  • I came to android from ios developing can you texplain poease – user5524159 Jan 27 '16 at 12:38
  • so i have to pass it via intent in onitemclick same as i've did for the list item – user5524159 Jan 27 '16 at 12:40
  • that's huge things to explain everything. If you are new start from this : http://developer.android.com/training/index.html . search "start activity for result". – Sayem Jan 27 '16 at 12:45
  • thnx for your advice , appreiate it – user5524159 Jan 27 '16 at 12:46
1

Reason: The reason you are getting this NullPointerException is that you are trying to access an id as imgbtn_favorite in the singlelistitem.xml where it does not exist. You can access a variable only in the xml associated with the Activity class.

Solution: I noticed that you were using that variable only to set the Tag and change ImageResource. You can't do this from another Activity. For this you can either

  1. Store a global value in SharedPreferences and show the changed value when the listview opens again.

  2. Or, if you do not need to open a new Activity, you can access the View in the ListView Activity itself.

EDIT:

  1. You can also use startActivityForResult so that you send some values back to the ListView Activity and then make the changes in the variable. You can refer to this link for an example.
Community
  • 1
  • 1
Ankit Aggarwal
  • 2,367
  • 24
  • 30
0

Replace

ImageView button = (ImageView) findViewById(R.id.imgbtn_favorite);

By

ImageView button = (ImageView) v.findViewById(R.id.imgbtn_favorite);
P. Jairaj
  • 1,033
  • 1
  • 6
  • 8
-1

You need to move this line:

ImageView button = (ImageView) v.findViewById(R.id.imgbtn_favorite);

out of your try catch (place it just before this block). You have not initialized in your else statement.

Kristy Welsh
  • 7,828
  • 12
  • 64
  • 106