【问题标题】:Pass id of sqlite table from listview to another activity将 sqlite 表的 id 从 listview 传递到另一个活动
【发布时间】:2012-01-03 00:15:39
【问题描述】:

我很难获得 sqlite 的 id。我有listview,然后我想获取一个sqlite表的id,然后我可以在完成测验后保存分数时使用它。

场景是这样的:用户创建用户名(或单击如果曾经创建过的用户名),在他/她单击其中一个用户名后进行测验,完成后用户将获得分数然后保存分数并可以查看稍后。

数据库代码

public class DatabaseUsername extends SQLiteOpenHelper {
private static final String DATABASE_NAME="usernm.db";
private static final int SCHEMA_VERSION=1;


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
}

@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 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 score, int userId) {
    ContentValues cv=new ContentValues();

    cv.put("score", score);
    cv.put("userId", userId);
    getWritableDatabase().insert("score", null, cv);
}


public String getNama(Cursor c) {
    return(c.getString(1));
}

public String getJekel(Cursor c) {
    return(c.getString(2));
}

public static int getId (Cursor c) {
    return(c.getInt(1));
}}

用户名列表.java

public class UsernameList extends ListActivity {
public final static String ID_EXTRA="com.rika.fyp.player";
Cursor model=null;
Cursor mode=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();
}


 public void onListItemClick(ListView parent, View view, int position, long id) {
        Intent intent = new Intent(this, TheEndActivity.class);
        Cursor cursor = (Cursor) adapter.getItem(position);
        intent.putExtra("USER_ID", cursor.getInt(cursor.getColumnIndex("_id")));
        startActivity(intent);

        Intent i=new Intent(UsernameList.this, QuizAppActivity.class);
        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);
        }

    }
}}

TheEndActivity.java

public class TheEndActivity extends Activity implements OnClickListener {

 protected int userId;

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

    userId = getIntent().getIntExtra("USER_ID", 0);
     SQLiteDatabase db = (new DatabaseUsername(this)).getWritableDatabase();
        final Cursor cursor = db.rawQuery("SELECT alm._id, alm.nama FROM almag alm  WHERE emp._id = ?", 
                                new String[]{""+userId});


    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);

    //handle button actions
    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) {

            finish();

            helper.insertScore(currentGame.getRight(), userId);

            Intent i = new Intent(TheEndActivity.this, MainMenu.class);
            startActivity(i);               
    }
    });

    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

    }}

我已经尝试了上面的这些代码,但仍然可以获取 id。我希望有一个人可以帮助我。

下面这些代码用于插入分数(在 TheEndActivity.java 中)

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

                helper.insertMark(currentGame.getRight(), userId );
                Intent i = new Intent(TheEndActivity.this, MainMenu.class);
                startActivity(i);
        }
        });

在 Database.java 中插入标记

public void insertMark(int score, int userId) {
    ContentValues cv=new ContentValues();

    cv.put("score", score);
    cv.put("userId", userId);

    getWritableDatabase().insert("score", null, cv);
}

【问题讨论】:

  • 你说 insertMark 返回 0,但它的返回类型是 void。你在说什么?
  • 对不起,我不是那个意思
  • 对我的误解很抱歉
  • 没关系,现在不明白是什么问题。列表视图与用户 _id 不正确有什么关系?本质上是什么问题?问题出现在什么方法中,出现问题的方法中包含哪些值?
  • listview 来自 sqlite(almag 表),我想检索 almag 表的 _id,它成为分数表中的外键,问题是我无法正确检索 almag 表的 _id(仍然得到0)。好像_id不能正确传递(insertMark的第二个参数)

标签: java android sqlite listview


【解决方案1】:

您是否尝试过使用long id 而不是int position

    public void onListItemClick(ListView parent, View view, int position, long id) {
        Intent intent = new Intent(this, TheEndActivity.class);
        Cursor cursor = (Cursor) adapter.getItem((int)id);
        intent.putExtra("USER_ID", cursor.getInt(cursor.getColumnIndex("_id")));
        startActivity(intent);

        Intent i=new Intent(UsernameList.this, QuizAppActivity.class);
        startActivity(i);
    }

其实再进一步看,这里打数据库还有什么意义呢?我认为当您将列表视图绑定到适配器时,默认情况下 _id 字段映射到列表视图的 id 字段。所以使用 id 应该给你你想要的 id 而不是访问数据库。

所以不妨试试这个:

public void onListItemClick(ListView parent, View view, int position, long id) {
    Intent intent = new Intent(this, TheEndActivity.class);

    intent.putExtra("USER_ID", (int)id);
    startActivity(intent);

    Intent i=new Intent(UsernameList.this, QuizAppActivity.class);
    startActivity(i);
}

我在工作,没有设置 Android 环境,但我认为这应该可以。

【讨论】:

  • 谢谢。我需要从 db 中检索 id 以连接分数和用户名,然后我可以使用它来查看分数。我尝试了您的建议,但出现错误:(
  • 是的,但您不是在 UserNameList.java 中查询分数,您只是将 USER_ID 传递给 TheEndActivity 活动。只需传递 id,在 TheEndActivity 中即可获取 id 并拉取分数
  • 我尝试添加这些代码:userId = getIntent().getIntExtra("USER_ID", (int)id);并保存分数 -> helper.insertMark(currentGame.getRight(), userId ); .但我还是 0
  • 你还在哪里得到0?从 insertMark 返回?从 getIntExtra("USER_ID"...) ?
  • 是的,从insertMark,userId变成了0(无法检索到数据库的id)
猜你喜欢
  • 1970-01-01
  • 2012-07-05
  • 2018-07-28
  • 1970-01-01
  • 1970-01-01
  • 2013-07-17
  • 1970-01-01
  • 2013-01-12
  • 2017-12-10
相关资源
最近更新 更多