1

Im trying to display inside an alert dialog the variable i (succesfully)get from firebase. As i mention in the comment i get nothing. I mean i get the first declaration of the value,which is "". What im doing wrong?

EDIT: The variable name is defined at the top of my class as public String name="";

@Override
    public void handleResult(Result result) {
       AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Scan Result");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

        getItemData();

       //here im trying to print the 'name' variable from getItemData(), and i get ""
        builder.setMessage(name);
        AlertDialog alert1 = builder.create();
        alert1.show();

    }

    //here i get the item from firebase 
    public void getItemData(){
        final DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("Items").child(myResult);
        mDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
               name = dataSnapshot.child("itemname").getValue().toString();
            }
            @Override
            public void onCancelled(DatabaseError databaseError) {
                Toast.makeText(addquantityactivity.this,"there was an error",Toast.LENGTH_SHORT).show();
            }
        });
    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • You cannot simply use the value of `name` outside the `onDataChange()` method. Firebase API is asynchronous, so any code that needs data from the Firebase, needs to be inside the `onDataChange()` method, or be called from there. So please check the duplicate to see how can you solve this using a custom callback. – Alex Mamo Jul 01 '20 at 14:15
  • is there a way much easier? i new to programming, and i dont get a lot:p –  Jul 01 '20 at 14:24
  • That's the simplest way if you're a beginner. – Alex Mamo Jul 01 '20 at 14:29
  • @AlexMamo thanks for the answer. but another error occured. my idea is to scan with barcode some items and get their name from firebase. I did what you posted on the duplicate. But every time i scan a new item i get the previous scanned item's name. Like the callback is called for the same item 2 times. Whats wrong with this? –  Jul 01 '20 at 14:52

0 Answers0