Firebase Realtime Database error while getting values - android

I am making a chat app using Firebase. I have created a class called Chat Activity where the user can send or receive messages. Along with this, I am creating Notifications. For the initial stage, I am building the notification as soon as the ChatActivity is being created.
The content of the body is the last message that was sent. But when I sent the title of the notification to the name of the user, it does not display the title. I am obtaining the name of the user using a new function called "getNameFromRoll()". But this also returns null.
When a user signs up in the app, not only it is registered in the firebase users list, but also in a child in the database called "students" in an inner child called "profiles". getNameFromRoll() reads data from this child.
Here's the code:
ChatActivity:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.NotificationCompat;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.ForwardingListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
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 java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
/**
* Created by shubham on 03/02/17.
*/
public class ChatActivity extends AppCompatActivity {
public String chatName;
public String chatRoll;
public String messageText;
public String time;
public String name;
public String senderRoll;
public String mId;
public List<Messages> mMessages;
public List<Chats> mChats;
public RecyclerView mMessagesListView;
public MessageAdapter mMessageAdapter;
public EditText mMessageEditText;
public FloatingActionButton mSendFAB;
public FirebaseDatabase mDatabase;
public DatabaseReference mSenderDatabaseReference;
public DatabaseReference mRecieverDatabaseReference;
public DatabaseReference mRecieverChatsDatabaseReference;
public DatabaseReference mUsersDatabaseReference;
public ChildEventListener mChildEventListener;
public ChildEventListener mChatsChildEventListener;
public ChildEventListener mUserChildEventListener;
public Intent mServiceIntent;
public String IS_NAME_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_NAMEKEY";
public String IS_MESSAGE_KEY = "com.app.shubhamjhunjhunwala.heritagecompanion_students.IS_MESSAGEKEY";
public ChatActivity() {
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
final Intent intent = getIntent();
Bundle extras = intent.getExtras();
chatName = intent.getStringExtra(ChatsActivity.EXTRA_NAME);
chatRoll = intent.getStringExtra(ChatsActivity.EXTRA_ROLL);
setTitle(chatName);
SharedPreferences sharedPreferences = getSharedPreferences("HCS", 0);
senderRoll = sharedPreferences.getString(AuthenticationActivity.ROLL_SHARED_PREFERENCE_KEY, "");
mDatabase = FirebaseDatabase.getInstance();
mSenderDatabaseReference = mDatabase.getReference().child("chats").child(senderRoll).child("messages").child(chatRoll);
mRecieverDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll).child("messages").child(senderRoll);
mRecieverChatsDatabaseReference = mDatabase.getReference().child("chats").child(chatRoll);
mUsersDatabaseReference = mDatabase.getReference().child("students").child("profiles");
mMessageEditText = (EditText) findViewById(R.id.message_edit_text);
mSendFAB = (FloatingActionButton) findViewById(R.id.send_fab);
mMessages = new ArrayList<>();
mChats = new ArrayList<>();
mMessagesListView = (RecyclerView) findViewById(R.id.messages_list_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
mMessagesListView.setLayoutManager(layoutManager);
mMessageAdapter = new MessageAdapter(mMessages, senderRoll, chatRoll);
mMessagesListView.setAdapter(mMessageAdapter);
mSendFAB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
messageText = mMessageEditText.getText().toString().trim();
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
time = df.format(c.getTime());
if (messageText != "") {
Messages message = new Messages(messageText, time, senderRoll, chatRoll, mId);
mSenderDatabaseReference.push().setValue(message);
mRecieverDatabaseReference.push().setValue(message);
}
mMessageEditText.setText("");
}
});
message();
}
public void message() {
mChildEventListener = new ChildEventListener() {
int n;
Chats chat;
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Messages messages = dataSnapshot.getValue(Messages.class);
mMessages.add(messages);
mMessagesListView.scrollToPosition(mMessages.size() - 1);
mMessageAdapter.notifyItemInserted(mMessages.size() - 1);
notificationBuilder(ChatActivity.this, messages.getSender(), messages.getMessage());
n = setNewChatHeader();
if (n == 1) {
chat = new Chats(chatName, chatRoll);
mRecieverChatsDatabaseReference.setValue(chat);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mSenderDatabaseReference.addChildEventListener(mChildEventListener);
}
public int setNewChatHeader() {
mChatsChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
if (dataSnapshot != null && dataSnapshot.getValue() != null) {
Chats chats = dataSnapshot.getValue(Chats.class);
if (chats.getName() != null) {
mChats.add(chats);
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mRecieverChatsDatabaseReference.addChildEventListener(mChatsChildEventListener);
if (mChats.size() != 0) {
for (int i = 0; i < mChats.size(); i++) {
Chats chat = mChats.get(i);
String name = chat.getName();
if (name.equals(chatName)) {
return 1;
}
}
}
return 0;
}
public String getSenderRoll() {
return senderRoll;
}
public void notificationBuilder(Context context, String name, String message) {
getNameFromRollNumber(name);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setColor(getResources().getColor(R.color.colorPrimary))
.setSmallIcon(R.drawable.ic_message_notification_icon)
.setLargeIcon(largeIcon(context))
.setContentTitle(this.name)
.setContentText(message)
.setStyle(new NotificationCompat.BigTextStyle().bigText(message))
.setDefaults(Notification.DEFAULT_VIBRATE)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
mBuilder.setPriority(Notification.PRIORITY_HIGH);
}
Intent resultIntent = new Intent(this, ChatActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
this,
0,
resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
int mNotificationId = 001;
NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public Bitmap largeIcon(Context context) {
Resources res = context.getResources();
Bitmap largeIcon = BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);
return largeIcon;
}
public void getNameFromRollNumber (String roll) {
mUsersDatabaseReference = mUsersDatabaseReference.child(roll);
mUserChildEventListener = new ChildEventListener() {
ChatActivity chatActivity = new ChatActivity();
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserDetails userDetails = dataSnapshot.getValue(UserDetails.class);
chatActivity.setName(userDetails.getName());
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
mUsersDatabaseReference.addChildEventListener(mUserChildEventListener);
Toast.makeText(ChatActivity.this, name, Toast.LENGTH_SHORT).show();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
UserDetails.class:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by shubham on 23/01/17.
*/
public class UserDetails {
UserDetails() {}
public String name;
public String email;
public String password;
public String phone;
public String roll;
public String sharingKey;
public String department;
public String year;
public String section;
public UserDetails(String name, String email, String password, String phone, String roll, String sharingKey, String department, String year, String section) {
this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
this.roll = roll;
this.sharingKey = sharingKey;
this.department = department;
this.year = year;
this.section = section;
}
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getSharingKey() {
return sharingKey;
}
public void setSharingKey(String sharingKey) {
this.sharingKey = sharingKey;
}
}
The sample of the database Structure:
heritage-companion-students
chats
students
-Kcgc88CAieCWCWPvA8D
-KcgcNrZj2Saueyaejw5
-Kcgce-x43DaaYiHjTpK
-Kcgcqh1uJ8E_KgKDcq0
-Kcgd36xoBcdsJriqMjS
-KcgdHY9CxaoCQ9poEna
profiles
1657099
1657102
1657103
1657108
-Kcgc87aRCL_D1KXJypP
department:
email:
name:
password:
phone:
roll:
sharingKey:
1657113
1657120

Related

My object class doesn't want to be passed with Intent.putExtra/Intent.getExtra

I have a object class that I want to use it between activities.
I used exactly the same method for another activities and worked perfectly fine. But here I can't figure it out what I am doing wrong. This is the object class :
`package com.mecachrome.ffbf;
import android.os.Parcel;
import android.os.Parcelable;
public class topic implements Parcelable {
public static Creator<topic> getCREATOR() {
return CREATOR;
}
public static final Creator<topic> CREATOR = new Creator<topic>() {
#Override
public topic createFromParcel(Parcel in) {
return new topic(in);
}
#Override
public topic [] newArray(int size) {
return new topic[size];
}
};
private String name;
private String comment;
private String id;
private String username;
public topic() {
}
public topic(String name, String comment, String id, String username) {
this.name = name;
this.comment = comment;
this.id = id;
this.username = username;
}
protected topic(Parcel in) {
name = in.readString();
comment = in.readString();
id = in.readString();
username = in.readString();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getComment() {
return comment;
}
public void setComment(String comment) {
this.comment = comment;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Override
public String toString() {
return "topic{" +
"name='" + name + '\'' +
", comment='" + comment + '\'' +
", id='" + id + '\'' +
", username='" + username + '\'' +
'}';
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(comment);
dest.writeString(id);
dest.writeString(username);
}
}`
This is the class that I want to take the object from:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;
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;
public class forum extends AppCompatActivity {
RecyclerView rv_forum;
forumAdapter myadapter;
Button add_topic;
Button test;
DatabaseReference databaseref;
private ArrayList<topic> topicList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_forum);
add_topic = findViewById(R.id.btn_new_topic);
rv_forum = findViewById(R.id.rv_topics);
rv_forum.setHasFixedSize(true);
rv_forum.setLayoutManager(new LinearLayoutManager(this));
test = findViewById(R.id.test_btn);
topicList = new ArrayList<>();
databaseref = FirebaseDatabase.getInstance().getReference("forum_topics");
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
topic top = dss.getValue(topic.class);
topicList.add(top);
}
myadapter = new forumAdapter(forum.this, topicList, mTopic -> {
Intent intent = new Intent(forum.this, topic_chat.class);
intent.putExtra("topic",mTopic);
startActivity(intent);
});
rv_forum.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(forum.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
add_topic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(forum.this, add_new_topic.class);
startActivity(i);
}
});
}
}`
And this is the class that I want to transfer the object to:
`package com.mecachrome.ffbf;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
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.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
public class topic_chat extends AppCompatActivity {
RecyclerView rv_chat;
chatAdapter myadapter;
Button send;
TextView topic_name;
TextView chat_text;
String chat;
private topic mTopic;
private ArrayList<chat> chatList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic_chat);
mTopic = getIntent().getParcelableExtra("topic");
send = findViewById(R.id.btn_send_chat);
rv_chat = findViewById(R.id.rv_topics);
rv_chat.setHasFixedSize(true);
rv_chat.setLayoutManager(new LinearLayoutManager(this));
topic_name = findViewById(R.id.tv_topic_name);
chat_text = findViewById(R.id.et_comment);
chat = chat_text.getText().toString().trim();
chatList = new ArrayList<>();
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
topic_name.setText(mTopic.getName());
Calendar calendar = Calendar.getInstance();
String currentDate = DateFormat.getDateInstance(DateFormat.SHORT).format(calendar.getTime());
chatList = new ArrayList<>();
databaseref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dss: snapshot.getChildren()){
chat mess = dss.getValue(chat.class);
chatList.add(mess);
}
myadapter = new chatAdapter(topic_chat.this, chatList, chat -> {
Intent intent = new Intent(topic_chat.this, topic_chat.class);
startActivity(intent);
});
rv_chat.setAdapter(myadapter);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
Toast.makeText(topic_chat.this, error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
send.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chat msg = new chat(mTopic.getName(),chat,mTopic.getId(),currentDate);
databaseref.setValue(msg).addOnCompleteListener(task1 -> {
if (task1.isSuccessful()){
Toast.makeText(topic_chat.this, "Review was been added Successfully", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(topic_chat.this, "Review failed to post. Try Again!", Toast.LENGTH_SHORT).show();
}
});;
}
});
}
}`
The object class is "topic"
The error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.mecachrome.ffbf.topic.getId()' on a null object reference
On this line
DatabaseReference databaseref = FirebaseDatabase.getInstance().getReference("forum_topics").child(mTopic.getId()).child("chat");
because mTopic.getId() is null. Any help?

Data of previous user is not removed on my Textviews even if I login a new user

Previously, i login a user and display its personal information in Textviews and it works fine for the first time, but when i sign-out and entered another user, the information of the previous user is still shown in the textview which supposedly his own personal data. I tried to login with a third user and still display the information of the first user. Here are my codes.. Your help is highly appreciated.
Userinformation.java
public class Userinformation {
private String establishmentname;
private String address;
private String contact;
private String availability;
private String price;
private String type;
private String condition;
private String ownername;
public Userinformation(){
}
public Userinformation (String establishmentname ,String address,String contact, String availability, String price, String type, String condition, String ownername){
this.establishmentname=establishmentname;
this.address=address;
this.contact=contact;
this.availability=availability;
this.price=price;
this.type=type;
this.condition=condition;
this.ownername=ownername;
}
public String getEstablishmentname() {
return establishmentname;
}
public void setEstablishmentname(String establishmentname) {
this.establishmentname = establishmentname;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getContact() {
return contact;
}
public void setContact(String contact) {
this.contact = contact;
}
public String getAvailability() {
return availability;
}
public void setAvailability(String availability) {
this.availability = availability;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOwnername() {
return ownername;
}
public void setOwnername(String ownername) {
this.ownername = ownername;
}
}
Profile.java
package *****************;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
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;
public class Profile extends AppCompatActivity implements View.OnClickListener {
ImageView userprofile;
TextView establishmentdisplay;
TextView addressdisplay;
TextView contactdisplay;
TextView availabilitydisplay;
TextView pricedisplay;
TextView typedisplay;
TextView conditiondisplay;
TextView ownernamedisplay;
Button btnsave;
private FirebaseAuth mAuth;
private FirebaseDatabase mFirebaseDatabase;
private FirebaseAuth.AuthStateListener mAuthListener;
DatabaseReference myRef;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
userprofile=(ImageView) findViewById(R.id.userprofile);
btnsave = (Button) findViewById(R.id.savechangesbtn);
establishmentdisplay = (TextView) findViewById(R.id.establishmentdisplay);
addressdisplay = (TextView) findViewById(R.id.addressdisplay);
contactdisplay = (TextView) findViewById(R.id.contactdisplay);
availabilitydisplay = (TextView) findViewById(R.id.availabilitydisplay);
pricedisplay = (TextView) findViewById(R.id.pricedisplay);
typedisplay = (TextView) findViewById(R.id.typedisplay);
conditiondisplay = (TextView) findViewById(R.id.conditiondisplay);
ownernamedisplay = (TextView) findViewById(R.id.ownernamedisplay);
btnsave.setOnClickListener(this);
mAuth = FirebaseAuth.getInstance();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference user = database.getReference("HomeownerUsers");
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()){
String establishmentname=ds.child("Establishment Name").getValue().toString();
String address=ds.child("Address").getValue().toString();
String contact=ds.child("Contact").getValue().toString();
String availability=ds.child("Availablility").getValue().toString();
String price=ds.child("Price").getValue().toString();
String type=ds.child("Type").getValue().toString();
String condition=ds.child("Conditions").getValue().toString();
String ownername=ds.child("Owner Name").getValue().toString();
establishmentdisplay.setText(establishmentname);
addressdisplay.setText(address);
contactdisplay.setText(contact);
availabilitydisplay.setText(availability);
pricedisplay.setText(price);
typedisplay.setText(type);
conditiondisplay.setText(condition);
ownernamedisplay.setText(ownername);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
protected void onStart() {
super.onStart();
if(mAuth.getCurrentUser() == null){
finish();
startActivity(new Intent(this,Homeownerlogin.class));
}
}
#Override
protected void onStop() {
super.onStop();
if(mAuthListener !=null){
mAuth.removeAuthStateListener(mAuthListener);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.menulogout:
FirebaseAuth.getInstance().signOut();
finish();
startActivity(new Intent(this, Homeownerlogin.class));
Toast.makeText(Profile.this,"Log out Successfully",Toast.LENGTH_SHORT).show();
}
return true;
}
#Override
public void onClick(View v) {
if (v==btnsave){
finish();
startActivity(new Intent(Profile.this,Profile.class));
}
}
}
This is my database:
You have added your firebase listener on the entire HomeownerUsers node and then you are looping through the results. Instead you should add the listener on the specific child of HomeownerUsers of the current user. And for a bit more optimisation in your code you can use the Userinformation class to retreive the data instead of retreiving each field seperatly.
So your addValueEventListener will look like this:
final DatabaseReference user = database.getReference("HomeownerUsers").child(UserUID);
user.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String establishmentname=dataSnapshot.child("Establishment Name").getValue().toString();
String address=dataSnapshot.child("Address").getValue().toString();
String contact=dataSnapshot.child("Contact").getValue().toString();
String availability=dataSnapshot.child("Availablility").getValue().toString();
String price=dataSnapshot.child("Price").getValue().toString();
String type=dataSnapshot.child("Type").getValue().toString();
String condition=dataSnapshot.child("Conditions").getValue().toString();
String ownername=dataSnapshot.child("Owner Name").getValue().toString();
establishmentdisplay.setText(establishmentname);
addressdisplay.setText(address);
contactdisplay.setText(contact);
availabilitydisplay.setText(availability);
pricedisplay.setText(price);
typedisplay.setText(type);
conditiondisplay.setText(condition);
ownernamedisplay.setText(ownername)
}
}
More information can be found in the firebase docs.

Saving user's extra data in firebase database

I'm trying to save user's data in my database but i sometimes get null value from:
currentUser = dataSnapshot.getValue(User.class);
the key is correctly to the user id but the value is null
Here is my code:
package com.example.eltobgy.yala;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
import com.firebase.ui.auth.AuthUI;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
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.google.firebase.database.ValueEventListener;
import java.util.Arrays;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private static final String ANONYMOUS = "Anonymous";
// Choose an arbitrary request code value
private static final int RC_SIGN_IN = 1;
public static DatabaseReference mDatabaseReference;
public static FirebaseDatabase mDatabase;
public static User currentUser;
// Firebase
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private ChildEventListener mChildEventListener;
private String mUsername;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Signing you in ...");
progressDialog.show();
mUsername = ANONYMOUS;
mFirebaseAuth = FirebaseAuth.getInstance();
mDatabase = FirebaseDatabase.getInstance();
currentUser = null;
mDatabaseReference = mDatabase.getReference().child("users");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
if (firebaseUser != null) {
// User is signed in
onSignedInInitialize(firebaseUser.getDisplayName());
DatabaseReference userDatabaseRefrence = mDatabaseReference.child(firebaseUser.getUid());
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
currentUser = dataSnapshot.getValue(User.class);
progressDialog.dismiss();
if (currentUser.isBasicInfo()) {
if (currentUser.getCurrentType().equals("")) {
Intent intent = new Intent(MainActivity.this, UserTypeActivity.class);
startActivity(intent);
} else if (currentUser.getCurrentType().equals("t")) {
if (!currentUser.isDeliveryModeActivation()) {
Intent intent = new Intent(MainActivity.this, DeliveryManExtraInfoActivity.class);
startActivity(intent);
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(MainActivity.this, BasicInfoActivity.class);
startActivity(intent);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Toast.makeText(MainActivity.this, "cancelled", Toast.LENGTH_SHORT).show();
}
};
userDatabaseRefrence.addValueEventListener(valueEventListener);
} else {
// User is signed out
onSignedOutCleanup();
List<AuthUI.IdpConfig> providers = Arrays.asList(
new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),
new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build());
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setAvailableProviders(providers)
.setTheme(R.style.LoginTheme)
.build(),
RC_SIGN_IN);
}
}
};
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
mDatabaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!dataSnapshot.exists()) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
User user = new User(firebaseUser.getUid(), firebaseUser.getDisplayName(), firebaseUser.getEmail());
mDatabaseReference.child(user.getId()).setValue(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.sign_out_menu:
AuthUI.getInstance().signOut(this).addOnCompleteListener(new OnCompleteListener<Void>() {
public void onComplete(#NonNull Task<Void> task) {
// user is now signed out
startActivity(new Intent(MainActivity.this, MainActivity.class));
finish();
}
});
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
//mMessageAdapter.clear();
//detachDatabaseReadListener();
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
}
And my User.java class
package com.example.eltobgy.yala;
import java.io.Serializable;
public class User implements Serializable {
private String id;
private String name;
private String phone;
private String email;
private String photoUrl;
private String currentType; //c for customer, d for delivery man
private boolean deliveryModeActivation;
private int rating;
private String gender; //u:unkown, f:female, m:male
private Birthday birthday;
private boolean basicInfo;
public User(String id, String name, String email) {
this.id = id;
this.name = name;
this.phone = "";
this.email = email;
this.currentType = "";
this.deliveryModeActivation = false;
this.rating = 0;
photoUrl = "";
gender = "u";
birthday = new Birthday(0, 0, 0);
basicInfo = false;
}
public User() {
}
public boolean isBasicInfo() {
return basicInfo;
}
public void setBasicInfo(boolean basicInfo) {
this.basicInfo = basicInfo;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Birthday getBirthday() {
return birthday;
}
public void setBirthday(Birthday birthday) {
this.birthday = birthday;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCurrentType() {
return currentType;
}
public void setCurrentType(String currentType) {
this.currentType = currentType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
public boolean isDeliveryModeActivation() {
return deliveryModeActivation;
}
public void setDeliveryModeActivation(boolean deliveryModeActivation) {
this.deliveryModeActivation = deliveryModeActivation;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
}
And my database

Unable to read from Firebase using the handleResult() method for a QR Code Scanner

I want the variables one, two and three to be able to read from my database when I scan the QR Code but I cant get them to display in the Builder.setMessage() line... I have tried calling the displayDeals() method in several places but none work...
package com.example.darren.offerapp;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
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.google.firebase.database.ValueEventListener;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class PopUpPage extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
private FirebaseAuth firebaseAuth;
private FirebaseUser firebaseUser;
private DatabaseReference databaseReference;
private String dealID;
private Deals_Information deals_information;
private String one = "";
private String two = "";
private String three = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pop_up_page);
//stuff for popup window
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.8), (int)(height*0.6));
//calling the method which will pull the deals from the database
//displaySuggestion();
firebaseAuth = FirebaseAuth.getInstance();
firebaseUser = firebaseAuth.getCurrentUser();
databaseReference = FirebaseDatabase.getInstance().getReference();
dealID = firebaseUser.getUid();
displayDeals();
}
public void displayDeals(){
databaseReference.child("FruitDeals").child(dealID).addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
deals_information = dataSnapshot.getValue(Deals_Information.class);
one = deals_information.getDeal();
two = deals_information.getPrice();
three = deals_information.getAisleNum();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public void onClick(View v){
mScannerView = new ZXingScannerView(this);
setContentView(mScannerView);
mScannerView.setResultHandler(this);
mScannerView.startCamera();
}
#Override
protected void onPause() {
super.onPause();
mScannerView.stopCamera();
}
#Override
public void handleResult(Result result) {
//do anything with result here
Log.w("handleResult", result.getText());
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Your Deal");
builder.setMessage("Offer: " + one + "\r\n\r\nPrice: " + two + "\r\n\r\nAisle Number: " + three + "");
AlertDialog alertDialog = builder.create();
alertDialog.show();
//resume scanning
//mScannerView.resumeCameraPreview(this); //uncomment out this line when you want to scan again
}
}
The Deals_Information class is here:
package com.example.darren.offerapp;
public class Deals_Information {
private String deal;
private String price;
private String aisleNum;
//getters and setters
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getAisleNum() {
return aisleNum;
}
public void setAisleNum(String aisleNum) {
this.aisleNum = aisleNum;
}
public String getDeal() {
return deal;
}
public void setDeal(String deal) {
this.deal = deal;
}
public Deals_Information(){
}
public Deals_Information(String deal, String price, String aisleNum)
{
this.deal = deal;
this.price = price;
this.aisleNum = aisleNum;
}
}
This is the image I am talking about in my last comment

How to not get data to overwritten in firebase and store an attribute as a list of items?

Whenever I click on the SAVE Button to save the name and number, the skills field is being overwritten.
Here the image of Activity while storing details
Also please help me to get the skills as a list instead of creating new skilladd every time. Also new skills must be appended to the list without overwriting.
/**** ACCOUNT.JAVA ****/
package com.coginitoamicis.coginitoamicis;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class Account extends AppCompatActivity implements View.OnClickListener {
private EditText accname;
private EditText accnumb;
private EditText accskill;
private Button accsave;
private Button accskilladd;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
firebaseAuth = FirebaseAuth.getInstance();
if (firebaseAuth.getCurrentUser()==null){
finish();
startActivity(new Intent(getApplicationContext(), LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
accname = (EditText) findViewById(R.id.accname);
accnumb = (EditText) findViewById(R.id.accnumb);
accsave = (Button) findViewById(R.id.accsave);
accskill = (EditText) findViewById(R.id.accskill);
accskilladd = (Button) findViewById(R.id.accskilladd);
accsave.setOnClickListener(this);
accskilladd.setOnClickListener(this);
}
private void userdatasave(){
String name = accname.getText().toString().trim();
String numb = accnumb.getText().toString().trim();
if(TextUtils.isEmpty(name)){
//name is empty
Toast.makeText(this,"Please Enter your Name",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(numb)){
//number is empty
Toast.makeText(this,"Please Enter your Mobile Number",Toast.LENGTH_SHORT).show();
return;
}
UserInformation userInformation = new UserInformation(name, numb);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).setValue(userInformation);
Toast.makeText(this,"Information Saved",Toast.LENGTH_SHORT).show();
}
private void skilldatasave(){
String skill = accskill.getText().toString().trim();
if(TextUtils.isEmpty(skill)){
//skills is empty
Toast.makeText(this,"Enter Skill to Proceed",Toast.LENGTH_SHORT).show();
return;
}
Skilladd skilladds = new Skilladd(skill);
FirebaseUser user =firebaseAuth.getCurrentUser();
databaseReference.child(user.getUid()).push().setValue(skilladds);
Toast.makeText(this,"Skills Added Successfully",Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
if (view == accsave){
userdatasave();
}
if (view == accskilladd){
skilldatasave();
}
}
}
/**** USERINFORMATION.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class UserInformation {
public String name;
public String numb;
public UserInformation(String name, String numb){
this.name = name;
this.numb = numb;
}
}
/**** SKILLADD.JAVA ****/
package com.coginitoamicis.coginitoamicis;
public class Skilladd {
public String skill;
public Skilladd(String skill){
this.skill = skill;
}
}
Use Push()
Firebase newsPush = new Firebase(Config.FIREBASE_URL);
final News news = new News();
news.setNewsTitle(newsTitleString);
news.setNewsDetails(newsDetailsString);
newsPush.push().setValue(news);
Create Getters and Setters for Object
public class News implements Serializable {
private String newsTitle;
private String newsDetails;
private String newsDate;
private String newsPicUrl;
/*news Model to get and set news data*/
public String getNewsTitle() {
return newsTitle;
}
public void setNewsTitle(String newsTitle) {
this.newsTitle = newsTitle;
}
public String getNewsDetails() {
return newsDetails;
}
public void setNewsDetails(String newsDetails) {
this.newsDetails = newsDetails;
}
Use this on oncreate
keysArray = new ArrayList<>();
valuesAdapter = new ArrayAdapter<String> (this,android.R.layout.simple_list_item_1, android.R.id.text1, displayArray);
listView.setAdapter(valuesAdapter);
listView.setOnItemClickListener(itemClickListener);
rootRef = FirebaseDatabase.getInstance().getReference();
rootRef.addChildEventListener(childEventListener);
save.setOnClickListener(this);
here i use this code onSAve click:
private void save(String name, String message) {
rootRef.child(name).setValue(message, new CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
nameEditText.setText("");
messageEditText.setText("");
hideProgressBar();
}
});
}
and here use child listner :
ChildEventListener childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.add(keyAndValue);
keysArray.add(dataSnapshot.getKey().toString());
updateListView();
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
String changedKey = dataSnapshot.getKey();
int changedIndex = keysArray.indexOf(changedKey);
String keyAndValue = "Name: " + dataSnapshot.getKey().toString() + "\t Messsage: " + dataSnapshot.getValue().toString();
displayArray.set(changedIndex, keyAndValue);
updateListView();
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
String deletedKey = dataSnapshot.getKey();
int removedIndex = keysArray.indexOf(deletedKey);
keysArray.remove(removedIndex);
displayArray.remove(removedIndex);
updateListView();
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
Log.d(TAG, dataSnapshot.getKey() + ":" + dataSnapshot.getValue().toString());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};

Categories

Resources