2017-02-07 19 views
1

我正在创建一个StudentManager应用程序。CursorAdapter和查询问题

  • 在MainActivity.java中,当我触摸浮动按钮时,它将切换到EditActivity.java。然后,在EditActivity.java中,如果按下done按钮,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

I think error comes from here

请帮助。非常感谢

+1

请原谅我的错误,因为这是我第一次在stackoverflow中提出问题。我编辑了我的问题 –

回答