android-reading and writing in realtime database - android

I have a user class, which have a contactlist(friends). I want to add the possibility to add friends.
My database
In my code I have a addFriend method, which call a checkUser method. Here I check if the user exists so I can add him in the friend list. I am having difficulties implementing that, like how can I retrieve a variable from an anonymous class?
Here is my code.
package com.android.pfe.other;
import android.support.annotation.Keep;
import android.util.Log;
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.IgnoreExtraProperties;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import java.io.Serializable;
import java.util.Hashtable;
import java.util.List;
/**
* Created by SADA INFO on 13/04/2018.
*/
#IgnoreExtraProperties
#Keep
public class User implements Serializable {
private static final String TAG ="UserClass" ;
public String username;
public String email;
public Hashtable contact;
public String Uid;
public List article;
public DatabaseReference mDatabase;
public List<User> UserList;
public User uti;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(com.android.pfe.other.User.class)
}
public User(String username, String email,String uid) {
this.username = username;
this.email = email;
this.contact=new Hashtable<String,Boolean>();
this.Uid=Uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void addUser(String UserId, String name, String email) {
mDatabase = FirebaseDatabase.getInstance().getReference("User");
User user = new User(name, email,UserId);
mDatabase.child(UserId).setValue(user);
}
public void addFriend(String UserId, final String email)
{
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(UserId);
final DatabaseReference friendlist = user.child("contact");
if(checkUser(email)==true)
friendlist.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Hashtable list = dataSnapshot.getValue(Hashtable.class);
if(list.isEmpty())
{
friendlist.setValue(email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public boolean checkUser(String email){
Query query = FirebaseDatabase.getInstance().getReference("User").orderByChild("email").equalTo(email);
query.addListenerForSingleValueEvent(mValueEventListener);
if(uti==null)
{
return false;
}
return true;
}
ValueEventListener mValueEventListener=new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
uti=dataSnapshot.getValue(User.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
}
};
}

I would recommend that you define an interface say 'ICheckUserListener' with something like onSuccess(DataSnapshot dataSnapshot) and onError(Exception e) methods.
public void checkUser(String email, ICheckUserListener listener)
//Since this method is independent of a specific User instance, it can be static which would require minor adjustments to prevent a memory-leak
{
ValueEventListener mValueEventListener = new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot)
{
listener.success(dataSnapshot.exists() ? dataSnapshot : null);
}
#Override
public void onCancelled(DatabaseError databaseError)
{
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
listener.onError(databaseError.toException());
}
};
FirebaseDatabase
.getInstance()
.getReference("User")
.orderByChild("email") //This is redundant if email ids are unique
.equalTo(email)
.addListenerForSingleValueEvent(mValueEventListener);
}
You can then implement 'ICheckUserListener' in your 'addFriend' method to handle the result.

Related

android- snapshot.getvalue points at a null pointer

