In array it is storing NULL instead of PDF file name - java

public class cp extends AppCompatActivity {
ListView ListPdf;
DatabaseReference databaseReference;
List<upload> uploadPdf;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cp);
ListPdf = (ListView) findViewById(R.id.List);
uploadPdf = new ArrayList<>();
ViewAllPdf();
}
private void ViewAllPdf() {
databaseReference = FirebaseDatabase.getInstance().getReference("year_1");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot PostSnapShot: dataSnapshot.getChildren()){
upload Pdf = PostSnapShot.getValue(upload.class);
uploadPdf.add(Pdf);
}
String[] uploads = new String[uploadPdf.size()];
for(int i=0;i<uploads.length;i++){
uploads[i] = uploadPdf.get(i).getName();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,uploads);
ListPdf.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
upload class
public class upload {
public String name;
public upload() {
this.name = name;
}
public String getName() {
return name;
}
}
In uploads[ ] it is storing null instead of file name,i cannot figure out what's the problem. I tried logcat for debuging but it shows Pdf object has three files but in uploads[ ] it stores NULL. Please look into it
Firebase database screenshot

The problem with your code is your POJO class Upload. See an example from Firebase Documentation
public class User {
public String username;
public String email;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(User.class)
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
}
Also the fields name in your Realtime Database doesn't match with your POJO class.

Related

Null Pointer when trying to retrieve user details from Firebase Realtime Database

