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));
}
}
Related
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.
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
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) {
// ...
}
});
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
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) {
}
};