【问题标题】:Inserting data to sqlite (second table with foreign key)将数据插入到 sqlite(第二个带有外键的表)
【发布时间】:2011-11-04 09:58:32
【问题描述】:

我在 sqlite 中插入数据时遇到了一些困难。该应用程序是测验应用程序,用户需要先拥有用户名(无密码),然后才能查看分数。在做测验之前,用户必须先创建用户名(如果是新用户)然后选择用户名(所有用户名都会被列出),所以用户需要点击相关的用户名。可以成功插入用户名(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));
}
}

结束活动

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
        
    }}

用户名列表

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 中得到了这些

ERROR/Database(319):插入 score=20 _id=0 时出错

ERROR/Database(319): android.database.sqlite.SQLiteConstraintException: 错误代码 19: 约束失败

【问题讨论】:

  • insertScore (int _id, int score) 中的cv.put("_id", _id); 看起来不太好......不应该是insertScore (int userId, int score) 中的cv.put("_id", userId); ...
  • 您是否在 logcat 中遇到任何错误?

标签: java android database sqlite


【解决方案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);
}

【讨论】:

  • 是的,但不要解决这个问题。我认为问题在于插入分数的方式,但我不知道如何解决它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-10-08
  • 1970-01-01
  • 2011-04-29
  • 1970-01-01
  • 1970-01-01
  • 2015-01-15
  • 2023-01-26
相关资源
最近更新 更多