ArrayList <cart> items.add(new_item)出错;

时间:2017-01-02 04:34:36

标签: java android startactivityforresult

我有以下活动,它只负责将新对象添加到此对象的数组列表中,但是当我运行它时它会崩溃。 下面是所涉及的所有类和错误消息的一部分,因为它很长。

首先:这是调用第二个活动并为结果启动它的活动。 itemDetails.java:

public class itemDetails extends AppCompatActivity implements View.OnClickListener{
    int request_Code = 1;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.item);

        Bundle received = getIntent().getExtras();
        int position= received.getInt("position");
        long id=received.getLong("id");
        /*int id=0;getIntent().getIntExtra("id",id);
        int position=0;*/
//        getIntent().getIntExtra("id",id);getIntent().getIntExtra("position", position);
        Toast.makeText( this, "id= " + id + ".  and posistion=  "+ position, Toast.LENGTH_LONG).show();

        Integer[] picsId = {
                R.drawable.pic1,
                R.drawable.pic2,
                R.drawable.pic3,
                R.drawable.pic4,
                R.drawable.pic5,
                R.drawable.pic6,
                R.drawable.pic7
                };

        String[] picsNames={"Rose", "Red Dahlia","Tulip","Red rose","Aloe","Mother-in-Law's tonque","Snake"};
        String[] picCategory= {"Flowers","Flowers","Flowers","Flowers","Indoor plants","Indoor plants","Indoor plants"};
        double[] prices={5.5, 4, 3, 6, 35, 40, 42 };
        ImageView imgview = (ImageView) findViewById(R.id.item_image);
        imgview.setImageResource(picsId[position]);
        TextView nametxt= (TextView) findViewById(R.id.nametxtview);
        TextView categorytxt= (TextView) findViewById(R.id.categorytxtview);
        TextView pricetxt= (TextView) findViewById(R.id.pricetxtview);
        nametxt.setText(picsNames[position]);
        categorytxt.setText("Category:  " + picCategory[position]);

        pricetxt.setText(String.valueOf(prices[position]));


        Button cart_button= (Button)findViewById(R.id.Add2cartbutton);
        cart_button.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        TextView name=  (TextView) findViewById(R.id.nametxtview);
        TextView pricetxt = (TextView) findViewById(R.id.pricetxtview);
        // cast the retrieved price to double type:
        double price = Double.parseDouble(pricetxt.getText().toString());
        Intent data= new Intent(this, AddnewItemToCart.class);
        data.putExtra("name",name.getText().toString()); // store the item name in the new intent

        data.putExtra("price", price); //, this saves the whole sentence
        startActivityForResult(data,request_Code);
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == request_Code){
            if(resultCode == RESULT_OK) {
                Toast.makeText(this, data.getStringExtra("name") + "is successfully added to your cart", Toast.LENGTH_SHORT).show();
            }
            }

    }
}

然后,这是我的应用程序崩溃的活动。 AddnewItemToCart.java: 顺便说一句,它没有分配给任何布局。

public class AddnewItemToCart extends AppCompatActivity{


    ArrayList<cart> items;
    cart_adapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);


        Bundle receivedData=  getIntent().getExtras();
        String name= receivedData.getString("name");
        double price=receivedData.getDouble("price");

        cart new_item= new cart(name,price); // created new Task object.
//        Toast.makeText(this, new_item.itemName + "   and    "+ new_item.price , Toast.LENGTH_LONG).show();

        items.add(new_item);
        adapter.notifyDataSetChanged();
        Intent data= new Intent();
        data.putExtra("name",name);
        setResult(RESULT_OK,data);
        //---closes the activity---
        finish();
    }
}

这是找到的错误消息:

FATAL EXCEPTION: main
                  Process: swe.trial, PID: 4054
                  java.lang.RuntimeException: Unable to start activity ComponentInfo{swe.trial/swe.trial.CartActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2646)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
                      at android.app.ActivityThread.-wrap12(ActivityThread.java)
                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1460)
                      at android.os.Handler.dispatchMessage(Handler.java:102)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
                   Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
                      at android.widget.ArrayAdapter.getCount(ArrayAdapter.java:344)
                      at android.widget.ListView.setAdapter(ListView.java:493)
                      at swe.trial.CartActivity.onCreate(CartActivity.java:36)
                      at android.app.Activity.performCreate(Activity.java:6664)
                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1118)
                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2599)
                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2707)
    package swe.trial;

