我有一个用于列出电影的应用程序。用户应该能够在提要中列出他们最喜欢的电影。我使用SharedPreferences来实现这一点。对于列表,我使用ListView。然而,当我在列表中添加新电影时,它会替换为前一部。
这是ListActivity,
public class ListActivity extends AppCompatActivity {
ListView listView;
ImageView listTitleImage;
ImageView homeIcon;
ImageView userListIcon;
ImageView searchIcon;
ImageView accountIcon;
public static SharedPreferences sharedPreferences;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = findViewById(R.id.listView);
listTitleImage = findViewById(R.id.listTitleImage);
homeIcon = findViewById(R.id.homeListImageViewList);
userListIcon = findViewById(R.id.homeListImageViewList);
searchIcon = findViewById(R.id.searchImageViewList);
accountIcon = findViewById(R.id.accountImageViewList);
sharedPreferences = getApplicationContext().getSharedPreferences("Save", Context.MODE_PRIVATE);
String title = sharedPreferences.getString(String.valueOf(1),"No movie");
String poster = sharedPreferences.getString(String.valueOf(2),"No poster");
ArrayList<List> list = new ArrayList<>();
list.add(new List(title,poster));
ListAdapter listAdapter = new ListAdapter(this,R.layout.movie_list,list);
listView.setAdapter(listAdapter);
}
}
这就是我存储电影细节的地方resultList是我用来从api获取数据的数组列表。
@Override
public boolean onMenuItemClick(MenuItem item) {
if(item.getItemId() == R.id.menuAdd){
String title = resultList.get(pos).getTitle();
String posterpath = resultList.get(pos).getPoster_path();
sharedPreferences = context.getSharedPreferences("Save", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(String.valueOf(1),title);
editor.putString(String.valueOf(2),posterpath);
editor.apply();
Intent intent1 = new Intent(context,ListActivity.class);
context.startActivity(intent1);
return true;
}
else if(item.getItemId() == R.id.menuShowDetails){
int movieId = resultList.get(pos).getMovieId();
Intent intent1 = new Intent(context, MovieDetails.class);
intent1.putExtra("movie_id",movieId);
context.startActivity(intent1);
return true;
}
return false;
}
最好的解决方案是,您必须使用SQLite数据库或房间数据库来存储列表,因为如果您想更新,它很容易使用和每次更新。。。
对于Sqlite参考-https://www.javatpoint.com/android-sqlite-tutorial
房间数据库参考-https://medium.com/mindorks/using-room-database-android-jetpack-675a89a0e942