所以我提出一個實現了自定義類的Android應用程序傳遞給其他活動。我想創建一個Menu_Organizer類的對象到其他活動,但是在初始化對象並將它發送到下一個Activity之後,該對象爲NULL。下面是類:自定義對象未通過的意圖PutExtra
菜單項類
import java.io.Serializable;
public class Menu_Items implements Serializable {
private String Name = "";
private String Description = "";
private float Price = 0.0f;
private String Category = "";
/* Getters and Setters*/
}
菜單管理類:
public class Menu_Organizer implements Serializable {
ArrayList<String> Categories;
ArrayList<Menu_Items> Food;
// EDITED
public Menu_Organizer() {
Categories = new ArrayList<String>();
Food = new ArrayList<Menu_Items>();
}
/* Other class methods */
}
第一個活動(主)
public class MainActivity extends AppCompatActivity {
private Button btn;
public Menu_Organizer menu;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onclick();
}
public void onclick() {
btn = (Button) findViewById(R.id. btn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Menu_Organizer menu = new Menu_Organizer();
menu.New_Menu_Item("Carne", "Pollo", "Pollo Asado Rico!", 4.55f);
Intent activity2= new Intent(MainActivity.this,temp.class);
activity2.putExtra("Menu", menu);
startActivity(activity2);
}
});
}
}
次活動
public class temp extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_Second);
Bundle bundle = getIntent().getExtras();
Menu_Organizer menu = (Menu_Organizer) bundle.getSerializable("Menu");
String str= menu.Food.get(0).getName();
}
}
的'Intent'在'MainActivity'被打開''temp' Activity',但對方'你已經發布Activity'類是'秒'。 –
你應該顯示你的New_Menu_Item實現。我的猜測是,在添加項目之前,您並未創建Food的新ArrayList實例。 –
http://stackoverflow.com/questions/4233873/how-do-i-get-extra-data-from-intent-on-android試過這個而不是'Bundle bundle = getIntent()。getExtras();'? – iCantSeeSharp