2

Button Click Event Code :

   btnsubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {


                    String meterip = textView.getText().toString().trim();

                    FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
                    String userid = user.getUid();
                    Log.d("User Id",userid);

                    dbmeter= FirebaseDatabase.getInstance().getReference("Meter").child(userid);
                  Query query=dbmeter.orderByChild("final_Reading").limitToLast(1);

                    query.addListenerForSingleValueEvent(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {


                             for(DataSnapshot customerSnapshot : dataSnapshot.getChildren()){

                                Meter m = customerSnapshot.getValue(Meter.class);
                                fmonth=m.getFinal_Month();
                                fyear=m.getFinal_Year();
                                freading=m.getFinal_Reading();
                                Log.d("Final Reading",freading);


                            }

                            if (dataSnapshot.getValue()==null)
                            {
                                Toast.makeText(getApplicationContext(),"Database Data not Found",Toast.LENGTH_LONG).show();
                            }

                        }

                        @Override
                        public void onCancelled(DatabaseError databaseError) {

                        }
                    });


                    Log.d("Final Reading",freading);
                    int imr = Integer.parseInt(freading); //Error indicating int null value
                    int fmr = Integer.parseInt(meterip);

                    int unit = fmr-imr;
                    unitconsume = String.valueOf(unit);

                    int energy = Integer.parseInt(Energy);
                    int rent = Integer.parseInt(Rent);
                    int price = unit*energy;
                    float gstf = (float) (price*12)/100;

                    float grossamount = (float) price+rent+gstf;
                    gross = String.valueOf(grossamount);

                    gst = String.valueOf(gstf);

                    Date date = new Date();

                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMMM");
                    lmonth=simpleDateFormat.format(date).toUpperCase();

                    simpleDateFormat = new SimpleDateFormat("yyyy");
                    lyear=simpleDateFormat.format(date).toUpperCase();


                    String id = dbmeter.push().getKey();

                   Meter c = new Meter(id, freading,fmonth,fyear,meterip,lmonth,lyear,unitconsume,Energy,gst,Rent,gross);
                    dbmeter.child(id).setValue(c);
                Intent intent = new Intent(MeterReading.this, Drawer_MainPage.class);
                    startActivity(intent);
                    finish();

                }

            });

Database Json Structure in Firebase as shown below. In Meter, First Child is User ID and then Push Id.

enter image description here

I want to fetch last entry for Meter Reading and need to fetch Final_Reading value to calculate further but I'm getting null instead correct data. I used firebase for same Meter but with addValueListener where i fetched using class but here not able to get.

I saw in Debug mode where it does not enter into dbmeter.add.

I have declared all used variables above onCreate() Method.

Error

 java.lang.NumberFormatException: Invalid int: ""

coming right now at this first row that i fetched

int imr = Integer.parseInt(freading);
coder
  • 8,346
  • 16
  • 39
  • 53
Umang
  • 90
  • 9

1 Answers1

1

You cannot use something now that hasn't been loaded yet. With other words, you cannot simply create the freading variable as a global variable and use the result that you are getting from the database outside the onDataChange() method because it will always be null, due the asynchronous behaviour of this method. This means that by the time you are trying to use that result outside that method, the data hasn't finished loading yet from the database and that's why is not accessible. A quick solve for this problem would be to use that results only inside the onDataChange() method, or if you want to use it outside, I recommend you see the last part of my anwser from this post in which I have exaplined how it can be done using a custom callback. You can also take a look at this video for a better understanding.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193