You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android Studio中用SQLite数据库实现笔记列表视图展示

Hey there! Let's get your SQLite-stored notes displayed in a list view—here's a step-by-step breakdown tailored to your current setup:

1. First, Refine Your Database Helper Class

Since you're already storing notes in SQLite, let's make sure your helper class has a method to fetch all saved notes. If you don't have a dedicated SQLiteOpenHelper class yet, create one like this:

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class NotesDatabaseHelper extends SQLiteOpenHelper {
    private static final String DATABASE_NAME = "Notes.db";
    private static final int DATABASE_VERSION = 1;
    
    // Table and column names
    public static final String TABLE_NOTES = "notes";
    public static final String COLUMN_ID = "_id";
    public static final String COLUMN_CONTENT = "content";

    public NotesDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // Create notes table on first launch
        String createTableQuery = "CREATE TABLE " + TABLE_NOTES + " (" +
                COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COLUMN_CONTENT + " TEXT NOT NULL)";
        db.execSQL(createTableQuery);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Reset table if database version updates
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        onCreate(db);
    }

    // Method to fetch all notes from database
    public Cursor getAllNotes() {
        SQLiteDatabase db = this.getReadableDatabase();
        // Return notes sorted by newest first
        return db.query(TABLE_NOTES, null, null, null, null, null, COLUMN_ID + " DESC");
    }
}

For modern Android development, RecyclerView is the best choice for list views—it's flexible, efficient, and supports advanced features. Here's how to set it up:

2.1 Add RecyclerView to Your Main Layout

Update your activity_main.xml to include a RecyclerView (replace or supplement your existing layout):

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/notes_recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="16dp"/>

2.2 Create a Layout for Individual Note Items

Make a new layout file note_item.xml to define how each note looks in the list:

<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/note_content"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:textSize="16sp"
    android:background="#f5f5f5"
    android:layout_marginBottom="8dp"/>

2.3 Build a RecyclerView Adapter

This adapter will connect your SQLite Cursor data to the RecyclerView:

import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.recyclerview.widget.RecyclerView;

public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.NoteViewHolder> {
    private Cursor mCursor;
    private Context mContext;

    public NotesAdapter(Context context, Cursor cursor) {
        mContext = context;
        mCursor = cursor;
    }

    @Override
    public NoteViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(mContext).inflate(R.layout.note_item, parent, false);
        return new NoteViewHolder(view);
    }

    @Override
    public void onBindViewHolder(NoteViewHolder holder, int position) {
        if (!mCursor.moveToPosition(position)) {
            return;
        }
        // Fetch note content and ID from Cursor
        String content = mCursor.getString(mCursor.getColumnIndex(NotesDatabaseHelper.COLUMN_CONTENT));
        long noteId = mCursor.getLong(mCursor.getColumnIndex(NotesDatabaseHelper.COLUMN_ID));
        
        // Bind data to the item view
        holder.noteContent.setText(content);
        holder.itemView.setTag(noteId); // Store ID for future actions (e.g., delete)
    }

    @Override
    public int getItemCount() {
        return mCursor.getCount();
    }

    // Update Cursor when new data is added
    public void swapCursor(Cursor newCursor) {
        if (mCursor != null) {
            mCursor.close();
        }
        mCursor = newCursor;
        if (newCursor != null) {
            notifyDataSetChanged();
        }
    }

    // ViewHolder class for recycling list items
    public class NoteViewHolder extends RecyclerView.ViewHolder {
        TextView noteContent;

        public NoteViewHolder(View itemView) {
            super(itemView);
            noteContent = itemView.findViewById(R.id.note_content);
        }
    }
}
3. Integrate Everything in Your MainActivity

Modify your existing MainActivity code to initialize the RecyclerView, load data from SQLite, and update the list when a new note is saved:

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.content.ContentValues;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

public class MainActivity extends Activity {
    private NotesDatabaseHelper mDbHelper;
    private RecyclerView mNotesRecyclerView;
    private NotesAdapter mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Initialize database helper
        mDbHelper = new NotesDatabaseHelper(this);

        // Set up RecyclerView
        mNotesRecyclerView = findViewById(R.id.notes_recycler_view);
        mNotesRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        
        // Load existing notes and attach adapter
        Cursor cursor = mDbHelper.getAllNotes();
        mAdapter = new NotesAdapter(this, cursor);
        mNotesRecyclerView.setAdapter(mAdapter);

        // Your existing save button logic (updated to refresh list)
        EditText inputEditText = findViewById(R.id.input_text);
        Button saveButton = findViewById(R.id.save_button);

        saveButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String noteContent = inputEditText.getText().toString().trim();
                if (!noteContent.isEmpty()) {
                    // Insert new note into database
                    SQLiteDatabase db = mDbHelper.getWritableDatabase();
                    ContentValues values = new ContentValues();
                    values.put(NotesDatabaseHelper.COLUMN_CONTENT, noteContent);
                    db.insert(NotesDatabaseHelper.TABLE_NOTES, null, values);

                    // Clear input field
                    inputEditText.setText("");

                    // Refresh the list with new data
                    Cursor newCursor = mDbHelper.getAllNotes();
                    mAdapter.swapCursor(newCursor);
                }
            }
        });
    }

    // Clean up resources when activity is destroyed
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mDbHelper.close();
        if (mAdapter != null) {
            mAdapter.swapCursor(null); // Close the old cursor
        }
    }
}
4. Key Notes to Remember
  • Cursor Management: Always close cursors when they're no longer needed to avoid memory leaks (we handle this in swapCursor and onDestroy).
  • Data Refresh: After adding a new note, we fetch a fresh Cursor and pass it to the adapter to update the list.
  • Alternative: ListView: If you prefer using ListView instead of RecyclerView, you can use SimpleCursorAdapter to bind data directly, but RecyclerView offers better performance and customization.

内容的提问来源于stack exchange,提问作者Coder567

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:01:18