我有以下活动,该活动仅负责将新对象添加到此对象的数组列表中,但是当我运行时会崩溃。以下是涉及的所有类,也是错误消息的一部分,因为它长。
首先:这是调用第二个活动并启动结果的活动。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;
这是主要活动,是否可以合并它&amp;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;
}
}
您尚未初始化列表。在使用列表/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();
}
}
请检查列表是否为null或不使用
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();
}
}
在您的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();
我查看您的代码,您没有在addNewitemtocart.java
中初始化 arraylist项目 items = new ArrayList<>; // This is initialize your items;