Hi I am trying to retrieve the unique key from the database from my ListView but I am unable to! Please Help!
Here is a picture of my Database :
Here is my Code
public class Inventory extends AppCompatActivity {
private Button AddProduct;
private DatabaseReference database;
private ListView mList;
private ArrayList<String> names = new ArrayList<>();
private ArrayList<String> keys = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_inventory);
AddProduct = (Button) findViewById(R.id.AddProduct);
AddProduct.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(Inventory.this, AddProduct.class));
}
});
mList = (ListView) findViewById(R.id.listView2);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, names);
mList.setAdapter(arrayAdapter);
database = FirebaseDatabase.getInstance().getReference("All Barcodes");
database.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(final DataSnapshot dataSnapshot) {
arrayAdapter.clear();
for(final DataSnapshot snapshot : dataSnapshot.getChildren()){
arrayAdapter.notifyDataSetChanged();
String barcode = (String) snapshot.child("barcode").getValue();
String name = (String) snapshot.child("pname").getValue();
String exp = (String) snapshot.child("expiration").getValue();
String q = (String) snapshot.child("quantity").getValue();
arrayAdapter.add("Product Name: "+name+"\nExpiry Date: "+exp+ "\nQuantity: "+q+"\nBarcode: "+ barcode );
mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {
//get position IMPT CODE
String myKey = mList.getItemAtPosition(i).toString();
String bc = myKey.split("Barcode:")[1];
bc = dataSnapshot.child(bc).getKey();
Toast.makeText(Inventory.this,bc,Toast.LENGTH_SHORT).show();
// Intent intent = new Intent(Inventory.this,Edit.class);
// intent.putExtra("value",bc);
// startActivity(intent);
}
});
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
When I clicked the Listview which displays the respective data, it will display the barcode number in a Toast as shown below. What I wanted is to retrieve "-KvaATA3zliSuv7S1RPe" which is the key of the respective data in the Toast. Any help would be greatly appreciated thanks!
UPDATE
I am now able to retrieve the key of data. However, no matter which data I clicked on the listview, it will always display the key of the Last Data in the JSON tree which is -KvaATA3zliSuv7S1RPe. Any help will be greatly appreciated.