I used an interface to retrieve data from the database and use it,at first when I was using String it was working but after i wanted to take the whole child I keep getting a null pointer, here is the whole class but the part where the null pointer is in checkUser method in uti variable
package com.android.pfe.other;
import android.support.annotation.Keep;
import android.util.Log;
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.IgnoreExtraProperties;
import com.google.firebase.database.ValueEventListener;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
/**
* Created by SADA INFO on 13/04/2018.
*/
#IgnoreExtraProperties
#Keep
public class User implements Serializable {
private static final String TAG ="UserClass" ;
public String username;
public String email;
public ArrayList<User> contact;
public String Uid;
public List article;
public DatabaseReference mDatabase;
public ArrayList<User> UserList;
public User uti;
public User() {
// Default constructor required for calls to DataSnapshot.getValue(com.android.pfe.other.User.class)
}
public User(String username, String email) {
this.username = username;
this.email = email;
}
public User(String username, String email,String uid) {
this.username = username;
this.email = email;
this.contact=new ArrayList<User>();
this.Uid=Uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public void addUser(String UserId, String name, String email) {
mDatabase = FirebaseDatabase.getInstance().getReference("User");
User user = new User(name, email,UserId);
mDatabase.child(UserId).setValue(user);
}
public void addFriend(String UserId, final String email)
{
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(UserId);
final DatabaseReference friendlist = user.child("contact");
checkUser(email, new ICheckUserListener() {
#Override
public void onSuccess(final User value) {
friendlist.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
ArrayList<User> list =(ArrayList<User>) dataSnapshot.getValue();
//this is where value is null
if(list==null&&value!=null)
{
list=new ArrayList<User>();
User user=new User(value.username,email);
list.add(user);
friendlist.setValue(list);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onError(Exception e) {
}
});
}
public void checkUser(String email, final ICheckUserListener listener) {
ValueEventListener mValueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// listener.onSuccess(dataSnapshot.exists() ? dataSnapshot : null);
//uti is always null
uti=dataSnapshot.getValue(User.class);
listener.onSuccess(uti);
if(uti==null) {
Log.w(TAG, "user pas trouvé");
}
// addFriend(uti.getEmail(),uti.getUsername());
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadUser:onCancelled", databaseError.toException());
listener.onError(databaseError.toException());
}
};
FirebaseDatabase
.getInstance()
.getReference("User")
.equalTo(email)
.addListenerForSingleValueEvent(mValueEventListener);
}
public void getFriends(String UserId){
mDatabase = FirebaseDatabase.getInstance().getReference("User");
DatabaseReference user = mDatabase.child(UserId);
final DatabaseReference friendlist = user.child("contact");
friendlist.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserList=(ArrayList)dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
public ArrayList<User> getUserList() {
return UserList;
}
}
my database
To get a user by their email address you'll need to run a Firebase Database query.
FirebaseDatabase
.getInstance()
.getReference("User")
.orderByChild("email")
.equalTo(email)
.addListenerForSingleValueEvent(mValueEventListener);
That will give your listener the right result.
But your onDataChange won't work yet either. You're trying to get a List out of the snapshot, but it really is a Map with the string keys (EuEr..., etc) and the properties as a value. So you'll need to convert that in your callback:
public void onDataChange(DataSnapshot dataSnapshot) {
UserList = new ArrayList<User>();
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
UserList.add(userSnapshot.getValue(User.class));
}
}

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.

Stuck with this issue of eventlistener with list

Have been trying to solve this problem for so long
I have a list called datalist in which I am storing data from firebase in order to use it in the recyclerview.
But the problem is inside childeventlistener the list is getting updated but before this happens return call is made and it ends up in a null list.
What should be done?
package com.example.dell.hungryapp;
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 java.util.ArrayList;
import java.util.List;
/**
* Created by Dell on 5/29/2017.
*/
public class itemmodel {
public String item_name;
public int quantity;
public String getItem_name() {
return item_name;
}
public void setItem_name(String item_name) {
this.item_name = item_name;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public static List<itemmodel> getObjectList(){
final List<itemmodel> datalist=new ArrayList<>();
DatabaseReference databaseReference= FirebaseDatabase.getInstance().getReference();
FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser();
databaseReference.child("Users").child(user.getUid()).child("Inventory").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
System.out.println("value is : "+dataSnapshot.getValue());
String id=dataSnapshot.getKey();
Integer qty=dataSnapshot.getValue(Integer.class);
itemmodel item=new itemmodel();
item.setItem_name(id);
item.setQuantity(qty);
datalist.add(item);
System.out.println("before size : "+datalist.size());
}
#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) {
}
});
System.out.println("before size : "+datalist.size());
return datalist;
}
}
Kindly follow this link if you want to retrieve the whole data from inventory. I have used maps in order to retrieve the whole data and stored it in array list
final DatabaseReference myRef = database.getReference().child("users").child(users.getUid).child("Inventory");
Remove the previous markers as the location updates
Hope it solves your problem

