将数据插入sqlite(带外键的第二个表)

时间:2011-11-04 09:58:33

标签: java android database sqlite

我在sqlite中插入数据时遇到了一些困难。该应用程序是测验应用程序,其中用户需要首先使用用户名(w / out密码),然后可以稍后查看分数。之前测验用户必须首先创建用户名(如果是新用户),然后选择用户名(将列出所有用户名),因此用户需要单击相关的用户名。用户名(almag表)可以成功插入,但不能用于分数表。两个表与外键链接,即userId。当用户完成测验并按下某个按钮(菜单按钮)时,我希望得分会自动保存,但我仍然面临困难。我希望有人可以提供帮助。

这些是应用程序的一些代码。

数据库java文件

public class DatabaseUsername extends SQLiteOpenHelper {
private static final String DATABASE_NAME="use.db";
private static final int SCHEMA_VERSION=1;
private View _id;
public DatabaseUsername(Context context) {
    super(context, DATABASE_NAME, null, SCHEMA_VERSION);
}   
@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE almag (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, jekel TEXT);");
    db.execSQL("CREATE TABLE score (_id INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER, userId INTEGER NOT NULL, FOREIGN KEY (userId) REFERENCES almag(_id) ON DELETE CASCADE);"); //create table score
    db.execSQL("PRAGMA foreign_keys = ON;");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // no-op, since will not be called until 2nd schema
    // version exists
}
public Cursor getAll() {
    return(getReadableDatabase().rawQuery("SELECT _id, nama, jekel FROM almag ORDER BY nama",null));
}
public Cursor getById(String id) {
    String[] args={id};
    return(getReadableDatabase().rawQuery("SELECT _id, nama, jekel FROM almag WHERE _ID=?",args));
}
public void insert(String nama, String jekel) {
    ContentValues cv=new ContentValues();
    cv.put("nama", nama);
    cv.put("jekel", jekel);     
    getWritableDatabase().insert("almag", "nama", cv);
}
public void insertScore (int _id, int score) {
    ContentValues cv=new ContentValues();   
    cv.put("_id", _id);
    cv.put("score", score);
    getWritableDatabase().insert("score", "score", cv);
}
public void setUsername(View _id) {
    this._id = _id;
}
public String getNama(Cursor c) {
    return(c.getString(1));
}
public String getJekel(Cursor c) {
    return(c.getString(2));
}
}

TheEndActivity

public class TheEndActivity extends Activity implements OnClickListener {

DatabaseUsername helper=null;
private int _id;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.theendactivitylayout);
    helper=new DatabaseUsername(this);
    final SetGame currentGame = ((TheApplication)getApplication()).getCurrentGame();
    String result = "Your Score is " + currentGame.getRight() + "/" + currentGame.getNumRounds() + ".. ";
    String comment = Mark.getResultComment(currentGame.getRight(), currentGame.getNumRounds(), getDifficultySettings());    

    TextView results = (TextView)findViewById(R.id.endgameResult);
    results.setText(result + comment);

    int image = Mark.getResultImage(currentGame.getRight(), currentGame.getNumRounds(), getDifficultySettings());
    ImageView resultImage = (ImageView)findViewById(R.id.resultPage);
    resultImage.setImageResource(image);

    Button finishBtn = (Button) findViewById(R.id.finishBtn);
    Button answerBtn = (Button) findViewById(R.id.answerBtn);
    finishBtn.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {       
            Intent i = new Intent(TheEndActivity.this, QuizAppActivity.class);
            startActivity(i);
            helper.insertScore(_id, currentGame.getRight());
    }
    });

    answerBtn.setOnClickListener(new View.OnClickListener() {   
        @Override
        public void onClick(View v) {

                Intent i = new Intent(TheEndActivity.this, AnsActivity.class);
                startActivityForResult(i, AppRule.PLAYBUTTON);
        }
        });

}

private int getDifficultySettings() {
    SharedPreferences settings = getSharedPreferences(AppRule.SETTINGS, 0);
    int diff = settings.getInt(AppRule.DIFFICULTY, 2);
    return diff;
}


    public boolean onKeyDown(int keyCode, KeyEvent event)
{
    switch (keyCode)
    {
    case KeyEvent.KEYCODE_BACK :
        return true;
    }

    return super.onKeyDown(keyCode, event);
}


    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

    }}

