0

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 : 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!

Screenshot of Activity

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.

Dugong98
  • 381
  • 1
  • 5
  • 15

1 Answers1

2

Inside your for-loop, change dataSnapshot to snapshot.

  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 = snapshot.getKey(); // changed from dataSnapshot to snapshot
                    Toast.makeText(Inventory.this,bc,Toast.LENGTH_SHORT).show();
                   // Intent intent  = new Intent(Inventory.this,Edit.class);
                  //  intent.putExtra("value",bc);
                   // startActivity(intent);
                }
            });

        }

EDITS:

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

        final List<String> keys = new ArrayList<>(); // will contain list of keys corresponding to listview item
        database.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(final DataSnapshot dataSnapshot) {
                arrayAdapter.clear();
                for(final DataSnapshot snapshot : dataSnapshot.getChildren()){


                    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();
                    names.add("Product Name: "+name+"\nExpiry Date: "+exp+ "\nQuantity: "+q+"\nBarcode: "+ barcode );
                    keys.add(snapshot.getKey());


                }
                arrayAdapter.addAll(names);
                arrayAdapter.notifyDataSetChanged();

                mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, final int i, long l) {


                        String myKey = keys.get(i);
                        Toast.makeText(Inventory.this, myKey ,Toast.LENGTH_SHORT).show();
                        // Intent intent  = new Intent(Inventory.this,Edit.class);
                        //  intent.putExtra("value",bc);
                        // startActivity(intent);
                    }
                });



            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });




    }

}
Sumit Jha
  • 2,095
  • 2
  • 21
  • 36
  • Thanks for Your Response! It now displays the key of the last data which is "-KvaATA3zliSuv7S1RPe", regardless of which data I click on the listview. I Example, I click the listView with the Product name "Dog", I would like to retrieve the key for that, any clue how? Thanks – Dugong98 Oct 04 '17 at 12:50
  • please check edits. I have slightly refactored your code. Placed comments where there is change. – Sumit Jha Oct 04 '17 at 13:47
  • Not all Heroes wear capes, Thanks a lot! The code works fine! – Dugong98 Oct 04 '17 at 13:59
  • Glad to help you Sir !! My pleasure :) – Sumit Jha Oct 04 '17 at 14:45