这是主要活动,是否有可能合并它? AddnewItemToCart.java ??

public class CartActivity extends AppCompatActivity implements View.OnClickListener {
    ArrayList<cart> items;
    cart_adapter adapter;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.shoppingcart);

        ListView cart_list= (ListView) findViewById(R.id.cart_list);
        cart_list.setAdapter(new cart_adapter(this, items));

        Button checkout = (Button) findViewById(R.id.checkout);
    }

    @Override
    public void onClick(View v) {


        Bundle receivedData=  getIntent().getExtras();
        String name= receivedData.getString("name");
        double price=receivedData.getDouble("price");

        cart new_item= new cart(name,price); // created new Task object.
//        Toast.makeText(this, new_item.itemName + "   and    "+ new_item.price , Toast.LENGTH_LONG).show();

        items.add(new_item);
        adapter.notifyDataSetChanged();
        Intent data= new Intent();
        data.putExtra("name",name);
        setResult(RESULT_OK,data);
        //---closes the activity---
        finish();

//        Toast.makeText(CartActivity.this, "Payment is not supported, Try again Later!", Toast.LENGTH_LONG).show();
    }
}


class cart_adapter extends ArrayAdapter<cart> {

    private ArrayList<cart> cart_items;
    private  Context context;

    public cart_adapter(Context context, ArrayList<cart> items) {
        super(context, R.layout.shoppingcart , items);
        this.context = context;
        this.cart_items = items;
    }


    public cart getItem(int position) {
        return cart_items.get(position);}


    public View getView(int position, View convertView, ViewGroup parent) {
        cart item = getItem(position);
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = inflater.inflate(R.layout.shoppingcart, parent, false);
        }
        TextView name= (TextView) convertView.findViewById(R.id.c_itemName);
        TextView price= (TextView) convertView.findViewById(R.id.c_itemPrice);
        name.setText(item.itemName);
        price.setText("price:  "+ item.price);

        return convertView;

    }


    public long getItemId(int position) {
        return position;

    }


}

4 个答案:

答案 0 :(得分:3)

您尚未初始化列表。在使用List / ArrayList之前,必须像这样初始化它:

ArrayList<cart> items = new ArrayList<>();

例如:

public class AddnewItemToCart extends AppCompatActivity{


ArrayList<cart> items;
cart_adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle receivedData=  getIntent().getExtras();
    String name= receivedData.getString("name");
    double price=receivedData.getDouble("price");

    //Initialize like this before using it.
    ArrayList<cart> items = new ArrayList<>();

    cart new_item= new cart(name,price); // created new Task object

    items.add(new_item);
    adapter.notifyDataSetChanged();
    Intent data= new Intent();
    data.putExtra("name",name);
    setResult(RESULT_OK,data);
    //---closes the activity---
    finish();
}
}

答案 1 :(得分:0)

AddnewItemToCart您正在设置items.add(new_item); 这是活动中的一个列表(也需要在另一个答案中发布实例化)和调用 adapter.notifyDataSetChanged();

您需要更新cart_adapter类中的项目列表。 例如:

adapter.addItem(new_item);//have to add method to update arraylist of items in adapter
adapter.notifyDataSetChanged();

答案 2 :(得分:0)

我查看了您的代码,您没有在AddnewItemToCart.java中初始化 ArrayList项

   items = new ArrayList<>;  // This is initialize your items;

答案 3 :(得分:0)

使用前请检查清单是否为空

if(items==null){
  items = new ArrayList<>();
}

现在你的班级看起来像是

    public class AddnewItemToCart extends AppCompatActivity{


ArrayList<cart> items;
cart_adapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    Bundle receivedData=  getIntent().getExtras();
    String name= receivedData.getString("name");
    double price=receivedData.getDouble("price");

    //check before use it


     if(items==null){
       items = new ArrayList<>();
     }

    cart new_item= new cart(name,price); // created new Task object

    items.add(new_item);
    adapter.notifyDataSetChanged();
    Intent data= new Intent();
    data.putExtra("name",name);
    setResult(RESULT_OK,data);
    //---closes the activity---
    finish();
}
}