0

So I try to compare 2 values, one is the "coinAmount" from Firebase, it's a Long value, and an EditText input (Which is a String).

Basically what I'm trying to achieve is, I want to show a warning if the input exceeds the coin amount that the user have.

        String coinAmount = coinWrapper.getEditText().getText().toString();

        if (Long.parseLong(coinAmount) >= coinValue) {

          Toast.makeText(getApplicationContext(), "You don't have enough coins!",
              Toast.LENGTH_SHORT).show();
        } else {

          Intent intent = new Intent(getActivity(), FriendActivity.class);
          intent.putExtra("coin", coinAmount);
          intent.putExtra("choice", choice);
          startActivity(intent);
        }

The reason I get the user input as String is because I'm going to display that value as a text later, so while I'm comparing I parsed it to Long. However, when I run the app I get this NullPointerException:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: ege.mevzubahis, PID: 13369
java.lang.NullPointerException
    at ege.mevzubahis.Fragments.BetsDialogFragment.onClick(BetsDialogFragment.java:135)
    at ege.mevzubahis.Fragments.BetsDialogFragment_ViewBinding$4.doClick(BetsDialogFragment_ViewBinding.java:70)
    at butterknife.internal.DebouncingOnClickListener.onClick(DebouncingOnClickListener.java:22)
    at android.view.View.performClick(View.java:4478)
    at android.view.View$PerformClick.run(View.java:18698)
    at android.os.Handler.handleCallback(Handler.java:733)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:149)
    at android.app.ActivityThread.main(ActivityThread.java:5257)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:515)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
    at dalvik.system.NativeStart.main(Native Method)

Here is the part where I try to get coinAmount from Firebase:

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    userID=sharedPreferences.getString("userIDKey",null);


    mDatabase.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {

        coinValue = (Long) dataSnapshot.child("coin").getValue();

      }

      @Override
      public void onCancelled(DatabaseError databaseError) {

        //Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

      }
    });

error is in this part:

if (Long.parseLong(coinAmount) >= coinValue) {

Full code

public class BetsDialogFragment extends DialogFragment implements View.OnClickListener {

  @BindView(R.id.tv_match) TextView tv_match;
  @BindView(R.id.textView2) TextView textView2;
  @BindView(R.id.textInputLayout) TextInputLayout textInputLayout;
  @BindView(R.id.radioButton4) RadioButton radioButton4;
  @BindView(R.id.radioButton5) RadioButton radioButton5;
  @BindView(R.id.radioButton6) RadioButton radioButton6;
  @BindView(R.id.button2) Button sendButton;

  String matchName;
  private DatabaseReference mDatabase;
  private RadioGroup radioGroup;
  private String choice;
  private EditText editText;
  private TextInputLayout coinWrapper;
  public Long coinValue;

  SharedPreferences sharedPreferences;
  private String userID;

  @Nullable @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
      Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.custom_dialog, null);
    matchName = getArguments().getString("betNameInPosition");
    mDatabase = FirebaseDatabase.getInstance().getReference();
    radioGroup = (RadioGroup) view.findViewById(R.id.radioGroup);
    editText = (EditText) view.findViewById(R.id.editText);
    coinWrapper = (TextInputLayout) view.findViewById(R.id.textInputLayout);
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    userID=sharedPreferences.getString("userIDKey",null);


    mDatabase.child("Users").child(userID).addListenerForSingleValueEvent(new ValueEventListener() {
      @Override
      public void onDataChange(DataSnapshot dataSnapshot) {

        coinValue = (Long) dataSnapshot.child("coin").getValue();

        Log.v("coin value: ", coinValue.toString());

      }

      @Override
      public void onCancelled(DatabaseError databaseError) {

        //Log.w(TAG, "loadPost:onCancelled", databaseError.toException());

      }
    });

    mDatabase.child("Bets")
        .child("Sports")
        .child(matchName)
        .addListenerForSingleValueEvent(new ValueEventListener() {
          @Override public void onDataChange(DataSnapshot dataSnapshot) {
            try {
              Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
              String value = (String) map.get("matchname").toString();
              tv_match.setText(value);
              String durationValue = (String) map.get("duration").toString();
              textView2.setText("Due to: " + durationValue);

              coinValue = (Long) dataSnapshot.child("coin").getValue();
            } catch (Throwable t) {
              Log.e("trycatchFAIL", "b");
            }
          }

          @Override public void onCancelled(DatabaseError databaseError) {

          }
        });

    ButterKnife.bind(this, view);
    return view;
  }

  @OnClick({ R.id.radioButton4, R.id.radioButton5, R.id.radioButton6})
  public void onClick(View view) {

    switch (view.getId()) {
      case R.id.radioButton4:
        choice = "home";
        Toast.makeText(getApplicationContext(), "choice: Home", Toast.LENGTH_SHORT).show();
        break;
      case R.id.radioButton5:
        choice = "draw";
        Toast.makeText(getApplicationContext(), "choice: Draw", Toast.LENGTH_SHORT).show();
        break;
      case R.id.radioButton6:
        choice = "away";
        Toast.makeText(getApplicationContext(), "choice: Away", Toast.LENGTH_SHORT).show();
        break;

    }
  }

  @OnClick(R.id.button2)
  public void onClickSendButton(View view){
    String coinAmount = coinWrapper.getEditText().getText().toString();

    Log.v("coinAmount",coinAmount);

    if (Long.parseLong(coinAmount) >= coinValue) {

      Toast.makeText(getApplicationContext(), "You don't have enough coins!",
          Toast.LENGTH_SHORT).show();
    } else {

      Intent intent = new Intent(getActivity(), FriendActivity.class);
      intent.putExtra("coin", coinAmount);
      intent.putExtra("choice", choice);
      startActivity(intent);
    }


  }
}
Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Ege Kuzubasioglu
  • 5,991
  • 12
  • 49
  • 85

2 Answers2

2
if (Long.parseLong(coinAmount) >= coinValue).  

there is the problem:
if coinAmount is null, will throw java.lang.NumberFormatException: null so it looks like coinValue is null.
because of using ">=", Java will try to change Long - > long. if the item is null, jvm will throw java.lang.NullPointerException.

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
cocalrush
  • 36
  • 3
  • You can't get `null` from an EditText `toString` – OneCricketeer Apr 27 '17 at 17:18
  • @cricket_007 they said "so it looks like coinValue is null." I think the analyse is correct. – njzk2 Apr 27 '17 at 17:29
  • @njzk2 I was making an additional comment. The way it is worded is confusing, but yes, `coinValue` is the null value here, though this just re-phrases the stacktrace, not provides a solution to the problem – OneCricketeer Apr 27 '17 at 17:31
  • @cricket_007 good point. Although the OP may not be aware that this comparison requires unboxing, and that the unboxing can cause the NPE. – njzk2 Apr 27 '17 at 17:33
1

If you get a NullPointer there, you also should get a NullPointer here.

   coinValue = (Long) dataSnapshot.child("coin").getValue();

   Log.v("coin value: ", coinValue.toString());

So, the problem is that Firebase didn't return you anything, or you clicked before it did.

One solution is to do a null check while you unbox the Long object yourself.

long _coinValue = if (coinValue == null) ? 0 : coinValue.longValue(); 

if (Long.parseLong(coinAmount) >= _coinValue) {
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245