单项视图活动中按收藏夹按钮时出现空指针异常

时间:2016-01-27 12:03:25

标签: android listview nullpointerexception sharedpreferences

我有一个列表视图,当在每个列表项上搞清楚时,它会打开一个新的单项itemview活动。在singleitemview活动中,我有一个收藏夹按钮,使用sharedpreferences将打开singleitemview活动的列表项添加到我的收藏夹活动中。要通过listitem点击,我使用jackson库将各自的listitem转换为json字符串,并通过意图使用putextra进入singleitemview活动。然后我将json字符串转换回singleitemview中的listitem对象并使用它添加到收藏夹

但现在当我点击singleitemview中的收藏夹按钮时,应用程序崩溃,重新打开应用程序后,listutem将添加到我最喜欢的活动中

这是代码

我列表活动的onitemclicklistener

    @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;
            }
    });
    }


}

指向nullpointer eception log cat的行是

                        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>

列出商品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>

我的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

4 个答案:

答案 0 :(得分:1)

findViewById点击事件初始化视图中,

首先不是一个好方法。在click事件之外初始化它。

第二次您的Button未正确初始化,这就是为什么它会变为空。

答案 1 :(得分:1)

<强>原因: 您收到此NullPointerException的原因是您尝试在imgbtn_favorite中访问不存在的singlelistitem.xml内的ID。 您只能在与Activity类关联的xml中访问变量。

解决方案:我注意到您仅使用该变量来设置Tag并更改ImageResource。您无法从其他活动执行此操作。为此你可以

  1. 将全局值存储在SharedPreferences中,并在listview再次打开时显示更改后的值。

  2. 或者,如果您不需要来打开新的Activity,您可以访问ListView Activity本身的View。

  3. 编辑:

    1. 您还可以使用startActivityForResult,以便将一些值发送回ListView活动,然后在变量中进行更改。您可以参考this link作为示例。

答案 2 :(得分:0)

替换

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

通过

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

答案 3 :(得分:-1)

你需要移动这一行:

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

从你的try catch中出来(把它放在这个块之前)。您尚未在else语句中初始化。