空指针异常按钮setOnClickListener(new OnClickListener()

时间:2013-07-01 06:13:40

标签: android android-listview

在列表行中显示按钮,并希望用户使用该按钮将列表项添加到购物车,但每当我加载列表获取错误不幸的是,如果我不在我的代码中使用按钮没有得到任何错误,应用程序已停止。

所以在这里我的问题在我尝试使用按钮时我的代码出了什么问题?

这是我遇到错误的一行:

    mImgAddCart.setOnClickListener(new OnClickListener() {

logcat的:

07-01 05:57:03.733: E/AndroidRuntime(779): FATAL EXCEPTION: main
07-01 05:57:03.733: E/AndroidRuntime(779): java.lang.NullPointerException
07-01 05:57:03.733: E/AndroidRuntime(779):  at com.example.sample.ItemsActivity$MyAsyncTask.onPostExecute(ItemsActivity.java:191)
07-01 05:57:03.733: E/AndroidRuntime(779):  at com.example.sample.ItemsActivity$MyAsyncTask.onPostExecute(ItemsActivity.java:1)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.os.AsyncTask.finish(AsyncTask.java:631)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.os.AsyncTask.access$600(AsyncTask.java:177)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.os.Handler.dispatchMessage(Handler.java:99)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.os.Looper.loop(Looper.java:137)
07-01 05:57:03.733: E/AndroidRuntime(779):  at android.app.ActivityThread.main(ActivityThread.java:5041)
07-01 05:57:03.733: E/AndroidRuntime(779):  at java.lang.reflect.Method.invokeNative(Native Method)
07-01 05:57:03.733: E/AndroidRuntime(779):  at java.lang.reflect.Method.invoke(Method.java:511)
07-01 05:57:03.733: E/AndroidRuntime(779):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-01 05:57:03.733: E/AndroidRuntime(779):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-01 05:57:03.733: E/AndroidRuntime(779):  at dalvik.system.NativeStart.main(Native Method)
07-01 05:57:07.172: E/Trace(806): error opening trace file: No such file or directory (2)

LazyAdapter.java:

     public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 
    String itemTitle, itemCost;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.listrow_items, null);

        final TextView title = (TextView)vi.findViewById(R.id.title); 
        final TextView cost = (TextView)vi.findViewById(R.id.cost); 
        ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);


        HashMap<String, String> item = new HashMap<String, String>();
        item = data.get(position);

        // Setting all values in listview
        title.setText(item.get(ItemsActivity.KEY_TITLE));
        cost.setText(item.get(ItemsActivity.KEY_COST));
        imageLoader.DisplayImage(item.get(com.example.sample.ItemsActivity.KEY_THUMB_URL), thumb_image);

        //Button mImgAddCart
        Button mImgAddCart = (Button) vi.findViewById(R.id.btn_add_to_order);
            mImgAddCart.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    itemTitle = title.getText().toString();
                    itemCost = cost.getText().toString();                  

                    if (Constants.sItem_Detail.size() <= 0) {
                        HashMap<String, String> sTempObj = new HashMap<String, String>();
                        sTempObj.put(KEY_TITLE, itemTitle);
                        sTempObj.put(KEY_COST, itemCost);
                        Constants.sItem_Detail.add(sTempObj);               
                        }                   

                    AlertDialog.Builder alertdialog = new AlertDialog.Builder(
                            ItemsActivity.this);
                    alertdialog.setTitle(getResources()
                            .getString(R.string.app_name));
                    alertdialog.setMessage("Item Added to Cart");

                    alertdialog.setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) 
                                {
                                    activity.finish();
                                }
                            });     
                    alertdialog.show();             
                }
            });

        return vi;
    }
}

行:

sTempObj.put(KEY_TITLE, itemTitle);

获得:

KEY_TITLE cannot be resolved to a variable

订单

AlertDialog.Builder alertdialog = new AlertDialog.Builder(ItemsActivity.this);

获得:

No enclosing instance of the type ItemsActivity is accessible in scope

订单

alertdialog.setTitle(getResources().getString(R.string.app_name));

获得:

The method getResources() is undefined for the type new View.OnClickListener(){}

