android - 数据不显示在列表视图中
问题描述
我正在创建一个小的 crud 系统。添加记录后,我必须在单击查看按钮时查看记录。我附上了下面的图片和代码。对此有误
**android.database.CursorIndexOutOfBoundsException: Index 4 requested, with a size of 4**
行是titles.add(c.getString(age));
单击此处的按钮代码
Intent i = new Intent(this,view.class);
startActivity(i);
**Listview xml file**
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".view">
<ListView
android:id="@+id/lst1"
android:layout_width="368dp"
android:layout_height="495dp"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp" />
</LinearLayout>
视图.java
public class view extends AppCompatActivity {
ListView lst1;
ArrayList<String> titles = new ArrayList<String>();
ArrayAdapter arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
SQLiteDatabase db = openOrCreateDatabase("StudentDB", Context.MODE_PRIVATE, null);
lst1 = findViewById(R.id.lst1);
Cursor c = db.rawQuery("select * from record",null);
int name = c.getColumnIndex("name");
int age = c.getColumnIndex("age");
c.moveToFirst();
titles.clear();
arrayAdapter = new ArrayAdapter(this,R.layout.support_simple_spinner_dropdown_item,titles);
lst1.setAdapter(arrayAdapter);
while (c != null)
{
titles.add(c.getString(name));
titles.add(c.getString(age));
c.moveToNext();
}
arrayAdapter.notifyDataSetChanged();
}
}
解决方案
我认为你应该使用 do-while 循环:
if(c.moveToFirst()) {
do {
titles.add(c.getString(name));
titles.add(c.getString(age));
} while (c.moveToNext())
}
推荐阅读
- batch-file - 我可以让批处理文件根据主机名执行特定命令吗?
- docker - 从容器运行的 docker 注册表的默认用户名密码是什么
- java - Java 部署配置问题
- python - 来自选定字形的散景服务器 on_change 不起作用
- bash - 为什么“grep '[^ -~]'”的行为与“grep -P -L '[^[:ascii:]]'”的行为相同?
- reactjs - 在 JSX 中将 props 分配给组件变量
- redis - 如果 master 在给定时间内关闭,则杀死 Redis Slave
- postgresql - 为什么我不能通过 select distincts 使用相等顺序?
- wso2 - WSO2 身份服务器 - 从 JWT 访问令牌中删除“内部/所有人”
- asp.net-core - AADB2C90006 在 redirect_uri 中带有 https-> http 转换