I'm trying to make a mini mobile wallet which stores users' details on firebase. I'm getting the error
Attempt to invoke virtual method 'void android.widget.TextView.setText(int)' on a null object reference
while using the setText() method to show user's balance. I've referred to many other similar questions on stackoverflow, but nothing helped me out.
Here are code files I think I have problem with.
The below code if for a fragment (wallet_info.xml)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".PassBook">
<!-- TODO: Update blank fragment layout -->
<TextView
android:layout_marginTop="250dp"
android:layout_marginLeft="30dp"
android:layout_marginRight="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="25dp"
android:id="@+id/walletText"
android:text="Wallet Balance"/>
<TextView
android:layout_margin="30dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="40dp"
android:layout_below="@id/walletText"
android:id="@+id/balanceText"/>
<Button
android:id="@+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/balanceText"
android:layout_centerHorizontal="true"
android:layout_marginTop="32dp"
android:text="Request Balance"
android:onClick="onRequest"/>
</RelativeLayout>
The android:onClick="onRequest"
shows a red underline asking me to create a public method even though I've created the method in the class on which the fragment is attached.
The below code is for home.java (a class on which wallet_info.xml fragment is attached.) I'm pasting the part where I'm getting the error.
public void onRequest(View view){
tv = (TextView)findViewById(R.id.balanceText);
wallet.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
wallet_info u = dataSnapshot.child(m).getValue(wallet_info.class);
tv.setText(u.getBalance());
//tv.setText(u.getBalance());
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
The line tv.setText(u.getBalance());
throws the mentioned error.
Thank you in advance.