6 个答案:

答案 0 :(得分:3)

您的 LazyAdapter 类代码应如下所示:

public class LazyAdapter extends BaseAdapter {

    private Activity activity;
    private ArrayList<HashMap<String, String>> data;
    private static LayoutInflater inflater=null;
    public ImageLoader imageLoader; 
    String itemTitle, itemCost;
    TextView title, cost;

    public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
    }

    public int getCount() {
        return data.size();
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        if(convertView==null)
            vi = inflater.inflate(R.layout.listrow_items, null);

        title = (TextView)vi.findViewById(R.id.title); 
        cost = (TextView)vi.findViewById(R.id.cost); 
        ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);


        HashMap<String, String> item = new HashMap<String, String>();
        item = data.get(position);

        // Setting all values in listview
        title.setText(item.get(ItemsActivity.KEY_TITLE));
        cost.setText(item.get(ItemsActivity.KEY_COST));
        imageLoader.DisplayImage(item.get(com.example.sample.ItemsActivity.KEY_THUMB_URL), thumb_image);

        //Button mImgAddCart
        Button mImgAddCart = (Button) vi.findViewById(R.id.btn_add_to_order);
            mImgAddCart.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    itemTitle = title.getText().toString();
                    itemCost = cost.getText().toString();                  

                    if (Constants.sItem_Detail.size() <= 0) {
                        HashMap<String, String> sTempObj = new HashMap<String, String>();
                        sTempObj.put(com.example.sample.ItemsActivity.KEY_TITLE, itemTitle);
                        sTempObj.put(com.example.sample.ItemsActivity.KEY_COST, itemCost);
                        Constants.sItem_Detail.add(sTempObj);               
                        }                  

        return vi;
    }
}

答案 1 :(得分:1)

如果你在listrow_items.xml中使用“btn_add_to_order”按钮,那么按钮的监听器应该在你的“LazyAdapter”类中看@下面的代码

 public class LazyAdapter extends BaseAdapter {

            private Activity activity;
            private ArrayList<HashMap<String, String>> data;
            private static LayoutInflater inflater=null;
            public ImageLoader imageLoader; 

            public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
                activity = a;
                data=d;
                inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                imageLoader=new ImageLoader(activity.getApplicationContext());
            }

            public int getCount() {
                return data.size();
            }

            public Object getItem(int position) {
                return position;
            }

            public long getItemId(int position) {
                return position;
            }

            public View getView(int position, View convertView, ViewGroup parent) {
                View vi=convertView;
                if(convertView==null)
                    vi = inflater.inflate(R.layout.listrow_items, null);

                TextView title = (TextView)vi.findViewById(R.id.title); 
                TextView cost = (TextView)vi.findViewById(R.id.cost); 
                ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);


                HashMap<String, String> item = new HashMap<String, String>();
                item = data.get(position);

                // Setting all values in listview
                title.setText(item.get(ItemsActivity.KEY_TITLE));
                cost.setText(item.get(ItemsActivity.KEY_COST));
                imageLoader.DisplayImage(item.get(com.example.sample.ItemsActivity.KEY_THUMB_URL), thumb_image);

                //Button mImgAddCart
                Button mImgAddCart = (Button) vi.findViewById(R.id.btn_add_to_order);
                    mImgAddCart.setOnClickListener(new OnClickListener() {

                        public void onClick(View v) {
                            // TODO Auto-generated method stub
                            itemTitle = txt_title.getText().toString();
                            itemCost = text_cost.getText().toString();                  

                            if (Constants.sItem_Detail.size() <= 0) {
                                HashMap<String, String> sTempObj = new HashMap<String, String>();
                                sTempObj.put(KEY_TITLE, itemTitle);
                                sTempObj.put(KEY_COST, itemCost);
                                Constants.sItem_Detail.add(sTempObj);               
                                }                   

                            AlertDialog.Builder alertdialog = new AlertDialog.Builder(
                                    ItemsActivity.this);
                            alertdialog.setTitle(getResources()
                                    .getString(R.string.app_name));
                            alertdialog.setMessage("Item Added to Cart");

                            alertdialog.setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(DialogInterface dialog,
                                                int which) 
                                        {
                                            finish();
                                        }
                                    });     
                            alertdialog.show();             
                        }
                    });

                return vi;
            }
        }

