我用SQlite创建了一个RecyclerView,并用Cardviews填充了它。单击Cardview后,新活动将开始显示书籍信息。为此,我使用RecyclerView Adapter类中的intent.putextra。对于我的书籍表中的Issue_status列,默认值为“可用”。现在,在图书信息活动中,我将使用textview显示其是否可用。下方有一个按钮,单击该按钮会将值更新为“不可用”。但是,单击更新是成功的,但不会实时更改活动。同样在返回到RecyclerView时,cardviews发行状态也不会改变。只有当我回到家并再次启动RecyclerView时,更新才会显示出来。我如何实时进行更新?
RecyclerViewAdapter
public RecyclerViewAdapter(Context mContext, List<book> mData) {
this.mContext = mContext;
this.mData = mData;
this.notifyDataSetChanged();
}
@Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
holder.bookname.setText(mData.get(position).getTitle());
holder.issuestatus.setText(mData.get(position).getIssue());
//set click listener
holder.cardView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(mContext, Book_Activity.class);
//passing data to the book activity
i.putExtra("title", mData.get(position).getTitle());
i.putExtra("issue", mData.get(position).getIssue());
//starting activity
mContext.startActivity(i);
}
});
更新方法
public boolean issue(String issue, String isbn){
ContentValues cv = new ContentValues();
cv.put("Issue_status", issue);
database.update("books", cv, "ISBN = ?", new String[] {isbn});
book Book = new book();
Book.setIssue(issue);
return true;
}
在RecyclerView中显示Cardview
database.open();
lstbook = databaseAccess.details("SELECT * FROM Books WHERE Category = ?", "Novel");
databse.close();
myrv = findViewById(R.id.recyclerview_id);
myAdapter = new RecyclerViewAdapter(this, lstbook);
myrv.setLayoutManager(new GridLayoutManager(this, 2));
myrv.setAdapter(myAdapter);
myAdapter.notifyDataSetChanged();
DisplayBookMethod
public ArrayList<book> details(String query, String category) {
ArrayList<book> list = new ArrayList<book>();
String[] where= new String[]{category};
Cursor cursor = database.rawQuery(query, where);
if (cursor!=null) {
if (cursor.moveToFirst()) {
do {
book Book = new book();
Book.setTitle(cursor.getString(1));
Book.setIssue(cursor.getString(10));
list.add(Book);
}while (cursor.moveToNext());
}
}cursor.close();
return list;
}
用于更新按钮的OnClickListener
Issue.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
databaseAccess.open();
databaseAccess.issue("Unavailable", ISBN);
Toast.makeText(getApplicationContext(), "Book Issued! Please collect from Library", Toast.LENGTH_LONG).show();
Issue.setVisibility(View.GONE);
Cancel.setVisibility(View.VISIBLE);
IssueStatus.setText(Issue_Status);
databaseAccess.close();
}
});
Cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
databaseAccess.open();
databaseAccess.issue("Available", ISBN);
Toast.makeText(getApplicationContext(), "Issue Cancelled! Please return book to Library if collected", Toast.LENGTH_LONG).show();
databaseAccess.close();
IssueStatus.setText(Issue_Status);
Cancel.setVisibility(View.GONE);
Issue.setVisibility(View.VISIBLE);
}
});