-1

ret_idx might be null for a new user since its entry in database is not made. So whenever the app detects ret_idx is null, it shows the java.lang.NullPointerException. How do I avoid this exception from crashing my app, considering ret_idx might go null in several cases.

String ret_idx=dataSnapshot.child("name").getValue().toString();

Yash Pawse
  • 41
  • 10
  • What do you mean by avoid this error? If the value might go null and you are getting null then I\it is not an error. Wherever you are using ret_idx next, there check for null value like if(ret_idx != null) then do something you want to do. – Surabhi Choudhary Aug 10 '19 at 15:52
  • @SurabhiChoudhary I have tried both if(ret_idx!=null) and if(!ret_idx.isEmpty()) and they work fine. Problem is in the assignment of ret_idx to null and checking if(ret_idx==null) or if(ret_idx.isEmpty()). App crashes when null is retrieved from the database and assigned to String ret_idx. – Yash Pawse Aug 10 '19 at 16:06
  • in all honesty, the best way to handle a possible null pointer exception is to make sure the object you're using is not null when you're using it. – a_local_nobody Aug 10 '19 at 16:07
  • Absolutely @a_local_nobody, but what else can I expect from a non-existent record in my database? Non-existent record would always give a null I assume... – Yash Pawse Aug 10 '19 at 16:10
  • To avoid a NullPointException we use a the Try-Catch-concept. Sometimes even Try-Catch-Finally. You should read more about Exceptions and how to handle them. The Internet is full with tutorials and information about Exceptions. Basic knowledge. – TheScribbler2019 Aug 10 '19 at 16:11
  • Yes @TheScribbler2019 I've tried it, but there is a problem with the variables. They are not found outside try{ }. – Yash Pawse Aug 10 '19 at 16:15
  • re: *App crashes when null is retrieved from the database and assigned to String ret_idx.* Assignment of null does not cause that exception. Quite likely your call to ```child()``` returns null, and then you try to dereference it to call ```getValue()```. Don't do that. Check for null first. –  Aug 10 '19 at 17:59
  • 1
    @TheScribbler2019 To avoid NullPointerExceptions you should **not** use try-catch, instead you should null-checks where necessary (or try and avoid null entirely). – Mark Rotteveel Aug 11 '19 at 05:45
  • @Mark Rotteveel You are right. – TheScribbler2019 Aug 11 '19 at 06:58

1 Answers1

1

Check whether your input data is null or not and if not then assign it to ret_idx.

if(dataSnapshot.child("name").getValue() != null){
   String ret_idx=dataSnapshot.child("name").getValue().toString();
}
  • 2
    It's inefficiently doing the same database lookup twice. Save the first return value. –  Aug 10 '19 at 18:00