【发布时间】:2021-06-22 07:26:45
【问题描述】:
所以我创建了一个应用程序,用户可以在其中输入有关他看过的电影的详细信息,例如名称、演员表、评分...等,并且详细信息存储在数据库中的表名称中,该表名称在 DataBaseHelper 类中初始化作为
public static final String TABLE_NAME = "table1";
在下面的代码段中,我创建了一个列表视图并显示了电影的名称,每个名称前面都有一个复选框。如果勾选复选框,则表示它是收藏夹,否则不是收藏夹...最初,如果电影是收藏夹,表格中的列设置为“否” 当勾选并按下按钮时,我希望所有带有勾选的电影名称在数据库中更新为“是”。
带有列表视图的DisplayActivity类
public class DisplayActivity extends AppCompatActivity {
DataBaseHelper myDb;
ListView movieNList;
Button addFavoritesB,button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
movieNList =(ListView) findViewById(R.id.moviesLV);
myDb=new DataBaseHelper(this);
addFavoritesB=(Button) findViewById(R.id.addButton);
button=(Button) findViewById(R.id.button);
ArrayList<String> theList=new ArrayList<>();
Cursor data=myDb.getData();
if (data.getCount()==0){
Toast.makeText(DisplayActivity.this,"The Database is empty",Toast.LENGTH_SHORT).show();
}else{
//Adds data to the list view
while(data.moveToNext()){
theList.add(data.getString(1));
Collections.sort(theList);
ListAdapter listAdapter=new ArrayAdapter<>(this, android.R.layout.simple_list_item_multiple_choice,theList);
movieNList.setAdapter(listAdapter);
}
}
buttonAction();
}
public void buttonAction(){
myDb.getWritableDatabase();
addFavoritesB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String itemSelected="Selected items : \n";
for (int i=0;i<movieNList.getCount();i++){
if (movieNList.isItemChecked(i)){
itemSelected += movieNList.getItemAtPosition(i)+"\n";
System.out.println(itemSelected);
myDb.updateFavorites(itemSelected,"yes");
}
}
}
});
}
DataBaseHelper 类中更新收藏列的方法
public boolean updateFavorites(String name,String favorites) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("FAVORITES", favorites);
Cursor res = db.rawQuery("select * from table1 where name=? ", new String[]{name});
if (res.getCount() > 0) {
long result = db.update(TABLE_NAME, contentValues, "name=?", new String[]{name});
if (result == -1) {
return false;
} else {
return true;
}
} else {
return false;
}
}
当我这样尝试时,列不会更新....请帮助
【问题讨论】:
标签: java sql sqlite sql-update android-sqlite