答案 2 :(得分:1)

快速修复LazyAdapter类中的当前问题:

<强>获得:

KEY_TITLE cannot be resolved to a variable

解决方案: 确保在ItemsActivity

中将KEY_TITLE声明为公共静态字段

<强>获得:

在范围

中无法访问ItemsActivity类型的封闭实例
AlertDialog.Builder alertdialog = new AlertDialog.Builder(ItemsActivity.this);

解决方案: 使用Activity上下文将AlertDialog显示为:

AlertDialog.Builder alertdialog = new AlertDialog.Builder(activity);

<强>获得:

alertdialog.setTitle(getResources().getString(R.string.app_name));

对于新的View.OnClickListener(){}类型,未定义方法getResources() 解决方案: 使用Activity上下文访问Resources:

alertdialog.setTitle(activity.getResources().getString(R.string.app_name));

答案 3 :(得分:1)

您刚刚初始化了按钮,然后调用方法......

看看这可能会有所帮助。

 public class LazyAdapter extends BaseAdapter {

 private Activity activity;
 private ArrayList<HashMap<String, String>> data;
 private static LayoutInflater inflater=null;
 public ImageLoader imageLoader; 
 String itemTitle, itemCost;

 public LazyAdapter(Activity a, ArrayList<HashMap<String, String>> d) {
    activity = a;
    data=d;
 inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);      
    imageLoader=new ImageLoader(activity.getApplicationContext());
}

public int getCount() {
    return data.size();
}

public Object getItem(int position) {
    return position;
}

public long getItemId(int position) {
    return position;
}

public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.listrow_items, null);

    final TextView title = (TextView)vi.findViewById(R.id.title); 
    final TextView cost = (TextView)vi.findViewById(R.id.cost); 
    ImageView thumb_image = (ImageView) vi.findViewById(R.id.list_image);
    Button mImgAddCart = (Button) vi.findViewById(R.id.btn_add_to_order);


    HashMap<String, String> item = new HashMap<String, String>();
    item = data.get(position);

    // Setting all values in listview
    title.setText(item.get(ItemsActivity.KEY_TITLE));
    cost.setText(item.get(ItemsActivity.KEY_COST));
    imageLoader.DisplayImage(item.get(com.example.sample.ItemsActivity.KEY_THUMB_URL), thumb_image);

    //Button mImgAddCart

        mImgAddCart.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                itemTitle = title.getText().toString();
                itemCost = cost.getText().toString();                  

                if (Constants.sItem_Detail.size() <= 0) {
                    HashMap<String, String> sTempObj = new HashMap<String, String>();
                    sTempObj.put(KEY_TITLE, itemTitle);
                    sTempObj.put(KEY_COST, itemCost);
                    Constants.sItem_Detail.add(sTempObj);               
                    }                   

                AlertDialog.Builder alertdialog = new AlertDialog.Builder(
                        ItemsActivity.this);
                alertdialog.setTitle(getResources()
                        .getString(R.string.app_name));
                alertdialog.setMessage("Item Added to Cart");

                alertdialog.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) 
                            {
                                activity.finish();
                            }
                        });     
                alertdialog.show();             
            }
        });

    return vi;
}

}

答案 4 :(得分:0)

您尚未在txt_title课程中初始化text_costItemsActivity

假设您有activity_item中的文字视图。

        setContentView(R.layout.activity_item);
        txt_title = (TextView) findViewById(R.id.title);
        text_cost = (TextView) findViewById(R.id.cost);  

答案 5 :(得分:0)

更改getResources行以使用活动上下文。还要在活动类中将KEY_TITLE声明为public。

 AlertDialog.Builder alertdialog = new AlertDialog.Builder(
                        a);
                alertdialog.setTitle(a.getResources()
                        .getString(R.string.app_name));
                alertdialog.setMessage("Item Added to Cart");

                alertdialog.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) 
                            {
                                a.finish();
                            }
                        });     
                alertdialog.show();