小编典典

SQLite列ID不是唯一的

sql

下面是我的代码,我只想显示我在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代码。谢谢 :)


阅读 271

收藏
2021-04-28

共1个答案

小编典典

好吧,我认为这个项目在您首次运行时效果很好。当您第二次运行它时,由于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
2021-04-28