2

下面是我的代码,我只想将我在 sqlite 数据库中插入的数据显示到文本视图,但我有这个错误,说 id 不是唯一的。

    package com.example.sqlitetest;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

public class Main extends Activity {

    TextView scrName, fName;
    Button go;
    SQLiteDatabase db;
    String screenName, fullName;
    Cursor cursor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        db = openOrCreateDatabase("MyDataBase", MODE_PRIVATE, null);
        db.execSQL("CREATE TABLE if not exists MyTable(ScreenName Varchar, FullName Varchar, id int(3) PRIMARY KEY);");
        db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");
        cursor = db.rawQuery("Select * from MyTable", null);
        cursor.moveToFirst();

        scrName = (TextView) findViewById(R.id.scrName);
        fName = (TextView) findViewById(R.id.fName);

        while(cursor.isAfterLast() == false){
            //retrieving the data from sqlite (im not sure if im doing it right)
            String screenname = cursor.getString(cursor.getColumnIndex("ScreenName"));
            String fullname = cursor.getString(cursor.getColumnIndex("FullName"));

            //this are the textview
            scrName.setText(screenname);
            fName.setText(fullname);

            cursor.moveToNext();
        }
        db.close();
    }
}

这是我的整个java代码。谢谢 :)

4

2 回答 2

3

嗯,我认为这个项目在你第一次运行时运行良好。当您第二次运行它时,它会给出错误,因为id您的primary key和 id 为 1 的行已经插入到您的数据库中。

要摆脱错误:

1) uninstall the app and run it again   
2) Don't make id as primary key   
3) Catch the exception and handle it yourself
于 2013-10-26T03:00:19.217 回答
1

我可以建议一个替代方案。您可以做的是制作 id 列autoincrement,同时仍将该列保持为primary key

编辑:- 我还有一些其他的建议给你:-

db.execSQL("Insert into MyTable VALUES('joff', 'tiquez', 1);");

您可以改用ContentValues

while(cursor.isAfterLast() == false){

可以替换为while(!cursor.isAfterLast()){. 这样看起来更干净。

或者您可以直接替换while(cursor.isAfterLast() == false){while(cursor.moveToNext()){并且可以cursor.moveToNext();从 while 块中删除。

快乐编码!!!

于 2013-10-26T04:37:04.140 回答