我有我的数据库,并在 ListView 中显示一些数据。当用户单击 ListView 中的项目时,我想将数据传递给另一个 Activity
long idProjeto;
ProjetosDAO pDAO;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lista_projetos);
ListView lv = (ListView)findViewById(R.id.lvListaProjetos);
final ListaProjetosAdapter adapter = new ListaProjetosAdapter(this);
pDAO = new ProjetosDAO(this);
pDAO.open();
Cursor cursor = pDAO.consultaParaListaprojetos();
String data = "";
String cliente = "";
String tipoProjeto = "";
String status = "";
if(cursor != null && cursor.moveToFirst()){
do{
data = cursor.getString(0);
cliente = cursor.getString(1);
tipoProjeto = cursor.getString(2);
status = cursor.getString(3);
idProjeto = Long.parseLong(cursor.getString(4));
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
try {
Date date = sdf.parse(data);
data = new SimpleDateFormat("dd/MM/yyyy HH:mm").format(date);
} catch (ParseException e) {
e.printStackTrace();
}
adapter.addDadosListaprojetos(data, cliente, tipoProjeto, status, idProjeto);
}while(cursor.moveToNext());
cursor.close();
pDAO.close();
}
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Intent intent = new Intent(ListaProjetosActivity.this, ListaCheckinsActivity.class);
intent.putExtra("idProjeto", idProjeto);
startActivity(intent);
}
});
}
public void novoProjeto(View v) {
Intent intent = new Intent(this, NovoProjetoActivity.class);
startActivity(intent);
}
}
我想将此 idProjeto 传递给另一个 Activity ,但它仅传递最后一项的数据。 while 中的每次循环,变量都会获得其他值。 如何获得正确的值?
最佳答案
当然,该值将在循环的每次迭代中被覆盖
。不要将它们放入 long
变量中,而是将它们放入 ArrayList
中。然后使用 onItemClick()
中的 position
值从 ArrayList
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
idProjeto = arrayList.get(position); // assuming you create a member variable ArrayList<Long> arrayList = new ArrayList<Long>()
Intent intent = new Intent(ListaProjetosActivity.this, ListaCheckinsActivity.class);
intent.putExtra("idProjeto", idProjeto);
startActivity(intent);
关于java - 如何从 onItemClickListener 内部获取 id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18903948/