如何从android中的ListView中选择特定用户

时间:2016-09-29 11:32:08

标签: android listview

我有学生在ListView中没有商店。现在我想选择并点击滚动否这样它会显示该学生的名字。例如,如果我有滚动否= 1,当我点击它时它应该告诉我名字,如果我点击第2卷,它应该显示我的名字像b,等等......

ArrayList<String> student = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, student);
ListView list = new(ListView)findViewById(R.id.ll);

public void dd(View view){
    if (res.getCount() == 0) {
        // show message
        showMessage("Error", "Nothing found");
        return;
    }

    while (res.moveToNext()) {
        String roll = "Roll No1:" + res.getString(0);
        String rolll = "Roll NO2:" + res.getString(1);
        String rollk = "Roll NO3:" + res.getString(2);
        student.add(roll);
        student.add(rolll);
        student.add(rollk);
        list.setAdapter(adapter);
    }
}


list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Toast.makeText(getBaseContext(), student.get(i), Toast.LENGTH_SHORT).show(); 
    }

});

它正常工作,但为所有人显示相同的信息。我也使用了开关语句,但是大量的案例如案例0,案例1,案例2等等。 而且我也使用if条件,但它也适用于if条件。所以我想要一个特定的方法来处理这个。并点击第2卷以显示一个学生姓名并点击第3卷以显示另一个学生姓名

1 个答案:

答案 0 :(得分:0)

我认为你的光标有些混乱。没有看到你的数据库设置很难说。让我们来看看你现在拥有的东西

//I would add res.moveToStart() here just to be safe.
while (res.moveToNext()) { //This should probably be a do while otherwise you'll skip the first entry

        //This is where things seem to be not right these next three statements get columns 1, 2 and 3 of your database.
        //So this would mean your database structure is 
        //|roll|roll|roll|
        //is this really correct?
        //I would think for performance you would have an index and something like
        //|id|roll name|roll email?|
        //with that setup you would simply do
        String rollName = "Roll NO2:" + res.getString(1);
        student.add(rollName);
}

//I would also instantiate adapter here now that your list is populate or call notifyDataSetChanged() on it
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_selectable_list_item, student);

//This should also be outside of your loop you don't need to call this every time. 
list.setAdapter(adapter);