public class ShowCustomer extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference reference;
AddCustomer customer;
private EditText fname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_customer);
database = FirebaseDatabase.getInstance();
reference = database.getReference("Customers");
customer = new AddCustomer();
reference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren() ) {
customer = ds.getValue(AddCustomer.class);
fname = (EditText) findViewById(R.id.fnameTxt);
fname.setKeyListener(null);
fname.setText(customer.getFname().toString());
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
问题:客户名称通过firebase数据库检索显示在列表视图中。如果我点击列表视图中的项目,则需要在另一个活动上显示客户的详细信息。鉴于bellow是listview onItemClickListner的代码段。
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(CustomerListView.this, ShowCustomer.class);
startActivity(intent);
}
});
如果点击列表视图中的任何项目,则会显示最后一个客户的fname。帮我解决这个问题。提前致谢。
这里给出了数据库结构 enter image description here
答案 0 :(得分:0)
要解决此问题,请使用以下代码:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference customersRef = rootRef.child("Customers");
ValueEventListener eventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<AddCustomer> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
AddCustomer addCustomer = ds.getValue(AddCustomer.class);
list.add(addCustomer);
}
ListView listView = (ListView) findViewById(R.id.list_view);
YourCustomAdapter<AddCustomer> arrayAdapter = new YourCustomAdapter<AddCustomer>(this, list);
listView.setAdapter(arrayAdapter);
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
customersRef.addListenerForSingleValueEvent(eventListener);
因此,您只需在.XML文件和自定义适配器中创建ListView
。就是这样!