Firebase database not retrieving data W/ClassMapper: No setter/field for -KeAi52QSaiuf7p5jEYM found on class

Database
"userinformation": [
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
}
Class myprofile not retrieving data
package **.****;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import android.view.Menu;
import android.view.MenuItem;
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.useri1;
public class myprofile extends AppCompatActivity {
private TextView myusername111;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.myprofile__activity);
myusername111 = (TextView) findViewById(R.id.textview22);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
useri1 model = dataSnapshot.getValue(useri1.class);
myusername111.setText(model.getusername());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
class edit_profile
package package ***.****;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import ***.***.m_Model.useri1;
public class edit_profile extends AppCompatActivity {
private Toolbar toolbar;
private EditText website;
private EditText username;
private Button bsubmit;
private DatabaseReference mFirebaseDatabase;
private FirebaseDatabase mFirebaseInstance;
private android.view.ViewGroup parent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
mFirebaseInstance = FirebaseDatabase.getInstance();
mFirebaseDatabase = mFirebaseInstance.getReference("users");
usernamr = (EditText) findViewById(R.id.usernamr);
website = (EditText) findViewById(R.id.website);
Button bsubmit = (Button) findViewById(R.id.b_submit);
bsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isEmpty(website, username) && !isEmpty(website, username)) {
mNewprofile("53", website.getText().toString().trim(), username.getText().toString().trim());
finish();
startActivity(new Intent(getApplicationContext(), myprofile.class));
}
}
} );
}
private void mNewprofile(String s, String username, String website) {
new_profile1 userinformation1 = new new_profile1(website, username);
mFirebaseDatabase.child("userinformation").setValue(userinformation1);
}
class useri1
package **.****.m_Model;
public class useri1 {
public String username;
public String website;
public Update_user1() {
}
public Update_user1(String username,String website) {
this.website = website;
this.username = username;
}
public String getwebsite() {
return website;
}
public String getusername() {
return username;
}
public void setwebsite(String website) {
this.website = website;
}
public void setusermame(String usermame) {
this.usermame = usermame;
}
Error:
W/ClassMapper: No setter/field for -KeAi52QSaiuf7p5jEYM found on class
***.****.m_Model.useri1
You're retrieving the value of userinformation. So the snapshot you get in onDataChange will have this value:
"-KeAi52QSaiuf7p5jEYM" : {
"website" : "test1"
"username" : "test1"
}
A useri1 has a website and a username property. But in the JSON above, there is only a property named -KeAi52QSaiuf7p5jEYM. So the two don't match up, leading to the error you get.
To fix this you should do a few things:
loop over the children in the snapshot
drastically simplify your POJO
The resulting code would be:
mFirebaseInstance.getReference("userinformation").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
MyUser model = dataSnapshot.getValue(MyUser.class);
myusername111.setText(model.username);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException(); // don't ignore errors
}
});
public class MyUser {
public String username;
public String website;
}
You could also use a class with getter and setter. But in that case make sure that the getters follow Java Bean property rules for the capitalization. So:
public class MyUser {
private String username;
private String website;
public MyUser() {
}
public String getUsername() { return username; }
public void setUsername(string value) { username = value; }
public String getWebsite() { return website; }
public void setWebsite(string value) { website = value; }
}
You should use ChildEventListener instead of ValueEventListener.
Because you are using ValueEventListener Firebase is trying to set a property named -KeAi52QSaiuf7p5jEYM, but it is not a property, it is a key.
The code to add ChildEventListener looks like:
mFirebaseInstance.getReference("userinformation").addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String previousKey) {
Update_user1 user = dataSnapshot.getValue(Update_user1.class);
// ...
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String previousKey) {
// ...
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
// ...
}
#Override
public void onCancelled(DatabaseError databaseError) {
// ...
}
});

Firebase Realtime Database error while getting values

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

Categories

Resources