UsernameList

public class UsernameList extends ListActivity {
public final static String ID_EXTRA="com.rika.fyp.player";
Cursor model=null;
AlmagAdapter adapter=null;
EditText nama=null;
RadioGroup jekel=null;
DatabaseUsername helper=null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.usernamelist);

    helper=new DatabaseUsername(this);

    nama=(EditText)findViewById(R.id.nama);
    jekel=(RadioGroup)findViewById(R.id.jekel); 
    model=helper.getAll();
    startManagingCursor(model);
    adapter=new AlmagAdapter(model);
    setListAdapter(adapter);
}

@Override
public void onDestroy() {
    super.onDestroy();

    helper.close();
}

@Override
public void onListItemClick(ListView list, View view,int position, long id) {

    helper.setUsername(nama);
    Intent i=new Intent(UsernameList.this, QuizAppActivity.class);

    i.putExtra(ID_EXTRA, String.valueOf(id));
    startActivity(i);
}       

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    new MenuInflater(this).inflate(R.menu.option, menu);

    return(super.onCreateOptionsMenu(menu));
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId()==R.id.add) {
        startActivity(new Intent(UsernameList.this, UsernameRegister.class));

        return(true);
    }

    return(super.onOptionsItemSelected(item));
}

private View.OnClickListener onSave=new View.OnClickListener() {
    public void onClick(View v) {
        String type=null;

        switch (jekel.getCheckedRadioButtonId()) {
            case R.id.pria:
                type="Pria";
                break;
            case R.id.perempuan:
                type="Perempuan";
                break;

        }

        helper.insert(nama.getText().toString(), type);

        model.requery();
    }
};

class AlmagAdapter extends CursorAdapter {
    AlmagAdapter(Cursor c) {
        super(UsernameList.this, c);
    }

    @Override
    public void bindView(View row, Context ctxt,Cursor c) {
        AlmagHolder holder=(AlmagHolder)row.getTag();
        holder.populateFrom(c, helper);
    }

    @Override
    public View newView(Context ctxt, Cursor c,ViewGroup parent) {
        LayoutInflater inflater=getLayoutInflater();
        View row=inflater.inflate(R.layout.usernamerow, parent, false);
        AlmagHolder holder=new AlmagHolder(row);
        row.setTag(holder);
        return(row);
    }
}

static class AlmagHolder {
    private TextView nama=null;
    private TextView alamat=null;
    private ImageView icon=null;
    private View row=null;

    AlmagHolder(View row) {
        this.row=row;

        nama=(TextView)row.findViewById(R.id.title);
        icon=(ImageView)row.findViewById(R.id.icon);
    }

    void populateFrom(Cursor c, DatabaseUsername helper) {
        nama.setText(helper.getNama(c));
        if (helper.getJekel(c).equals("Pria")) {
            icon.setImageResource(R.drawable.pria);
        }
        else if (helper.getJekel(c).equals("Perempuan")) {
            icon.setImageResource(R.drawable.perempuan);
        }

    }
}}

我在logcat中得到了这些

  

错误/数据库(319):插入得分错误= 20 _id = 0

     

错误/数据库(319):android.database.sqlite.SQLiteConstraintException:错误代码19:约束失败

1 个答案:

答案 0 :(得分:-1)

您的onCreate()方法看起来过于复杂。试试这个:

public void onCreate(SQLiteDatabase db) {
    db.execSQL("CREATE TABLE almag (_id INTEGER PRIMARY KEY AUTOINCREMENT, nama TEXT, jekel TEXT);");
    db.execSQL("CREATE TABLE score (_id INTEGER PRIMARY KEY AUTOINCREMENT, score INTEGER, userId FOREIGN KEY REFERENCES almag(_id) ON DELETE CASCADE);"); //create table score
}

我无法保证它能解决你的问题,但简单有办法解决问题。

还可以尝试将插入方法更改为:

public void insert(String nama, String jekel) {
    ContentValues cv=new ContentValues();
    cv.put("nama", nama);
    cv.put("jekel", jekel);     
    getWritableDatabase().insert("almag", null, cv);
}

public void insertScore (int _id, int score) {
    ContentValues cv=new ContentValues();   
    cv.put("_id", _id);
    cv.put("score", score);
    getWritableDatabase().insert("score", null, cv);
}