从ListView切换到RecyclerView

从ListView切换到RecyclerView,listview,android-recyclerview,Listview,Android 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("not

我想将我的
列表视图
更改为
回收视图
。以下是我的主要活动:

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);

}
这是我的
NoteRepo
课程:

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();
    }


}
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;
}
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
并保持对数据库的可访问性?有什么建议吗?

回收视图是一个显示大量项目的非常有效的视图。根据该网站,一个
RecyclerView
是:

一种灵活的视图,用于提供进入大型数据集的有限窗口

假设您已经在
列表视图
中使用了一个现有布局文件,您可以轻松地将其链接到
回收视图
。在主活动布局文件中,键入:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
创建类后,需要为
列表创建一个新类。创建一个新的Java类,并将其命名为
RecycleServiceWList.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();
    }
}
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<>();
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);

确保使用已有的代码实例化包含数据库中所有项目的列表。如果您有任何问题,请在下面的评论中询问。

对于显示大量项目而言,
RecyclerView
是一个非常有效的视图。根据该网站,一个
RecyclerView
是:

一种灵活的视图,用于提供进入大型数据集的有限窗口

假设您已经在
列表视图
中使用了一个现有布局文件,您可以轻松地将其链接到
回收视图
。在主活动布局文件中,键入:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
创建类后,需要为
列表创建一个新类。创建一个新的Java类,并将其命名为
RecycleServiceWList.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();
    }
}
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<>();
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);

确保使用已有的代码实例化包含数据库中所有项目的列表。如果您有任何问题,请在下面的评论中提问。

您可以将项目的布局文件附加到您的问题中吗?您可以将项目的布局文件附加到您的问题中吗?