我想将ListView
更改为RecyclerView
。这是我的主要活动:
Button btnAdd, btnGetAll;
TextView note_Id;
@Override
public void onClick(View view) {
if (view == findViewById(R.id.btnAdd)) {
Intent intent = new Intent(this, NoteDetail.class);
intent.putExtra("note_Id", 0);
startActivity(intent);
} else {
NoteRepo repo = new NoteRepo(this);
ArrayList<HashMap<String, String>> noteList = repo.getNoteList();
if (noteList.size() != 0) {
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
note_Id = (TextView) view.findViewById(R.id.note_Id);
String noteId = note_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(), NoteDetail.class);
objIndent.putExtra("note_Id", Integer.parseInt(noteId));
startActivity(objIndent);
}
});
ListAdapter adapter = new SimpleAdapter(MainActivity.this, noteList, R.layout.view_note_entry, new String[]{"id", "title"}, new int[]{R.id.note_Id, R.id.note_title});
setListAdapter(adapter);
} else {
Toast.makeText(this, "No note!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnAdd.setOnClickListener(this);
btnGetAll = (Button) findViewById(R.id.btnGetAll);
btnGetAll.setOnClickListener(this);
}
这是我的NoteDetail
课程:
Button btnSave , btnDelete;
Button btnClose;
EditText editTextTitle;
EditText editTextNote;
private int _Note_Id=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_detail);
btnSave = (Button) findViewById(R.id.btnSave);
btnDelete = (Button) findViewById(R.id.btnDelete);
btnClose = (Button) findViewById(R.id.btnClose);
editTextTitle = (EditText) findViewById(R.id.editTextTitle);
editTextNote = (EditText) findViewById(R.id.editTextNote);
btnSave.setOnClickListener(this);
btnDelete.setOnClickListener(this);
btnClose.setOnClickListener(this);
_Note_Id =0;
Intent intent = getIntent();
_Note_Id =intent.getIntExtra("note_Id", 0);
NoteRepo repo = new NoteRepo(this);
Note note = new Note();
note = repo.getNoteById(_Note_Id);
editTextTitle.setText(note.title);
editTextNote.setText(note.note);
}
public void onClick(View view) {
if (view == findViewById(R.id.btnSave)){
NoteRepo repo = new NoteRepo(this);
Note note = new Note();
note.note=editTextNote.getText().toString();
note.title=editTextTitle.getText().toString();
note.note_ID=_Note_Id;
if (_Note_Id==0){
_Note_Id = repo.insert(note);
Toast.makeText(this,"New Note Insert",Toast.LENGTH_SHORT).show();
}else{
repo.update(note);
Toast.makeText(this,"Note Record updated",Toast.LENGTH_SHORT).show();
}
}else if (view== findViewById(R.id.btnDelete)){
NoteRepo repo = new NoteRepo(this);
repo.delete(_Note_Id);
Toast.makeText(this, "Note Record Deleted", Toast.LENGTH_SHORT);
finish();
}else if (view== findViewById(R.id.btnClose)){
finish();
}
}
这是我的NoteRepo
课程:
public NoteRepo(Context context) {
dbHelper = new DBHelper(context);
}
public int insert(Note note) {
//Open connection to write data
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Note.KEY_note,note.note);
values.put(Note.KEY_title, note.title);
// Inserting Row
long note_Id = db.insert(Note.TABLE, null, values);
db.close(); // Closing database connection
return (int) note_Id;
}
public void delete(int note_Id) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
// It's a good practice to use parameter ?, instead of concatenate string
db.delete(Note.TABLE, Note.KEY_ID + "= ?", new String[] { String.valueOf(note_Id) });
db.close(); // Closing database connection
}
public void update(Note note) {
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(Note.KEY_note,note.note);
values.put(Note.KEY_title, note.title);
// It's a good practice to use parameter ?, instead of concatenate string
db.update(Note.TABLE, values, Note.KEY_ID + "= ?", new String[] { String.valueOf(note.note_ID) });
db.close(); // Closing database connection
}
public ArrayList<HashMap<String, String>> getNoteList() {
//Open connection to read only
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
Note.KEY_ID + "," +
Note.KEY_title + "," +
Note.KEY_note +
" FROM " + Note.TABLE;
//Note note = new Note();
ArrayList<HashMap<String, String>> noteList = new ArrayList<HashMap<String, String>>();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
HashMap<String, String> note = new HashMap<String, String>();
note.put("id", cursor.getString(cursor.getColumnIndex(Note.KEY_ID)));
note.put("title", cursor.getString(cursor.getColumnIndex(Note.KEY_title)));
noteList.add(note);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return noteList;
}
public Note getNoteById(int Id){
SQLiteDatabase db = dbHelper.getReadableDatabase();
String selectQuery = "SELECT " +
Note.KEY_ID + "," +
Note.KEY_title + "," +
Note.KEY_note +
" FROM " + Note.TABLE
+ " WHERE " +
Note.KEY_ID + "=?";// It's a good practice to use parameter ?, instead of concatenate string
int iCount =0;
Note note = new Note();
Cursor cursor = db.rawQuery(selectQuery, new String[] { String.valueOf(Id) } );
if (cursor.moveToFirst()) {
do {
note.note_ID =cursor.getInt(cursor.getColumnIndex(Note.KEY_ID));
note.title =cursor.getString(cursor.getColumnIndex(Note.KEY_title));
note.note =cursor.getString(cursor.getColumnIndex(Note.KEY_note));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return note;
}
这是我的DBHelper
课程:
private static final int DATABASE_VERSION = 4;
// Database Name
private static final String DATABASE_NAME = "crud.db";
public DBHelper(Context context ) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
//All necessary tables you like to create will create here
String CREATE_TABLE_NOTE = "CREATE TABLE " + Note.TABLE + "("
+ Note.KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT ,"
+ Note.KEY_title + " TEXT, "
+ Note.KEY_note + " TEXT )";
db.execSQL(CREATE_TABLE_NOTE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed, all data will be gone!!!
db.execSQL("DROP TABLE IF EXISTS " + Note.TABLE);
// Create tables again
onCreate(db);
}
如何切换到RecyclerView
并仍然保持对数据库的可访问性?有什么建议吗?
答案 0 :(得分:0)
RecyclerView
是显示大量项目的非常有效的视图。根据{{3}}网站,RecyclerView
是:
灵活的视图,用于为大型数据集提供有限的窗口。
假设您已经在ListView
中使用了现有的布局文件,则可以轻松地将其与RecyclerView
相关联。在主活动布局文件中,键入:
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
我无法构建我的应用并在添加上述代码时出现错误
您可能需要编译依赖项,如下所示:
compile 'com.android.support:recyclerview-v7:+'
您现在需要创建一个RecyclerView.Adapter
课程。创建一个新的Java类并将其命名为RecyclerViewAdapter.java
。将以下代码添加到其中:
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {
public Context context;
public List<RecyclerViewList> list;
public RecyclerViewAdapter(Context context, List<RecyclerViewList> list) {
this.context = context;
this.list = list;
}
public static class RecyclerViewHolder extends RecyclerView.ViewHolder {
TextView title;
TextView note;
public RecyclerViewHolder(View view) {
super(view);
title = (TextView) view.findViewById(R.id.your_title);
note = (TextView) view.findViewById(R.id.your_note);
}
}
@Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup viewGroup, int position) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.your_layout_file, viewGroup, false);
RecyclerViewHolder viewHolder = new RecyclerViewHolder(view);
return viewHolder;
}
@Override
public void onBindViewHolder(final ListsListHolder viewHolder, final int position) {
viewHolder.title.setText(list.get(position).title);
viewHolder.note.setText(list.get(position).note);
}
@Override
public void onAttachedToRecyclerView(RecyclerView recyclerView) {
super.onAttachedToRecyclerView(recyclerView);
}
@Override
public int getItemCount() {
return list.size();
}
}
创建课程后,您需要为List<>
创建一个新课程。创建一个新的Java类并将其命名为RecyclerViewList.java
。将以下代码添加到其中:
public class RecyclerViewList {
public String title;
public String note;
public RecyclerViewList(String title, String note) {
this.title = title;
this.note = note;
}
}
在NoteRepo.java
文件中,将函数getNoteList
更改为:
public Cursor getNoteList() {
SQLiteDatabase db = dbHelper.getReadableDatabase();
return db.query(Note.TABLE, new String[] {Note.KEY_ID, Note.KEY_title, Note.KEY_note}, null, null, null, null, null);
}
在主活动Java类中,在类声明下面添加以下代码:
private List<RecyclerViewList> list = new ArrayList<>();
在onCreate
事件中,添加以下代码:
NoteRepo repo = new NoteRepo(this);
Cursor cursor = repo.getNoteList();
if (cursor.moveToFirst()) {
do {
list.add(new RecyclerViewList(cursor.getString(column), cursor.getString(column)));
} while (cursor.moveToNext());
}
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, list);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
确保使用您已有的代码使用数据库中的所有项目实例化列表。如果您有任何问题,请在下面的评论中提问。