要解决Android RecyclerView无法从数据库获取数据的问题,你需要执行以下步骤:
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "your_database_name";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "your_table_name";
private static final String COLUMN_ID = "id";
private static final String COLUMN_NAME = "name";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
String createTableQuery = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT)";
db.execSQL(createTableQuery);
}
public void insertData(String name) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_NAME, name);
db.insert(TABLE_NAME, null, contentValues);
db.close();
}
}
public class MyAdapter extends RecyclerView.Adapter {
private List dataList;
private DatabaseHelper databaseHelper;
public MyAdapter(Context context) {
databaseHelper = new DatabaseHelper(context);
dataList = databaseHelper.getData();
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
String data = dataList.get(position);
holder.textView.setText(data);
}
@Override
public int getItemCount() {
return dataList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView textView;
public ViewHolder(@NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
}
}
}
public class MainActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private MyAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new MyAdapter(this);
recyclerView.setAdapter(adapter);
}
}
通过以上步骤,你的Android RecyclerView应该能够从数据库获取数据并正确地显示在列表中。请确保你的数据库中已经插入了数据,并检查适配器中从数据库获取数据的代码是否正确。