我非常坚持使用 Parcelable 将对象从一个活动传递到另一个活动,但是我在 line 处遇到空指针异常Log.i("Name",""+rcp.getName());
,您可以在下面的代码中检查这一行。请在最后检查代码 CookingDataModel 类。
这是对象接收活动的代码
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);// No title to display
setContentView(R.layout.recipe_ingredient_detail);
CookingDataModel cook = new CookingDataModel();
RecipeDataModel rcp;
ArrayList<IngredientDataModel> ing;
Bundle bundle = this.getIntent().getExtras();
if(bundle!=null)
cook = bundle.getParcelable("Cooking");
rcp = cook.getRecipe();
ing = cook.getIngredientList();
Log.i("Name",""+rcp.getName());
Log.i("Decrp",""+rcp.getDescription());
Log.i("Duration",""+rcp.getPrepTime());
Log.i("Instructions",""+rcp.getInstructions());
for(int k = 0; k < ing.size(); k++)
{
Log.i("Item Name",""+ing.get(k).getItemName());
Log.i("Item Amount",""+ing.get(k).getItemAmount());
}
}
这是我发送对象的代码CookingDataModel
。
ListView recepeListView = getListView();
recepeListView.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3)
{
CookingDataModel cook = recpeList.get(position);
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("Cooking",cook);
intent.putExtras(bundle);
intent.setClass(RecipeList.this,RecipeIngredientDetail.class);
startActivity(intent);
}
});
这是 CookingDataModel 类的代码。
public class CookingDataModel implements Parcelable{
private RecipeDataModel recipe = null;
private ArrayList<IngredientDataModel> ingredientList = null;
public RecipeDataModel getRecipe() {
return recipe;
}
public void setRecipe(RecipeDataModel recipe) {
this.recipe = recipe;
}
public ArrayList<IngredientDataModel> getIngredientList() {
return ingredientList;
}
public void setIngredientList(ArrayList<IngredientDataModel> ingredientList) {
this.ingredientList = ingredientList;
}
public static final Parcelable.Creator<CookingDataModel> CREATOR = new Parcelable.Creator<CookingDataModel>()
{
public CookingDataModel createFromParcel(Parcel in)
{
return new CookingDataModel(in);
}
public CookingDataModel[] newArray(int size)
{
return new CookingDataModel[size];
}
};
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel arg0, int arg1) {
// TODO Auto-generated method stub
}
public CookingDataModel(Parcel in) {
// TODO Auto-generated constructor stub
}
public CookingDataModel()
{
}
}
请在这方面帮助我,以便我可以继续我的项目。提前致谢。