将第二个项目添加到listview会覆盖第一个项目

时间:2015-10-01 19:02:23

标签: android listview

我有一个带有空ListView的活动和一个用户创建新项目的按钮(在第二个活动中)。创建第一个项目并将其重新添加到ListView,但第二个项目会覆盖第一个项目,或者它会在某个地方消失。以下是我的代码

public class Series extends Activity implements View.OnClickListener{

ListView seriesView;
Button btnNewSerie;
String titleNew = "";
Integer seasonNew = 1;
Integer seasonLengthNew = 23;
private ArrayList<SerieModel> list;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_series);

    seriesView = (ListView) findViewById(R.id.seriesView);
    btnNewSerie = (Button) findViewById(R.id.btnAddSerie);
    btnNewSerie.setOnClickListener(this);
    list = new ArrayList<>();

    MyArrayAdapter myArrayAdapter = new MyArrayAdapter(this, list);
    seriesView.setAdapter(myArrayAdapter);
    // click and edit a serie
    seriesView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            Intent intentEdit = new Intent(Series.this, EditSerie.class);
            String title = (String) seriesView.getItemAtPosition(position);
            intentEdit.putExtra("Title", title);
            // TODO: 01/10/15 Add season and last chapter as extras
            startActivity(intentEdit);
        }
    });

    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        titleNew = extras.getString("Title");
        seasonNew = extras.getInt("Season");
        seasonLengthNew = extras.getInt("Duration");

        SerieModel addedSerie = new SerieModel(titleNew, seasonNew, seasonLengthNew);
        list.add(addedSerie);
        myArrayAdapter.notifyDataSetChanged();
    }


}

public void setListData() {
    for (int i = 0; i < list.size(); i++) {
        final SerieModel tempSerie = new SerieModel(titleNew, seasonNew, seasonLengthNew);

    }
}
}

1 个答案:

答案 0 :(得分:0)

发现问题:因为新项目是在另一项活动中创建的,所以项目存储在&#39; list&#39;调用OnPause时会被销毁(忘记Activity生命周期)。我的解决方案是在this tutorial之后将项目存储在SQLite数据库中。