简体   繁体   English

SimpleCursorAdapter将数据从数据库获取到ListView

[英]SimpleCursorAdapter to get Data from Database to ListView

I have to create an app and for this I need to create a database. 我必须创建一个应用程序,为此,我需要创建一个数据库。 I'm able to create new entries, but I don't know how to read the database to get the stored data and put it in a ListView. 我能够创建新条目,但是我不知道如何读取数据库以获取存储的数据并将其放入ListView中。

public class DatabaseHelper extends SQLiteOpenHelper {

private static final String DATABASE_NAME="students.db";
private static final String TABLE_NAME="student_details";
private static final String COL_1="ID";
private static final String COL_2="NAME";
private static final String COL_3="SURNAME";
private static final String COL_4="MARKS";
private static final int DATABASE_VERSION=1;

public DatabaseHelper (Context context)
{
    super(context, DATABASE_NAME, null, DATABASE_VERSION);

}



@Override
public void onCreate(SQLiteDatabase db) {


db.execSQL("create table " + TABLE_NAME + "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");

    Log.d("info", "TABLE WAS CREATED");


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    db.execSQL("DROP TABLE IF EXIST " + TABLE_NAME);
    onCreate(db);
    Log.d("Info","TABLE WAS UPDATED");

}

public boolean insertdata(String name,String surname,String marks)
{

    SQLiteDatabase db= this.getWritableDatabase();

    ContentValues contentValues= new ContentValues();
    contentValues.put(COL_2,name);
    contentValues.put(COL_3, surname);
    contentValues.put(COL_4, marks);

    long result=db.insert(TABLE_NAME,null,contentValues);
    if (result==-1)
        return false;
    else
        return true;

}
public Cursor getallData()
{
    SQLiteDatabase db= this.getWritableDatabase();

    Cursor res=db.rawQuery("SELECT * FROM "+TABLE_NAME,null);
    return res;

}
public boolean updateData(String id,String name,String surname,String marks) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues contentValues = new ContentValues();
   // contentValues.put(COL_1, id);
           contentValues.put(COL_2, name);
    contentValues.put(COL_3, surname);
    contentValues.put(COL_4, marks);

    db.update(TABLE_NAME, contentValues, COL_1 + " =? ", new String[]{id});
    return true;

}
public Cursor getData(int id){
    SQLiteDatabase db = this.getReadableDatabase();
    Cursor res =  db.rawQuery( "select * from student_details where ID="+id+"", null );
    if(res != null && res.moveToFirst()) {
        return res;
    }
    return res;
}
public int deleteData(String id)
{
    SQLiteDatabase db = this.getWritableDatabase();
    return db.delete(TABLE_NAME, COL_1 + " =?", new String[]{id});

}

 public class DisplayData extends Activity {

    DatabaseHelper myDB;
    ListView list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.data_display);
        list= (ListView) findViewById(R.id.listView);
        myDB= new DatabaseHelper(this);
        //Cursor res = myDB.getallData();
        String[] from={"ID","NAME","SURNAME","MARKS"};

        int[] to={R.id.textView11,R.id.textView13,R.id.textView15 };
        Cursor cursor=myDB.getallData();
       // allData();
        SimpleCursorAdapter adapter= new SimpleCursorAdapter(this,R.layout.custom_data_display,cursor,from,to);
        list.setAdapter(adapter);
        // adapter= new ArrayAdapter(this,R.layout.custom_data_display,)


    }


This is the error I get: 这是我得到的错误:

com.example.ky.studentmarks E/AndroidRuntime﹕ FATAL EXCEPTION: main
        Process: com.example.aeiltech.studentmarks, PID: 23469
        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.ky.studentmarks/com.example.aeiltech.studentmarks.DisplayData}: java.lang.IllegalArgumentException: column '_id' does not exist
                at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2436)
                at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2498)
                at android.app.ActivityThread.access$900(ActivityThread.java:179)
                at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1324)
                at android.os.Handler.dispatchMessage(Handler.java:102)
                at android.os.Looper.loop(Looper.java:146)
                at android.app.ActivityThread.main(ActivityThread.java:5641)
                at java.lang.reflect.Method.invokeNative(Native Method)
                at java.lang.reflect.Method.invoke(Method.java:515)
                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1288)
                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1104)
                at dalvik.system.NativeStart.main(Native Method)

You should first try a tutorial before jumping into coding that you don't understand. 在进入您不了解的编码之前,您应该首先尝试一个教程。
Official: 官方:
1. http://developer.android.com/training/basics/data-storage/databases.html . 1. http://developer.android.com/training/basics/data-storage/databases.html
Similar: 类似:
2. Android column '_id' does not exist? 2. Android栏'_id'不存在? .
Good tutorial: 好的教程:
3. http://www.vogella.com/tutorials/AndroidSQLite/article.html . 3. http://www.vogella.com/tutorials/AndroidSQLite/article.html
Your problem seem to be that you don't have that column("_id") that the SimpleCursor needs in the database. 您的问题似乎是您没有SimpleCursor在数据库中需要的column(“ _ id”)。 Check the (2) for this problem that you have and also in order to understand how to fix the problem take a look at (3). 检查(2)中是否存在此问题,并且还为了了解如何解决该问题,请查看(3)。
Happy coding. 快乐的编码。

Change id to _id in your table. 将表中的id更改为_id Also, you need to declare SimpleCursorAdapter adapter as a field of the DisplayData class not as a local variable within onCreate . 另外,您需要将SimpleCursorAdapter adapter声明为DisplayData类的字段,而不是onCreate的局部变量。

Try creating your database like this: 尝试像这样创建数据库:

 private static final String DATABASE_CREATE = "create table "
        + TABLE_NAME + "(" + COL_1 +
        " integer primary key autoincrement, "  +
        COL_2 + " text not null, "  + COL_3 + " text not null, " + COL_4 + " integer);";

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(DATABASE_CREATE);
}

Also in public Cursor getallData() , make sure to put res.moveToFirst() , before you return res . 同样在public Cursor getallData() ,确保在return res之前放入res.moveToFirst()

Take a look at voggela tutorial because you need to have a DAO class to acces data from the database without using it directly. 看一下voggela 教程,因为您需要一个DAO类来访问数据库中的数据而无需直接使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM