我正在制作StudentManager应用程序。
在MainActivity.java中,当我触摸浮动按钮时,它将切换到EditActivity.java。然后,在EditActivity.java中,如果我按下完成按钮,sendToMain()将从EditActivity获取数据并发送到MainActivity,然后DatabaseHandler.java将数据存储在数据库中。
当我尝试创建游标以从数据库填充ListView时,问题就出现了。我在DatabaseHandler.java中创建了returnCursor(),然后我在MainActivity中使用它,并出现错误。我不知道我的光标查询是错误的还是StudentCursorAdapter.java是错误的,或者这个错误来自其他地方。
MainActivity.java
public void showStudent()
{
Cursor cursor = databaseHandler.returnCursor();
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
Toast.makeText(this, name, Toast.LENGTH_SHORT).show(); //to make sure cursor can be used
StudentCursorAdapter studentCursorAdapter = new StudentCursorAdapter(this, cursor);
studentCursorAdapter.notifyDataSetChanged();
MlistView1.setAdapter(studentCursorAdapter);
}
DatabaseHandler.java
public Cursor returnCursor()
{
//String selectQuery = "select * from " + TABLE_STUDENTS;
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor = database.query(TABLE_STUDENTS,
new String[] {KEY_IDNUM, KEY_NAME, KEY_BIRTHYEAR, KEY_ISMALE, KEY_CLASSNAME},
null, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
return cursor;
}
StudentCursorAdapter.java
public class StudentCursorAdapter extends CursorAdapter
{
public StudentCursorAdapter(Context context, Cursor cursor)
{
super(context, cursor, 0);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
return LayoutInflater.from(context).inflate(R.layout.custom_listview_layout, parent, false);
}
@Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView CtextView1 = (TextView) view.findViewById(R.id.CtextView1);
TextView CtextView2 = (TextView) view.findViewById(R.id.CtextView2);
ImageView CimageView = (ImageView) view.findViewById(R.id.CimageView1);
String name = cursor.getString(cursor.getColumnIndexOrThrow("name"));
String className = cursor.getString(cursor.getColumnIndexOrThrow("classname"));
CtextView1.setText(name);
CtextView2.setText(className);
}
}
这是我的项目(用Android Studio 2.2.3编写),分支3-8_Fe-6-2017 https://github.com/nhatnguyenduy/StudentManager/tree/3-8_Fe-6-2017
请帮忙。非常感谢
答案 0 :(得分:0)
感谢我的讲师,我知道我做错了什么。因为我使用了CursorAdapter,所以“_id”必须出现在我的数据库中,但我并没有这样做。 有关详细信息:https://developer.android.com/reference/android/widget/CursorAdapter.html