In my Android app, I have a database repository to contact Firebase Realtime Database and a service layer with some methods. My SaveUserProfile method works but I keep getting a null pointer on my GetUserFromUid.
The 'user' object it returns is null and I don't know why. The node in my DB is called "users" (all lowercase) and I want to retrieve a user as a model via their userId and display the name and email onscreen.
Can anybody see where I'm going wrong?
My DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context){
super();
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public User GetUserFromFirebase(String uid) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
return user;
}
My DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
private DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
User user = dbContext.GetUserFromFirebase(uid);
return user;
}
My User model:
public class User {
public String userId;
public String name;
public String email;
public String account;
//constructor required for calls to DataSnapshot.getValue(User.class)
public User(){
}
public User(String userId, String name, String email, String account) {
this.userId = userId;
this.name = name;
this.email = email;
this.account = account;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAccount() {
return account;
}
public void setAccount(String account) {
this.account = account;
}
My activity where I want to display the users' details:
public class DetailsActivity extends AppCompatActivity {
//tag
private static final String TAG = DetailsActivity.class.getSimpleName();
//firebase auth
private FirebaseAuth mAuth;
//variables
private TextView inputName, inputEmail;
private DatabaseReference mFirebaseDatabase;
private String userId;
public String currentUserAccount;
public String teacherAccountNav = "Teacher";
public User userDetails;
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserDetails(userId);
inputName.setText(userDetails.name);
inputEmail.setText(userDetails.email);
}
public User getUserDetails(String uid){
DbService dbService = new DbService(this);
userDetails = dbService.GetUserFromUid(uid);
return userDetails;
}
EDITS BELOW
My callback:
public interface Callback {
void myResponseCallback(User user);
}
My EDITED DbContext:
public class DbContext implements IDbContext {
User user = null;
Context context;
DatabaseReference databaseUsers = FirebaseDatabase.getInstance().getReference("users");
public DbContext(Context context) {
this.context = context;
}
#Override
public void AddUserAccount(User user1) {
databaseUsers.child(user1.userId).setValue(user1);
}
#Override
public void GetUserFromFirebase(String uid, final Callback callback) {
databaseUsers.child(uid)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
user = dataSnapshot.getValue(User.class);
callback.myResponseCallback(user);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
My EDITED DbService:
public class DbService implements IDbService {
//instance of DbContext for firebase handling
public DbContext dbContext;
public DbService(Context context){
super();
dbContext = new DbContext(context);
}
#Override
public User SaveUserProfile(User u) {
dbContext.AddUserAccount(u);
return u;
}
#Override
public User GetUserFromUid(String uid) {
final User[] user1 = {new User()};
dbContext.GetUserFromFirebase(uid, new Callback() {
#Override
public void myResponseCallback(User user) {
user1[0] = user;
}
});
return user1[0];
}
My EDITED Activity:
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
inputName = findViewById(R.id.nameTextView);
inputEmail = findViewById(R.id.emailTextView);
FirebaseDatabase mFirebaseInstance = FirebaseDatabase.getInstance();
//reference to 'users' node
mFirebaseDatabase = mFirebaseInstance.getReference("users");
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
assert user != null;
userId = user.getUid();
getUserFromFirebase(userId);
}
public void getUserFromFirebase(String uid){
userDetails = (new DbService(this)).GetUserFromUid(uid);
inputEmail.setText(userDetails.email);
inputName.setText(userDetails.name);
}
Debug BEFORE edits:
Debug AFTER edits:
As you can see from the debug, before the callback interface, userDetails was null. After the interface implementation, userDetails is not null but all of the object values are null. I don't know why this is as they are filled in the database. Any ideas?

when I manually change value in firebase database I create more items in listview instead of updating value in listview

I have No idea what's going wrong in my code Please Help Me.
Just Trying To Retrieve data to list view.
My MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView listView;
FirebaseDatabase database;
DatabaseReference ref;
ArrayList<String> list;
ArrayAdapter <String> adapter;
User user;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
user = new User();
listView = findViewById(R.id.listView);
database = FirebaseDatabase.getInstance();
ref = database.getReference("match1contest1");
list = new ArrayList<>();
adapter = new ArrayAdapter<String>(this,R.layout.user_info,R.id.userInfo, list);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()){
user = ds.getValue(User.class);
list.add(user.getName().toString()+user.getEmail().toString());
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
My User.java
public class User {
private String name;
private String email;
private String phone;
private String userName;
private String password;
public User() {
}
public User(String name, String email, String phone, String userName, String password) {
this.name = name;
this.email = email;
this.phone = phone;
this.userName = userName;
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
Below Are Images
I Just Want To Update the Value
I don't know why it creates more items
I have only 3 children in firebase
I am Just retrieving data, the data is saved manually from firebase console
Please Help Me...
When you update a value in your database, it will trigger your
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {...
Again, and that will fetch for all childrens (included the updated one) and will be placed inside the list again this will duplicate the items since inside your onDataChange you have a for loop that will loop throught all the childrens again and will add them again to the current populated list.
What you need to do, is to clear the list when is fetched again
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
list.clear();
for (DataSnapshot ds: dataSnapshot.getChildren()){
user = ds.getValue(User.class);
list.add(user.getName().toString()+user.getEmail().toString());
}
listView.setAdapter(adapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Another way you can do it is to use updateChildren() with a map, this will just update the item you are updating in your database

Firebase Database unable to retrieve value

I am unable to change the text of multiple TextView to the values retrieved from Firebase Realtime Database.
My database looks like: Database
My current code is:
public class SearchResult extends AppCompatActivity {
TextView searchResultHSPName,searchResultHSPStatus, searchResultHSPType,searchResultHSPRating;
Button messageButton;
private static final String TAG = "SearchResult";
DatabaseReference rootReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result);
searchResultHSPName = (TextView) findViewById(R.id.hspNameSearchResultTextView);
searchResultHSPType = (TextView) findViewById(R.id.hspTypeSearchResultTextView);
searchResultHSPRating = (TextView) findViewById(R.id.hspRatingSearchResultTextView);
searchResultHSPStatus = (TextView) findViewById(R.id.hspStatusSearchResultTextView);
//take the searched name from searchFunction and query db for the user details
Intent intent = getIntent();
final String searchedHSPName = intent.getExtras().getString("SearchFunctionMessage");
rootReference = FirebaseDatabase.getInstance().getReference();
DatabaseReference userReference = rootReference.child("HSPUsers");
userReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
HSPUsers user = snapshot.getValue(HSPUsers.class);
String userName = user.HSPName;
if(userName == searchedHSPName){
searchResultHSPName.setText(userName);
searchResultHSPStatus.setText(user.HSPStatus);
searchResultHSPRating.setText(user.HSPRating);
searchResultHSPType.setText(user.HSPType);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
And my HSPUsers class is:
public class HSPUsers {
//HSP user contains 4 fields of data UserName, Status,Type,Rating
public String HSPName,HSPStatus, HSPType,HSPRating;
//constructor for datasnapshot
public HSPUsers(){
}
public HSPUsers(String username, String status, String type, String rating){
this.HSPName=username;
this.HSPStatus=status;
this.HSPType=type;
this.HSPRating=rating;
}
//get and set methods
public String getHSPUserName() {
return HSPName;
}
public void setHSPUserName(String HSPUserName) {
this.HSPName = HSPUserName;
}
public String getHSPUserStatus() {
return HSPStatus;
}
public void setHSPUserStatus(String HSPUserStatus) {
this.HSPStatus = HSPUserStatus;
}
public String getHSPUserType() {
return HSPType;
}
public void setHSPUserType(String HSPUserType) {
this.HSPType = HSPUserType;
}
public String getHSPUserRating() {
return HSPRating;
}
}
public String getHSPUserRating() {
return HSPRating;
}
}
Ideally, i would like to change the textViews to the user's Name/Status/Rating/Type. However, there has been no change to the textviews and i am left with UnchangedTextViews
Would appreciate any advice on how to change the TextViews to the HSPName/rating/Status/type?
Thank you in advance for any advice.

Android Firebase get all user Info problem

I would like to list the users who registered to the system.
MainPage:
List<User> users;
databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
{
User user = postSnapShot.getValue(User.class);
users.add(user);
customAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("selam", "onCancelled: " + databaseError );
}
});
User Java Class
public class User {
private String email ="";
private String nickname="";
private String status="";
private String uid="";
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUid() {
return uid;
}
public void setUid(String uid) {
this.uid = uid;
}
İmages
You get that NullPointerException because you haven't initialized your users list. To solve this, please use the following code:
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
List<User> users = new ArrayList<>(); //Initialize the list
for(DataSnapshot postSnapShot : dataSnapshot.getChildren())
{
User user = postSnapShot.child("userInfo").getValue(User.class);
users.add(user);
}
customAdapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("selam", "onCancelled: " + databaseError );
}
});
Please also note, that I moved customAdapter.notifyDataSetChanged();, outside the for loop and I have also added .child("userInfo") call because there is an extra level in your database tree.

Android - Firebase database child node

I have a Firebase databse structure like this :
the firebase database structure
Now I want to access the items in the node "comingSoonPages" to a model class. How can i get the reference to these different user specified items in that node?
The database reference :
mUpcomingDatabaseReference = mFirebaseDatabase.getReference().child("comingSoonPages").child("blrKoramangala")
now the listener to the reference is as :
mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
Log.e("snap" , String.valueOf(snapShot));
try{
UpcomingProperty property = snapShot.getValue(UpcomingProperty.class);
Log.e("name" , String.valueOf(property.getName()));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUpcomingDatabaseReference.addValueEventListener(mValueEventListener);
when i try to log the names in each of the nodes , i get NPE and the value is null.
The model class in which i am mapping is :
public class UpcomingProperty implements Serializable {
//private Amenities amenities;
private List<String> amenities;
private Coordinates coordinates;
private Image image;
private String link;
private String location;
private String name;
private Text text;
private List<String> sortParameter;
private EarlyBird earlyBird;
public UpcomingProperty(){}
public List<String> getAmenities() {
return amenities;
}
public void setAmenities(List<String> amenities) {
this.amenities = amenities;
}
public Coordinates getCoordinates() {
return coordinates;
}
public void setCoordinates(Coordinates coordinates) {
this.coordinates = coordinates;
}
public Image getImage() {
return image;
}
public void setImage(Image image) {
this.image = image;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Text getText() {
return text;
}
public void setText(Text text) {
this.text = text;
}
public List<String> getSortParameter() {
return sortParameter;
}
public void setSortParameter(List<String> sortParameter) {
this.sortParameter = sortParameter;
}
public EarlyBird getEarlyBird() {
return earlyBird;
}
public void setEarlyBird(EarlyBird earlyBird) {
this.earlyBird = earlyBird;
}
}
Thanks.
the extended firebase node :
extended node values
To get that data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
The out will be the only the names. But you can get also all the other values in the same way.
If you want to use the model class, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference comingSoonPagesRef = rootRef.child("comingSoonPages");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
UpcomingProperty upcomingProperty = ds.getValue(UpcomingProperty.class);
Log.d("TAG", upcomingProperty.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
comingSoonPagesRef.addListenerForSingleValueEvent(eventListener);
You'll have the same output.
Assuming that comingSoonPages holds a list of item, You need to add a ChildEventListener on the comingSoonPages reference if you want to access all the child nodes of that.
DatabaseReference upcomingItemsRef = mFirebaseDatabase.getReference().child("comingSoonPages");
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) {
if(dataSnapshot.exists()) {
// Handle each individual node like blrKoramangala, cyberHub here.
String key = dataSnapshot.getKey();
// Get the UpcomingProperty object here.
UpcomingProperty property = dataSnapshot.getValue(UpcomingProperty.class);
Log.d(TAG, "property.getName():" + property.getName();
}
}
// Other methods of ChildEventListener go here
};
upcomingItemsRef.addChildEventListener(childEventListener);
You can read more about working with lists of data here.
However, if that's not a list, here's what you're doing wrong:
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// Don't do this. It will get the children of blrKoramangala and
// those won't be of UpcomingProperty type.
// Remove and replace with dataSnapshot.exists()
for (DataSnapshot snapShot : dataSnapshot.getChildren()){
...
}
}

Categories

Resources