I have beenn struggling to find out why I am getting the error: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
Below is the full description of the error:
2021-03-15 14:15:49.906 24447-24447/com.goldencrestit.quicky2 D/AndroidRuntime: Shutting down VM
2021-03-15 14:15:49.907 24447-24447/com.goldencrestit.quicky2 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.goldencrestit.quicky2, PID: 24447
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
at com.goldencrestit.quicky2.ViewProfileActivity$1.onDataChange(ViewProfileActivity.java:64)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(ValueEventRegistration.java:75)
at com.google.firebase.database.core.view.DataEvent.fire(DataEvent.java:63)
at com.google.firebase.database.core.view.EventRaiser$1.run(EventRaiser.java:55)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:264)
at android.app.ActivityThread.main(ActivityThread.java:7581)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
This error pops up when I click on the "View your Profile" button in order to load the profile page.
Below is the expected result. It is support to fetch data from my firebase realtime database to fill the dummy texts:
Check below my codes:
activity_company_portal.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
android:orientation="vertical"
tools:context=".CompanyPortal">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar_home" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:padding="20dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/logout_btn"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/ic_baseline_power_settings_new_24" />
</LinearLayout>
<ImageView
android:id="#+id/imageView3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:layout_marginTop="10dp"
app:srcCompat="#drawable/logo" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="20dp">
<Button
android:id="#+id/view_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="20dp"
android:textColor="#color/text_color_secondary"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_all_jobs" />
<Button
android:id="#+id/add_job"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/view_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/add_a_new_job" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/add_job"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/edit_your_profile" />
<Button
android:id="#+id/view_profile"
android:layout_width="match_parent"
android:layout_height="60dp"
android:background="#drawable/button_bg"
android:layout_marginTop="50dp"
android:textColor="#color/text_color_secondary"
android:layout_below="#id/edit_profile"
android:textSize="16sp"
android:letterSpacing=".2"
android:text="#string/view_your_profile" />
</RelativeLayout>
</LinearLayout>
CompanyPortalActivity.java
public class CompanyPortalActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_portal);
Toolbar toolbar = findViewById(R.id.toolbar_home);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Quicky Job Portal");
Button viewJobs = findViewById(R.id.view_job);
Button postJobs = findViewById(R.id.add_job);
Button edit_profile = findViewById(R.id.edit_profile);
Button view_profile = findViewById(R.id.view_profile);
viewJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), IndividualPostActivity.class)));
postJobs.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), PostJobsActivity.class)));
edit_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), EditProfileActivity.class)));
view_profile.setOnClickListener(v -> startActivity(new Intent(getApplicationContext(), ViewProfileActivity.class)));
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
ImageButton mLogoutBtn = findViewById(R.id.logout_btn);
mLogoutBtn.setOnClickListener(v -> {
mAuth.signOut();
sendUserToLogin();
});
}
#Override
protected void onStart() {
super.onStart();
if(mCurrentUser == null){
sendUserToLogin();
}
}
private void sendUserToLogin() {
Intent loginIntent = new Intent(getApplicationContext(), CompanyLoginActivity.class);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
loginIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(loginIntent);
finish();
}
}
activity_view_profile.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/bg_color"
tools:context=".ViewProfileActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<include
layout="#layout/toolbar"
android:id="#+id/toolbar"/>
<ImageView
android:id="#+id/imageView7"
android:layout_width="match_parent"
android:layout_height="50dp"
app:srcCompat="#drawable/logo" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginTop="10dp"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Name" />
<TextView
android:id="#+id/company_name"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Golden Crest Tech"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Business Type" />
<TextView
android:id="#+id/business_type"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Technology"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Phone Number" />
<TextView
android:id="#+id/phone_number"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="08020345678"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:text="Company Address" />
<TextView
android:id="#+id/address"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_marginTop="5dp"
android:layout_marginEnd="40dp"
android:layout_marginBottom="20dp"
android:textAlignment="center"
android:layout_marginStart="40dp"
android:textColor="#color/text_color_secondary"
android:text="Surulere, Lagos"
android:background="#drawable/text_display" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#color/text_color_primary"
android:layout_marginEnd="40dp"
android:layout_marginStart="40dp"
android:layout_marginBottom="5dp"
android:text="Company Detail" />
<EditText
android:id="#+id/editTextTextMultiLine"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="40dp"
android:layout_marginEnd="40dp"
android:background="#drawable/text_display_2"
android:clickable="false"
android:editable="false"
android:ems="10"
android:enabled="false"
android:fontFamily="#font/open_sans"
android:gravity="start|top"
android:inputType="textMultiLine"
android:text="#string/company_detail_dummy"
android:textColor="#color/text_color_secondary"
android:textSize="14sp" />
<Button
android:id="#+id/edit_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/button_bg"
android:layout_marginLeft="40dp"
android:layout_marginRight="40dp"
android:layout_marginTop="10dp"
android:layout_marginBottom="20dp"
android:textColor="#color/text_color_secondary"
android:textAllCaps="false"
android:textSize="16sp"
android:text="Edit Profile" />
</LinearLayout>
</ScrollView>
ViewProfileActivity.java
public class ViewProfileActivity extends AppCompatActivity {
private DatabaseReference myRef;
TextView company_name_txt, business_type_txt, phone_number_txt, company_address_txt;
EditText company_detail_txt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_profile);
company_name_txt = findViewById(R.id.company_name);
business_type_txt = findViewById(R.id.business_type);
phone_number_txt = findViewById(R.id.phone_number);
company_address_txt = findViewById(R.id.address);
company_detail_txt = findViewById(R.id.company_detail);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Objects.requireNonNull(getSupportActionBar()).setTitle("Company Profile");
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true);
Objects.requireNonNull(getSupportActionBar()).setDisplayShowHomeEnabled(true);
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId()==android.R.id.home){
finish();
}
return super.onOptionsItemSelected(item);
}
}
Below is what I am trying to display on the Job Detail Layout:
The error seems to come from this piece of code:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
String phoneNumber = snapshot.child("phone_number").getValue().toString();
String companyAddress= snapshot.child("address").getValue().toString();
String businessType = snapshot.child("business_type").getValue().toString();
company_name_txt.setText(companyName);
business_type_txt.setText(businessType);
company_address_txt.setText(companyAddress);
phone_number_txt.setText(phoneNumber);
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
The above code is loading all data from /Company Profile and then trying to read the company_name property from it. But if we look at the data you shared, there is no /Company Profile/company_name property, so that explains why getValue() returns null and the toString() then leads to the exception you get.
It seems your JSON tree consists of: /Company Profile/$uid/$pushid. How to property load the data from this structure depends on how much information you already know in your code, so let's look at the options:
If you know both the UID and the push ID of the information you want to load, you can do load just that with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
String pushid = "-MVmyqx...3rwsAO"; // must be the exact, complete value
myRef.child(uid).child(pushid().addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()){
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
If you know the UID, but not the push ID, of the information you want to load, you can load all push IDs and loop over them with:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
String uid = "6babpG...MxLg33"; // must be the exact, complete value
myRef.child(uid).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
So here we loop over dataSnapshot.getChildren() to get across the unknown push IDs from the database. This means we can have multiple child nodes, so you may want to consider using a list view/recycler view for displaying the data.
The final case is if you know neither the UID nor the push ID of the data you want to display. In that case you need two nested loops to navigate over the data, one for the UIDs in the JSON, and one for the push IDs. So:
myRef = FirebaseDatabase.getInstance().getReference().child("Company Profile");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
for (DataSnapshot snapshot: userSnapshot.getChildren()) {
String companyName = snapshot.child("company_name").getValue().toString();
...
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException(); // never ignore errors
}
});
You'll note that the solution is quite similar to the previous one, but now with a second loop. Here too, you'll have to consider what is the best UI element to display the structure, as now you're navigating/parsing an entire tree-like structure from the database.
Related
After message sending it isn't showing. But I'm receiving the message in Firebase Database. What's wrong with it? Have you any suggestions?
MainActivity.class
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
FirebaseUser currentUser;
private FirebaseListAdapter<ChatMessage> adapter;
private final static String TAG = "LOG";
EditText input;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
checkAuth();
input = (EditText)findViewById(R.id.input);
FloatingActionButton fab =
(FloatingActionButton)findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (input.getText().toString().equals(null) && input.getText().toString().equals("")) {
Log.i(TAG, "Mesage is empty");
} else {
// Read the input field and push a new instance
// of ChatMessage to the Firebase database
FirebaseDatabase.getInstance()
.getReference()
.push()
.setValue(new ChatMessage(input.getText().toString(),
FirebaseAuth.getInstance()
.getCurrentUser()
.getDisplayName())
);
displayChatMessages();
// Clear the input
input.setText("");
}
}
});
}
private void displayChatMessages() {
ListView listOfMessages = (ListView) findViewById(R.id.list_of_messages);
//Suppose you want to retrieve "chats" in your Firebase DB:
Query query = FirebaseDatabase.getInstance().getReference();
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.message)
.build();
//Finally you pass them to the constructor here:
adapter = new FirebaseListAdapter<ChatMessage>(options){
#Override
protected void populateView(View v, ChatMessage model, int position) {
// Get references to the views of message.xml
TextView messageText = (TextView) v.findViewById(R.id.message_text);
TextView messageUser = (TextView) v.findViewById(R.id.message_user);
TextView messageTime = (TextView) v.findViewById(R.id.message_time);
// Set their text
messageText.setText(model.getMessageText());
messageUser.setText(model.getMessageUser());
Log.i(TAG, model.getMessageUser() + ": " + model.getMessageText());
// Format the date before showing it
messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm:ss)",
model.getMessageTime()));
}
};
listOfMessages.setAdapter(adapter);
}
public void checkAuth(){
// Check if user is signed in (non-null) and update UI accordingly.
currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
displayChatMessages();
///
} else {
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
}
#Override
public void onStart() {
super.onStart();
checkAuth();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.textfield.TextInputLayout
android:id="#+id/textInputLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#id/fab"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/fab">
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/hint" />
</com.google.android.material.textfield.TextInputLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:clickable="true"
android:tint="#android:color/white"
app:fabSize="mini"
app:layout_constraintStart_toStartOf="#+id/textInputLayout"
/>
<ListView
android:id="#+id/list_of_messages"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="16dp"
android:divider="#android:color/transparent"
android:dividerHeight="12dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
message.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/message_user"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/message_user"
android:layout_alignParentEnd="true"
android:id="#+id/message_time" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/message_user"
android:layout_alignParentStart="true"
android:layout_marginTop="5dp"
android:id="#+id/message_text"
android:textAppearance="#style/TextAppearance.AppCompat.Body1"
android:textSize="18sp" />
By the way, it's not a good solution to obey type more text.
It looks like your post is mostly code; please add some more details.
I am getting a blank listView on running this code.I have checked the contents of the array by displaying them in a text view to the bottom of the listView.Changing to linear layout didn't work as well.
This is my first time using a listView so forgive me if its a stupid question.
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_background"
tools:context=".current_month">
<ListView
android:id="#+id/barcode_detail"
android:layout_width="374dp"
android:layout_height="403dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.277" />
<TextView
android:id="#+id/title_tv"
android:layout_width="299dp"
android:layout_height="42dp"
android:layout_marginStart="141dp"
android:layout_marginEnd="141dp"
android:fontFamily="sans-serif-black"
android:textAlignment="center"
android:textColor="#F7F3F3"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.037" />
<TextView
android:id="#+id/resultView"
android:layout_width="245dp"
android:layout_height="143dp"
android:layout_marginStart="29dp"
android:layout_marginTop="29dp"
android:layout_marginEnd="65dp"
android:layout_marginBottom="65dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/bar_code_scan"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_detail" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/bar_code_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:clickable="true"
android:focusable="true"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/fruit_scan"
app:layout_constraintEnd_toEndOf="#+id/fruit_scan"
app:srcCompat="#drawable/ic_barcode_scan" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/scanButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="339dp"
android:layout_marginEnd="16dp"
android:layout_marginBottom="16dp"
android:clickable="true"
android:contentDescription="TODO"
android:focusable="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:srcCompat="#drawable/ic_baseline_add_24" />
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/fruit_scan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:clickable="true"
android:focusable="true"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/scanButton"
app:layout_constraintEnd_toEndOf="#+id/scanButton"
app:srcCompat="#drawable/ic_vegetable_scan" />
</androidx.constraintlayout.widget.ConstraintLayout>
JAVA CODE (A subset of the oncreate function)
final ArrayList<String> dat = new ArrayList<>();
final FirebaseUser users = firebaseAuth.getCurrentUser();
String result = users.getEmail().replace(".","");
DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference().child("Users").child(result).child("January").child("Product");
databaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
dat.add(snapshot.child("productname").getValue().toString());
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
ArrayAdapter arrayAdapter = new ArrayAdapter(current_month.this, android.R.layout.simple_list_item_1,dat);
barcode_detail.setAdapter(arrayAdapter);
Your arrayAdapter is not being notified of the changes made to list.
after adding items to the list you should call arrayAdapter.notifyDataSetChanged();
Your code should look something like this:
final ArrayList<String> dat = new ArrayList<>();
final FirebaseUser users = firebaseAuth.getCurrentUser();
String result = users.getEmail().replace(".","");
ArrayAdapter arrayAdapter = new ArrayAdapter(current_month.this, android.R.layout.simple_list_item_1,dat);
barcode_detail.setAdapter(arrayAdapter);
DatabaseReference databaseReference2 = FirebaseDatabase.getInstance().getReference().child("Users").child(result).child("January").child("Product");
databaseReference2.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()){
dat.add(snapshot.child("productname").getValue().toString());
}
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Hello my problem is that i am getting a null pointer exception in my program i am getting a exception in a imageview of a layout file i am trying to make a firebase app so i use try-catch blocks for handling firebase error so i decided to make a beautiful dialog box but when i test it first time it runs but now it throws a null pointer exception so please help me here is my code and activities
:- my register activity
public class registerActivity extends Activity {
Dialog error_dialog_box_register;
TextView dialog_title_register, dialog_message_register;
ImageView dialog_main_image, dialog_cancel_image;
Button ok_button, login_button;
private Button RegisterButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
RegisterButton = findViewById(R.id.register_in_button);
RegisterButtonListener();
}
private void RegisterButtonListener() {
RegisterButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
CreateNewAccount();
}
});
}
private void CreateNewAccount() {
mAuth.createUserWithEmailAndPassword(Email, Password)
.addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Register_Progress_bar.setVisibility(View.GONE);
SendUserToDate_of_birthActivity();
} else {
try {
Register_Progress_bar.setVisibility(View.GONE);
throw Objects.requireNonNull(task.getException());
} catch (FirebaseAuthUserCollisionException f) {
ShowErrorPopup();
Toast.makeText(registerActivity.this, "User already exists", Toast.LENGTH_SHORT).show();
} catch (FirebaseNetworkException e) {
Toast.makeText(registerActivity.this, "Error network error", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
#SuppressLint("SetTextI18n")
private void ShowErrorPopup() {
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
dialog_cancel_image = (ImageView) findViewById(R.id.Cancel_dialog_box_register);
ok_button = (Button) findViewById(R.id.dialog_ok_button_register);
login_button = (Button) findViewById(R.id.dialog_login_button_register);
dialog_title_register = (TextView) findViewById(R.id.Dialog_title_register);
dialog_message_register = (TextView) findViewById(R.id.dialog_message_register);
dialog_cancel_image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
error_dialog_box_register.dismiss();
}
});
login_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SendUserToLoginActivity();
}
});
dialog_title_register.setText("Error");
dialog_message_register.setText("Email already exists please login or try again");
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.show();
}
}
Here is my xml file:-
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical">
<ImageView
android:id="#+id/Cancel_dialog_box_register"
android:layout_width="46dp"
android:layout_height="38dp"
android:layout_alignParentEnd="true"
android:layout_marginTop="7dp"
android:layout_marginEnd="7dp"
android:elevation="5dp"
android:src="#drawable/ic_close_black_24dp"
/>
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
app:cardBackgroundColor="#color/ColorRed"
app:cardCornerRadius="15dp"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:layout_marginBottom="25dp"
android:orientation="vertical">
<TextView
android:id="#+id/Dialog_title_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="25sp"
android:textStyle="bold" />
<ImageView
android:id="#+id/dialog_main_image_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="10dp"
android:src="#drawable/ic_error_black_24dp" />
<TextView
android:id="#+id/dialog_message_register"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginBottom="20dp"
android:text=""
android:textAlignment="center"
android:textColor="#000000"
android:textSize="18sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/dialog_login_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="#string/login"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp" />
<Button
android:id="#+id/dialog_ok_button_register"
android:layout_width="180dp"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:layout_marginStart="15dp"
android:layout_marginTop="20dp"
android:background="#drawable/login_b_custom"
android:text="Ok"
android:textColor="#color/colorPrimaryDark"
android:textSize="15sp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And i am getting error like these
2019-08-03 15:52:13.840 5711-5711/? E/Zygote: isWhitelistProcess - Process is Whitelisted
2019-08-03 15:52:13.841 5711-5711/? E/Zygote: accessInfo : 1
2019-08-03 15:52:43.642 5711-5711/com.geetmp3.themusicapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.geetmp3.themusicapp, PID: 5711
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
at com.geetmp3.themusicapp.AccountCreation.registerActivity.ShowErrorPopup(registerActivity.java:193)
at com.geetmp3.themusicapp.AccountCreation.registerActivity.access$300(registerActivity.java:34)
at com.geetmp3.themusicapp.AccountCreation.registerActivity$2.onComplete(registerActivity.java:146)
at com.google.android.gms.tasks.zzj.run(Unknown Source:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7076)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)
Please reply me why i am getting null pointer exception and please help me
In your OnCreate function you assign your RegisterButton as:
RegisterButton = findViewById(R.id.register_in_button);
but in your layout you have two buttons with the IDs of:
android:id="#+id/dialog_login_button_register"
and
android:id="#+id/dialog_ok_button_register"
So your findViewById call returns with null because no button with the ID of register_in_button exists. Then you get an exception when you attempt to invoke the null object's method.
Please create variables reference by dialog because all ImageVeiw or textview are inside the dialog
error_dialog_box_register= new Dialog(this);
error_dialog_box_register.requestWindowFeature(Window.FEATURE_NO_TITLE);
error_dialog_box_register.setContentView(R.layout.custom_popup_p);
error_dialog_box_register.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
error_dialog_box_register.setCancelable(false);
dialog_cancel_image = error_dialog_box_register.findViewById(R.id.Cancel_dialog_box_register);
I am using Recycleview Adapter to show my list of items from Firebase Real-time Database.
I have a button which shows text value from Firebase initially when clicked will change the same key value in Firebase Database and I want it to show the updated text in Button too.
But it doesn't unless exit activity and reopen activity. Then it displays the updated value in Button text instead of the initial one.
How to update and show the value without exiting the Adapter?
I used notifyItemChanged(position) but it doesn't do anything.
Here is my Code
public class SubjectBooksAdapter extends RecyclerView.Adapter<SubjectBooksAdapter.MyViewHolder> {
ArrayList<Books> bookslist;
CardView cv;
FirebaseAuth fauth;
FirebaseDatabase database;
DatabaseReference dbreference;
Books g;
SubjectBooksAdapter adapter;
public SubjectBooksAdapter(ArrayList<Books> bookslist){
this.bookslist = bookslist;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout,parent,false);
return new MyViewHolder(v);
}
public class MyViewHolder extends RecyclerView.ViewHolder {
Button mSolved;
MyViewHolder(final View itemView) {
super(itemView);
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
dbreference.keepSynced(true);
mSolved = (Button) itemView.findViewById(R.id.book_solved);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
database = FirebaseDatabase.getInstance();
dbreference = database.getReference("books");
g = bookslist.get(position);
holder.mSolved.setText(g.getMarkid());
holder.bookName.setText(g.getBname());
holder.bookprice.setText("Rs. "+g.getPrice());
holder.sellername.setText(g.getSellername());
holder.mSolved.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference classicalMechanicsRef = rootRef.child("books").child(g.getCondition()).child(g.getBookid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("bmark").getRef().setValue("Solved");
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
};
classicalMechanicsRef.addListenerForSingleValueEvent(valueEventListener);
notifyItemChanged(position);
}
});
#Override
public int getItemCount() {
return bookslist.size();
}
}
xml code is
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<android.support.v7.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/my_card_view"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:layout_marginBottom="3dp"
android:layout_marginTop="4dp" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="2dp" >
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".9"
android:layout_marginBottom="5dp">
<ImageView
android:id="#+id/imageView"
android:layout_width="75dp"
android:layout_height="75dp"
android:scaleType="fitXY"
android:padding="2dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="8dp"
android:paddingRight="7dp"
android:gravity="left">
<TextView
android:id="#+id/book_name"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight=".4"
android:text="Book Name"
android:textStyle="bold"
android:fontFamily="sans-serif-condensed"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_margin="1dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="#+id/seller_name"
android:layout_width="match_parent"
android:fontFamily="sans-serif"
android:layout_height="35dp"
android:layout_weight=".3"
android:text="Seller"
android:layout_margin="2dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<Button
android:fontFamily="sans-serif-condensed"
android:gravity="center"
android:textColor="#ffffff"
android:text="Remove"
android:textStyle="bold"
android:layout_marginEnd="15dp"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_marginRight="15dp"
android:layout_width="wrap_content"
android:id="#+id/book_solved"
android:textAllCaps="false"
android:layout_height="35dp"
android:background="#drawable/buttonshape1"
android:padding="8dp"
android:layout_toRightOf="#id/seller_name"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:orientation="horizontal"
android:layout_marginTop="4dp"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/profile_details"
android:layout_width="match_parent"
android:layout_height="35dp"
android:fontFamily="sans-serif-condensed"
android:text="View Details"
android:background="#drawable/buttonshape1"
android:gravity="center"
android:textColor="#ffffff"
android:textStyle="bold"
android:layout_marginEnd="15dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_marginRight="15dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
Thanks in advance.
Whatever the value you want to change in your adapter you can do using notifyItemChanged(position). NotifyItemChange only works when there is a change in your Model Class.
Let say here you are setting the value your Book Name on a TextView by using this code.
Books g = bookslist.get(position);
holder.bookName.setText(g.getBname());
Now if you want to change the value of Book name on Button click you have to change the value in your ArrayList Model also then notify it.
Books g = bookslist.get(position);
g.setBname("your new value");
After this, your notifyItemChanged(position) will display the new value. This is how notify works in RecyclerView
Why you have to do so?
Whenever the notify is called in RecylerView it again set the value from the ArrayList. But in your case, the value is not updated locally in your list but is updated in the FireBase. That's why you get the updated value whenever you again open your app.
NOTE
To change the value of Button with text Remove, get the Markid in the Datachange of the FireBase. Then set that value in the respective model(of that position) from the ArrayList for String Markid.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
dataSnapshot.child("bmark").getRef().setValue("Solved");
// Here you need to save the value in the arraylist.
bookslist.get(position).setMardid("Here what ever the value you will pass will get updated on the button after notify"); //Try adding the static string that you want after button click.
notifyItemChanged(position)
}
Error:
android.support.v7.widget.AppCompatEditText{8701551bVFED..CL.
.......484,0-747,118 #7f0b006c app:id/name_text
I am trying to set user's name information to FirebaseUser "DisplayName" during the registration. I am new to android, java and firebase. But couldn't find any solution despite my all researchs. id/name_text is the edit text which takes name from the user in registation. I thought it's a string issue, but couldn't fix.
Help. Thanks.
Here are the codes.
public class RegisterActivity extends AppCompatActivity {
#BindView(R.id.register_button) Button mRegisterButton;
#BindView(R.id.surname_edittext) EditText mSurnameEditText;
#BindView(R.id.name_text) EditText mNameEditText;
#BindView(R.id.password_edittext) EditText mPasswordEditText;
#BindView(R.id.mail_edittext) EditText mMailEditText;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
}
#OnClick(R.id.register_button)
public void register_button(View view){
RegisterUser();
}
private void RegisterUser() {
String surname = mSurnameEditText.getText().toString().trim();
String name = mNameEditText.getText().toString().trim();
String password = mPasswordEditText.getText().toString().trim();
String mail = mMailEditText.getText().toString().trim();
if (TextUtils.isEmpty(name)) {
Toast.makeText(this, "enter the name", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(surname)) {
Toast.makeText(this, "enter the surname", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "enter the password", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(mail)) {
Toast.makeText(this, "enter the mail", Toast.LENGTH_SHORT).show();
return;
}
mAuth.createUserWithEmailAndPassword(mail,password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Toast.makeText(RegisterActivity.this,"Successfully",Toast.LENGTH_SHORT).show();
savetheinfo();
}
else{
Toast.makeText(RegisterActivity.this,"Could not registered , please try again...",Toast.LENGTH_SHORT).show();
}
}
});
}
private void savetheinfo() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(String.valueOf(mNameEditText)).build();
user.updateProfile(profileUpdates);
}
}
public class ProfileActivity extends AppCompatActivity {
#BindView(R.id.user_name) TextView mUserName;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
ButterKnife.bind(this);
mAuth = FirebaseAuth.getInstance();
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
setDataToView(user);
}
private void setDataToView(FirebaseUser user) {
mUserName.setText(user.getDisplayName());
}
}
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="24dp"
android:text="REGISTER"
android:layout_marginBottom="50dp"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name: "/>
<EditText
android:id="#+id/name_text"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Surname: "/>
<EditText
android:id="#+id/surname_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Mail: "/>
<EditText
android:id="#+id/mail_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Password: "/>
<EditText
android:id="#+id/password_edittext"
android:layout_width="100dp"
android:layout_height="wrap_content" />
</LinearLayout>
<Button
android:id="#+id/register_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Register"
android:layout_marginTop="50dp"/>
</LinearLayout>
String.valueOf(mNameEditText) is equivalent to mNameEditText.toString() if the view is not null. You're probably looking for mNameEditText.getText().toString() which gives you the content of the EditText element.
I was able to resolve the issue as follows:
I simply used mNameEditText.getText().toString(). I forgot the .getText() in between.