android - 如何在android studio的自定义列表视图中显示外部sqlite数据库的数据?
问题描述
我想知道这是在android studio中使用/ oop & sqlite在自定义列表视图中显示数据的方式吗?
在这个java页面中,我在这里分配了它们
public static Model txn;
public static SQLiteHelper mSQLiteHelper;
ListView mListView;
ArrayList<Model> mList;
RecordListAdapter mAdapter = null;
之后,我初始化了它们
mListView =findViewById(R.id.listView);
mList = new ArrayList<>();
mAdapter = new RecordListAdapter(this, R.layout.row, mList);
mListView.setAdapter(mAdapter);
这是我试图抓住它们并展示出来的代码。我在这条线上遇到了一个问题mList.add(new Model(id, name, address, phone));
。
try{
SQLiteDatabase db = mSQLiteHelper.getReadableDatabase();
Cursor cursor = db.query("Table1", new String[]{"id", "name", "address", "phone"}, null,
null, null, null, null);
mList.clear();
while(cursor.moveToNext()){
int id = cursor.getInt(3);
String name = cursor.getString(0);
String address = cursor.getString(1);
String phone = cursor.getString(2);
mList.add(new Model(id, name, address, phone));
}
mAdapter.notifyDataSetChanged();
if (mList.size() == 0) {
Toast.makeText(this, "No record found...", Toast.LENGTH_SHORT).show();
}
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int i, long l) {
return false;
}
});
}catch (Exception e){
e.printStackTrace();
}
这是红色错误说
Model() in Model cannot be applied to:
Expected Actual
Parameters: Arguments
id(int)
name(java.lang.String)
address(java.lang.String)
phone(java.lang.String)
这是我的模型页面
public class Model {
private int id;
private String name;
private String address;
private String phone;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
我该怎么做才能解决这个问题?提前致谢...
解决方案
您没有采用 4 个参数的构造函数。你需要类似的东西: -
public Model(int id,String name,String address,String phone){
this.id = id;
this.name = name;
this.address = address;
this.phone = phone;
}
在您的模型类中。
另外使用:-
int id = cursor.getInt(0);
String name = cursor.getString(1);
String address = cursor.getString(2);
String phone = cursor.getString(3);
即偏移量 0 是光标中的第一列,即id, 3是phone。
虽然更好地根据列名获得偏移量。例如(理想情况下使用常量作为表名和列名,而不是到处硬编码)。
int id = cursor.getInt(csr.getColumnIndex("id"));
如果这不能解决问题,请编辑您的问题以包含堆栈跟踪。
推荐阅读
- javascript - 用百分比计算器创建一个整数
- sql - 如何将亚马逊卖家报告上传到 SQL 数据库?
- python - 将量化的 Pytorch 模型导出到 onnx 时出现分段错误
- android - 在特定时间关闭 App 时安排 Android 功能
- f# - 任何地方都有 option<> 计算表达式吗?
- python - 最大子数组总和 - 我的解决方案哪里错了?Kadane 算法
- c# - Google API Explorer 不会创建 Compute Engine 虚拟机实例
- java - junit 5 自定义参数化测试
- palantir-foundry - 如何获得轮廓中多列的最小值?
- apache - 在 httpd.conf 中加载模块 mod_proxy_cluster.so 时,在 AIX 7.2 powerpc v1.3.0 上出现以下错误))