This question already has answers here:
What is a NullReferenceException, and how do I fix it?
(27 answers)
Closed 3 years ago.
I don't know what make problem that show follower follow list,
it was working but after few days later (maybe there is possbility i touch something...) it didn't working
what makes it error NullPointerException?
This is my Error
2019-06-17 11:53:31.158 8298-8298/com.example.blogapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.blogapp, PID: 8298
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.together.Activities.FollowersActivity$5.onDataChange(FollowersActivity.java:157)
at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database##17.0.0:184)
at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database##17.0.0:75)
at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database##17.0.0:63)
at com.google.firebase.database.core.view.
Nothing showing redline ... just null point
This is my btn that i clicked*
followers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FollowersActivity.class);
intent.putExtra("id", profileid);
intent.putExtra("title","followers");
startActivity(intent);
}
});
following.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getContext(), FollowersActivity.class);
intent.putExtra("id", profileid);
intent.putExtra("title","following");
startActivity(intent);
}
});
This is my FollowersActivity
package com.example.together.Activities;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import com.example.together.Adapter.UserAdapter;
import com.example.together.Model.User;
import com.example.together.R;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class FollowersActivity extends AppCompatActivity {
String id;
String title;
List<String> idList;
RecyclerView recyclerView;
UserAdapter userAdapter;
List<User> userList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_followers);
Intent intent = getIntent();
id = intent.getStringExtra("id");
title = intent.getStringExtra("title");
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
recyclerView = findViewById(R.id.recycler_view);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
userList = new ArrayList<>();
userAdapter = new UserAdapter(this, userList, false);
recyclerView.setAdapter(userAdapter);
idList = new ArrayList<>();
switch (title){
case "likes":
getLikes();
break;
case "following":
getFollowing();
break;
case "followers":
getFollowers();
break;
}
}
private void getLikes() {
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Likes")
.child(id);
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowing(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(id).child("following");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void getFollowers(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Follow")
.child(id).child("followers");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
idList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
idList.add(snapshot.getKey());
}
showUsers();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
private void showUsers(){
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
for (String id : idList){
if (user.getId().equals(id)){
userList.add(user);
}
}
}
userAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
The user object is null and you are trying to retrieve data from null object
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
userList.clear();
for (DataSnapshot snapshot : dataSnapshot.getChildren()){
User user = snapshot.getValue(User.class);
// check user exists or not.. here user gets null
if(user!=null){
for (String id : idList){
if (user.getId().equals(id)){
userList.add(user);
}
}}
}
Check a profileid on first activity.
intent.putExtra("id", profileid);
and make sure print a log here is you get a value of profileid
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have been getting this error since I implemented the
public void getOtherAnimals(){
DatabaseReference otherAnimalDb = FirebaseDatabase.getInstance().getReference().child("Users").child(animalTwo);
otherAnimalDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.exists() && !snapshot.child("connections").child("no").hasChild(currentUId) && !snapshot.child("connections").child("yes").hasChild(currentUId)){
Cards item = new Cards(snapshot.getKey(), snapshot.child("name").getValue().toString());
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
section of code, the program worked beautifully before. I have done my reading on NullPointerExceptions but I don't have enough experience working with them to find the issue. I understand my program is pointing to a null object, but I cannot find it.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.android.adoptme, PID: 20525
java.lang.NullPointerException: Attempt to invoke interface method 'int java.lang.CharSequence.length()' on a null object reference
at java.util.regex.Matcher.reset(Matcher.java:177)
at java.util.regex.Matcher.<init>(Matcher.java:90)
at java.util.regex.Pattern.matcher(Pattern.java:297)
at com.google.firebase.database.core.utilities.Validation.isValidPathString(Validation.java:40)
at com.google.firebase.database.core.utilities.Validation.validatePathString(Validation.java:44)
at com.google.firebase.database.DataSnapshot.hasChild(DataSnapshot.java:80)
at com.example.android.adoptme.MainActivity$5.onChildAdded(MainActivity.java:186)
at com.google.firebase.database.core.ChildEventRegistration.fireEvent(ChildEventRegistration.java:79)
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:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Here is my code: (And yes I am aware that there is probably a better way to write it, I am still working on it and refining it with research).
package com.example.android.adoptme;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.FitWindowsViewGroup;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.lorentzos.flingswipe.SwipeFlingAdapterView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private Cards cards_data[];
private arrayAdapter arrayAdapter;
private int i;
private FirebaseAuth firebaseAuth;
private String currentUId;
private DatabaseReference petDb;
ListView listView;
List<Cards> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
petDb = FirebaseDatabase.getInstance().getReference().child("Users");
firebaseAuth = FirebaseAuth.getInstance();
checkAnimalType();
rowItems = new ArrayList<Cards>();
arrayAdapter = new arrayAdapter(this, R.layout.item, rowItems);
SwipeFlingAdapterView flingContainer = (SwipeFlingAdapterView) findViewById(R.id.frame);
flingContainer.setAdapter(arrayAdapter);
flingContainer.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
#Override
public void removeFirstObjectInAdapter() {
// this is the simplest way to delete an object from the Adapter (/AdapterView)
Log.d("LIST", "removed object!");
rowItems.remove(0);
arrayAdapter.notifyDataSetChanged();
}
#Override
public void onLeftCardExit(Object dataObject) {
Cards obj = (Cards) dataObject;
String userId = obj.getUserId();
petDb.child(userId).child(userId).child("connections").child("no").child(currentUId).setValue(true);
makeToast(MainActivity.this, "Left!");
}
#Override
public void onRightCardExit(Object dataObject) {
Cards obj = (Cards) dataObject;
String userId = obj.getUserId();
petDb.child(userId).child(userId).child("connections").child("yes").child(currentUId).setValue(true);
makeToast(MainActivity.this, "Right!");
}
#Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
}
#Override
public void onScroll(float scrollProgressPercent) {
}
});
// Optionally add an OnItemClickListener
flingContainer.setOnItemClickListener(new SwipeFlingAdapterView.OnItemClickListener() {
#Override
public void onItemClicked(int itemPosition, Object dataObject) {
makeToast(MainActivity.this, "Clicked!");
}
});
}
static void makeToast(Context ctx, String s){
Toast.makeText(ctx, s, Toast.LENGTH_SHORT).show();
}
private String animalOne, animalTwo;
public void checkAnimalType(){
final FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
DatabaseReference dogDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Dog");
dogDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded( DataSnapshot snapshot, String s) {
if (snapshot.getKey().equals(user.getUid())){
animalOne = "Dog";
animalTwo = "Cat";
getOtherAnimals();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
DatabaseReference catDb = FirebaseDatabase.getInstance().getReference().child("Users").child("Cat");
catDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.getKey().equals(user.getUid())){
animalOne = "Cat";
animalTwo = "Dog";
getOtherAnimals();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved( DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
public void getOtherAnimals(){
DatabaseReference otherAnimalDb = FirebaseDatabase.getInstance().getReference().child("Users").child(animalTwo);
otherAnimalDb.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot snapshot, String s) {
if (snapshot.exists() && !snapshot.child("connections").child("no").hasChild(currentUId) && !snapshot.child("connections").child("yes").hasChild(currentUId)){
Cards item = new Cards(snapshot.getKey(), snapshot.child("name").getValue().toString());
rowItems.add(item);
arrayAdapter.notifyDataSetChanged();
}
}
#Override
public void onChildChanged(DataSnapshot snapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot snapshot) {
}
#Override
public void onChildMoved(DataSnapshot snapshot, String s) {
}
#Override
public void onCancelled(DatabaseError error) {
}
});
}
public void logoutUser (View view){
firebaseAuth.signOut();
Intent intent = new Intent (MainActivity.this, LoginRegistration.class);
startActivity(intent);
}
}
I appreciate any help you can provide me. Thanks in advance.
I think the .hasChild(currentUId) might be causing issues here. You should verify once if it's pointing to correct node in the Firebase DB or not. I couldn't really comment so had to post an answer only.
By referring to the image below. If I want to make a module to list out all all the event info like registerEventName, registerEventLocation.... How should call into it? The second row is uuid of created event person id, follow by event id. Thanks in advance. I want display all the information of the event list created by all user.Please tell me if there was any extra information needed.
package com.example.jmham.eventuser;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.bumptech.glide.Glide;
import com.example.jmham.eventuser.Model.ListInfo;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.jmham.eventuser.ViewHolder.MenuViewHolder;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.mancj.materialsearchbar.MaterialSearchBar;
import com.example.jmham.eventuser.Model.User;
import java.util.ArrayList;
import java.util.List;
public class List_Of_Event extends AppCompatActivity {
FirebaseDatabase database;
DatabaseReference eventinfo;
RecyclerView recycle_menu;
RecyclerView.LayoutManager layoutManager;
FirebaseStorage storage;
StorageReference storageRef;
EditText search_edit_text;
FloatingActionButton search_item;
ArrayList<String> fullNameList;
ArrayList<String> profilePicList;
ArrayList<String> contectNumber;
ArrayList<String> EventId;
ArrayList<String> EventLocation;
ArrayList<String> EventName;
ArrayList<String> EventRadiogroup;
ArrayList<String> EventStartDate;
//Search functionality
FirebaseRecyclerAdapter<ListInfo,MenuViewHolder> searchAdapter;
List<String> suggestList = new ArrayList<>();
MaterialSearchBar materialSearchBar;
FirebaseRecyclerAdapter <ListInfo, MenuViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_event);
storage = FirebaseStorage.getInstance();
storageRef = storage.getReference();
//search_edit_text = (MaterialSearchBar) findViewById(R.id.search_edit_text);
search_edit_text = (EditText) findViewById(R.id.search_edit_text);
/*
* ArrayList<String> fullNameList;
ArrayList<String> profilePicList;
ArrayList<String> contectNumber;
ArrayList<String> EventId;
ArrayList<String> EventLocation;
ArrayList<String> EventName;
ArrayList<String> EventRadiogroup;
ArrayList<String> EventStartDate; * */
fullNameList = new ArrayList<>();
profilePicList = new ArrayList<>();
contectNumber = new ArrayList<>();
EventId = new ArrayList<>();
EventLocation = new ArrayList<>();
EventName = new ArrayList<>();
EventRadiogroup = new ArrayList<>();
EventStartDate = new ArrayList<>();
/*
search_item.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent search_bar = new Intent(List_Of_Event.this, search_bar.class);
startActivity(search_bar);
finish();
}
}); */
/*
search_edit_text.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
if (!s.toString().isEmpty()){
setAdapter(s.toString());
}
}
});
*/
recycle_menu = (RecyclerView) findViewById(R.id.recycle_menu);
recycle_menu.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recycle_menu.setLayoutManager(layoutManager);
database = FirebaseDatabase.getInstance();
// eventinfo = database.getReference("ListOfEvent");
System.out.println();
loadMenu();
eventinfo = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref2,ref3,ref4;
ref2 = eventinfo.child("ListOfEvent");
ref3 = ref2.child("ListOfEvent").child();
//DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ChatRoom").child(str);
ref2.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Result will be holded Here
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
EventName.add(String.valueOf(dsp.getValue())); //add result into array list
// Toast.makeText(List_Of_Event.this, EventName, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
//System.out.println(eventinfo.child("ListOfEvent").child(RegisterEventId).child("profileImageUr").toString());
//Search
materialSearchBar = (MaterialSearchBar)findViewById(R.id.searchBar);
materialSearchBar.setHint("Enter your Event");
//materialSearchBar.setSpeechMode(false); No need, becuz we already define it at XML
// loadSuggest(); //Write function to load Sugggest from Firebase
// setAdapter();
materialSearchBar.setLastSuggestions(suggestList);
materialSearchBar.addTextChangeListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// When user type theri text, we wil change list
List<String> suggest = new ArrayList<String>();
for (String search:suggest){
if(search.toLowerCase().contains(materialSearchBar.getText().toLowerCase()))
suggest.add(search);
}
materialSearchBar.setLastSuggestions(suggest);
}
#Override
public void afterTextChanged(Editable s) {
}
});
materialSearchBar.setOnSearchActionListener(new MaterialSearchBar.OnSearchActionListener() {
#Override
public void onSearchStateChanged(boolean enabled) {
//When Search Bar is close
//Restore original adapter
// if(! enabled) recycle_menu.setAdapter(adapter);
}
#Override
public void onSearchConfirmed(CharSequence text) {
// When search finish
//Show result of search adapter
// startSearch(text);
}
#Override
public void onButtonClicked(int buttonCode) {
}
});
// setAdapter(s.toString());
}
/*
private void startSearch(CharSequence text) {
searchAdapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(
ListInfo.class;
R.layout.activity_list_of_event,
MenuViewHolder.class,ListInfo.("registerEventName")
) {
#Override
protected void populateViewHolder(MenuViewHolder viewHolder, ListInfo model, int position) {
}
};
}
*/
/* private void loadSuggest(){
storageRef.orderByChild("registerEventName".equals()).addValueListener(new ValueEventListener()
{
}
);
} */
private void loadSuggest(){
eventinfo.child("ListInfo").addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot:dataSnapshot.getChildren())
{
ListInfo item = postSnapshot.getValue(ListInfo.class);
suggestList.add(item.getRegisterEventName()); // add name of food to suggest list
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
public void loadMenu(){
Query query = eventinfo.orderByKey();
FirebaseRecyclerOptions<ListInfo> firebaseRecyclerOptions =
new FirebaseRecyclerOptions.Builder<ListInfo>()
.setQuery(query, ListInfo.class)
.build();
adapter = new FirebaseRecyclerAdapter<ListInfo, MenuViewHolder>(firebaseRecyclerOptions) {
#NonNull
#Override
public MenuViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.activity_list,viewGroup,false);
return new MenuViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull MenuViewHolder holder, int position, #NonNull ListInfo model) {
System.out.println("test ::"+model.getImageToUpload());
holder.txtRegisterEventStartDate.setText(model.getRegisterEventStartDate());
holder.txtRegisterEventName.setText(model.getRegisterEventName());
holder.txtContact_number.setText(model.getRegisterContactNumber());
holder.txtRegisterEventRadiogroup.setText(model.getRegisterEventRadiogroup());
holder.txtRegisterEventLocation.setText(model.getRegisterEventLocation());
// model = storageReference.child("profileImageUrl").child(fileName)
System.out.println("test ::"+model.getImageToUpload());
Glide.with(getBaseContext()).load(model.getImageToUpload()
).into(holder.imageView);
System.out.println(model.getRegisterEventName());
System.out.println(model.getImageToUpload());
// String URL = FirebaseDatabase.getInstance().getReference().child(model.getRegisterEventId()).child("profileImageUrl");
// System.out.println("TESTURL: "+URL);
// Glide.with(getApplicationContext())
// .load(URL)
// .into(viewHolder.imageView);
System.out.println(model.getRegisterEventName());
System.out.println("Highlight" + model.getImageToUpload());
final ListInfo clickItem = model;
}
};
recycle_menu.setAdapter(adapter);
}
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
//---
}
//search_item
try this,
String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();
databaseRef.child("ListOfEvent").child(currentUser).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot objSnapshot: dataSnapshot.getChildren()) {
String key = objSnapshot.getKey();
Toast.makeText(Chat.this, key, Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Hope it's help full.
Hope this helps you.
databaseRef.child("ListOfEvent").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userIdSnapshot : dataSnapshot.getChildren()) {
for (DataSnapshot snapshot : userIdSnapshot.getChildren()) {
String regEventName = snapshot.child("registerEventName").getValue().toString();
String regEventLoc = snapshot.child("registerEventLocation").getValue().toString();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I i am working with firebase realtime database.. I retrieved data and everything but my main problem is that the data is not being displayed unless i press back button.. I went through stacks everywhere it suggested to notifyDataSetChanged(); which i did before, but still no luck. As i am using GridLayout i cant use the adapter in the addListeneOnDatachange function as it shows error saying that it is not allowed to add the adapter there for my RecyclerViewAdapter.
package my.unimas.a50200siswa.studentattendancemonitoringsystem;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
import java.util.List;
public class HomeActivity extends AppCompatActivity {
String userID;
List<CourseModel> listCourse;
TextView btnSignOut, UserName;
/*---- Firebase Database stuff ----*/
FirebaseAuth mAuth;
FirebaseUser user;
FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
#Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
/*-------Finding View---------*/
btnSignOut = (TextView) findViewById(R.id.btnsignout_home);
UserName = findViewById(R.id.username);
RecyclerView myrv = findViewById(R.id.recyclerviewcourse);
myrv.setLayoutManager(new GridLayoutManager(this,2));
// CourseCode();
btnSignOut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAuth.signOut();
}
});
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() == null) {
startActivity(new Intent(HomeActivity.this, SignInActivity.class));
}
}
};
/* ----------------- Firebase Elements -----------------*/
mAuth = FirebaseAuth.getInstance();
user = mAuth.getCurrentUser();
userID = user.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
myRef = rootRef.child("Users");
/*------------------------------------------------------------------*/
listCourse = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w("Hello", "Failed to read value.", error.toException());
}
});
RecyclerViewAdapterCourse myAdapter = new RecyclerViewAdapterCourse(this,listCourse);
myAdapter.notifyDataSetChanged();
myrv.setAdapter(myAdapter);
}
}
You need to call myAdapter.notifyDataSetChanged() every time the data changes. In your case this means you need to call it at the end of the onDataChanged(DataSnapShot dataSnapShot) function.
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userName = dataSnapshot.child(userID).child("userName").getValue(String.class);
UserName.setText(userName);
String coursecode[] = new String[10];
String coursename[] = new String[10];
listCourse.clear();
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
myAdapter.notifyDataSetChanged()
}
I have an app that asks a series of questions. These questions are stored on the firebase db. I am trying to change the child node "Status" from the click of the button. The button being pressed for testing is button "AnswerA".
To date i have managed to change all "Status" nodes to the button press but i only want to change one at a time as the questions are being asked.
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
You are looping though all questions and performing the same logic on all of them. You want to select only the question you are interested in, e.g.:
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals()) { // TODO: How you chose the child from your index
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
Adding full playing activity for review,
import android.content.Intent;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.hiverecord.kee01.hiverecord.Common.Common;;
import com.hiverecord.kee01.hiverecord.Model.Question;
import com.hiverecord.kee01.hiverecord.Model.QuestionList;
import com.hiverecord.kee01.hiverecord.Model.User;
import com.squareup.picasso.Picasso;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
public class Playing extends AppCompatActivity implements View.OnClickListener {
final static long INTERVAL = 5000; //5sec
final static long TIMEOUT = 60000; //70 sec
int progressValue = 0;
CountDownTimer mCountDown;
int index=0,
thisQuestion=0,
totalQuestion,
correctAnswer;
ProgressBar progressBar;
ImageView question_image;
Button btnA,btnB;
TextView txtQuestionNum,question_text;
FirebaseDatabase database;
DatabaseReference test;
private int i = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playing);
database = FirebaseDatabase.getInstance();
test = database.getReference("Questions"); //get the reference
//Views
txtQuestionNum = findViewById(R.id.txtTotalQuestion);
question_text = findViewById(R.id.question_text);
question_image = findViewById(R.id.question_image);
progressBar = findViewById(R.id.progressBar);
btnA = findViewById(R.id.btnAnswerA);
btnB = findViewById(R.id.btnAnswerB);
btnA.setOnClickListener(this);
btnB.setOnClickListener(this);
}
#Override
public void onClick(View view) {
mCountDown.cancel();
if (index < totalQuestion)
{
Button clickedButton = (Button) view;
if (clickedButton.getText().equals(Common.questionList.get(index).getCorrectAnswer())) {
final FirebaseDatabase database = FirebaseDatabase.getInstance();
//db reference
final DatabaseReference ref = database.getReference("Questions");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals(Common.questionList.get(index).getKey())){
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
correctAnswer++;
showQuestion(++index); //next question
}
});
}
else {
Map<String, Object> userUpdates = new HashMap<>();
//userUpdates.put("AnswerA", "");
//userUpdates.put("AnswerB", "NO");
test.updateChildren(userUpdates);
//choose answer false
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
showQuestion(++index);
}
}
}
private void showQuestion(int index) {
if(index < totalQuestion)
{
thisQuestion++;
txtQuestionNum.setText(String.format("%d/%d",thisQuestion, totalQuestion));
progressBar.setProgress(0);
progressValue=0;
if(Common.questionList.get(index).getIsImageQuestion().equals("true"))
{
//if is image
Picasso.with(getBaseContext())
.load(Common.questionList.get(index).getQuestion())
.into(question_image);
question_image.setVisibility(View.VISIBLE);
question_text.setVisibility(View.VISIBLE);
}
else
{
question_text.setText(Common.questionList.get(index).getQuestion());
//If question is text, we will set image to invisible
question_image.setVisibility(View.INVISIBLE);
question_text.setVisibility(View.VISIBLE);
}
btnA.setText(Common.questionList.get(index).getAnswerA());
btnB.setText(Common.questionList.get(index).getAnswerB());
mCountDown.start(); //Start timer
}
else
{
//if it is a final question
Intent intent = new Intent(this,Done.class);
Bundle dataSend = new Bundle();
//dataSend.putInt("SCORE", score);
dataSend.putInt("TOTAL", totalQuestion);
dataSend.putInt("CORRECT", correctAnswer);
intent.putExtras(dataSend);
startActivity(intent);
finish();
}
}
#Override
protected void onResume() {
super.onResume();
totalQuestion = Common.questionList.size();
mCountDown = new CountDownTimer(TIMEOUT,INTERVAL) {
#Override
public void onTick(long minisec) {
progressBar.setProgress(progressValue);
progressValue++;
}
#Override
public void onFinish() {
mCountDown.cancel();
showQuestion(++index);
}
};
showQuestion(index);
}
}
Solution:
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//logcat and show the index
Log.i("Button A Index accessed", index + "");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Get DataSnapShot of Children in ref Questions
for (DataSnapshot questionCode : dataSnapshot.getChildren()) {
String questionCodeKey = questionCode.getKey();
if (questionCodeKey.equals("0" + index)) {
//Retrieve value at child node AnswerA
String correctAnswerString = questionCode.child("AnswerA").getValue(String.class);
//Take value of AnswerA and place it in new node "Status"
ref.child(questionCodeKey).child("Status").setValue(correctAnswerString);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
How to set value (name) in EditText?
"users": [
"-KTYWvZG4Qn9ZYTc47O6" : {
"name" : "my name"
}
}
I did it but
package **.****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.EditText;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import ****.****.m_Model.Update_user1;
public class Update_a extends AppCompatActivity {
private EditText name111;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Update__activity);
myname111 = (EditText) findViewById(R.id.editext2);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("users");
String userId = mFirebaseDatabase.push().getKey();
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Update_user1.class
package **.****.m_Model;
public class Update_user1 {
public String name;
public Update_user1() {
}
public Update_user1(String name) {
this.name = name;
}
public String getname() {
return name;
}
But this not work
E/AndroidRuntime: FATAL EXCEPTION: main Process: *.******, PID:
14980 java.lang.NullPointerException: Attempt to invoke virtual
method java.lang.String ..m_Model.Update_user1.getname() on a
null object reference
at *.********.Update_u$1.onDataChange(Update_u.java:61)
When you run this line:
String userId = mFirebaseDatabase.push().getKey();
You generate a new so-called push ID. Next you attach a listener to a location based on this freshly created push ID.
mFirebaseDatabase.child(userId).addValueEventListener(new ValueEventListener() {
...
Since push IDs are statistically guaranteed to be unique, no value will exist at this location yet.
This means that onDataChange() will fire with an empty DataSnapshot:
public void onDataChange(DataSnapshot dataSnapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
Since the DataSnapshot is empty, getValue() will not be able to get a Update_user1 and thus it will return null. And that leads to model.getname() calling getname() on a null object and thus throwing a NullPointerException.
The simplest way to handle the null is:
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
}
the answer of frank is right as you really want to get the value of id doesn't exist yet and you must make the listener on the key that have the values so you don't have to know the hashkey of it
so you can make as follow
mFirebaseDatabase.getReference("users")
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Update_user1 model = dataSnapshot.getValue(Update_user1.class);
myname111.setText(model.getname());
}
#Override
public void onCancelled(DatabaseError databaseError) {
// TODO
}
});