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

Java 将数据插入sqlite(第二个带外键的表),java,android,database,sqlite,Java,Android,Database,Sqlite,我在将数据插入sqlite时遇到了一些困难。该应用程序是测验应用程序,其中用户需要有一个用户名(w/out密码),然后分数可以查看以后。在进行测验之前,用户必须先创建用户名(如果是新用户),然后选择用户名(所有用户名都将列出),因此用户需要单击相关用户名。用户名(ALMG表)可以成功插入,但不能用于分数表。两个表用外键链接,外键是userId。当用户完成测验并按下某些按钮(菜单按钮)时,我希望分数将自动保存,但我仍然面临着这样做的困难。。我希望有人能帮忙 这些是应用程序的一些代码 数据库java

我在将数据插入sqlite时遇到了一些困难。该应用程序是测验应用程序,其中用户需要有一个用户名(w/out密码),然后分数可以查看以后。在进行测验之前,用户必须先创建用户名(如果是新用户),然后选择用户名(所有用户名都将列出),因此用户需要单击相关用户名。用户名(ALMG表)可以成功插入,但不能用于分数表。两个表用外键链接,外键是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);
        }
        
    }
}}
我把这些放在航海日志里了

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

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

您的
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);
}

cv.put(“\u id”,“\u id”)insertScore(int\u id,int score)
中的code>看起来不太好。。。。不应该是
cv.put(“\u id”,userId)
insertScore(int userId,int score)
中…您在logcat中是否收到任何错误?是的,但不会对该问题产生影响。我认为问题在于如何插入分数,但我不知道如何解决它