The goal of the following code is to save data in Cloud Firestore from a android device(api 24)
public class MainActivity extends AppCompatActivity {
public static final String NUM_KEY="num";
public static final String SMS_KEY="sms";
private static final String TAG = "MainActivity";
private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("android/websms");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void saveSMS(View view){
EditText num = (EditText) findViewById(R.id.num);
EditText sms = (EditText) findViewById(R.id.msg);
String quotenum = num.getText().toString();
String quotesms = sms.getText().toString();
Button button = (Button) findViewById(R.id.button);
Map<String,Object> dataToSave = new HashMap<String, Object>();
dataToSave.put(NUM_KEY,quotenum);
dataToSave.put(SMS_KEY,quotesms);
mDocRef.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG,"Document was not saved",e);
}
});
}
I'm following some Firestore tutorials on youtube and it seems to be a little bit outdated because when I'm running it on my android device I get the following error on the console
04-17 02:09:50.718 2600-2712/com.example.joao.websms1 E/art: The String#value field is not present on Android versions >= 6.0
Thank you in advance to anyone willing to help.
¿Have u tried using the method push?
mDocRef.push(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG,"Document was not saved",e);
}
});
Related
I tryed to show up text on the TextView which i'm saved with the saveQuote methode on Firestore, but just recieve null. I'm also had some problems by doing this with the "normal" database from Firebase. I definded the OnClick mthode for the buttons on the xml. Can someone maybe tell me how to fix that problem ? My logcat say "E/memtrack: Couldn't load memtrack module", "GCM_HB_ALARM release without a matched acquire!" and " Not supplying enough data to HAL, expected position".
public class MainActivity extends AppCompatActivity {
private static final String TAG = "InspiringQuote";
public static final String AUTHOR_KEY = "author";
public static final String QUOTE_KEY = "quote";
private TextView textViewData;
private DocumentReference mDocRef = FirebaseFirestore.getInstance().document("sampleData/inspiration");
TextView mQuoteTextView;
private FirebaseFirestore db = FirebaseFirestore.getInstance();
private CollectionReference noteRef = db.collection("inspiration");
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//mQuoteTextView = (TextView) findViewById(R.id.text_view_data);
textViewData = (TextView) findViewById(R.id.text_view_data);
//Toolbar Options
//toolbar = (Toolbar) findViewById(R.id.testToolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setTitle("HomePage");
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//
}
public void saveQuote(View view){
EditText quoteView = (EditText) findViewById(R.id.editTextQuote);
EditText authorVIew = (EditText) findViewById(R.id.editTextAuthor);
String quoteText = quoteView.getText().toString();
String authorText = authorVIew.getText().toString();
if (quoteText.isEmpty() || authorText.isEmpty()){return;}
Map<String, Object> dataToSave = new HashMap<String, Object>();
dataToSave.put("QUOTE_KEY", quoteText);
dataToSave.put("AUTHOR_KEY", authorText);
mDocRef.set(dataToSave).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "Document has been saved");
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w(TAG, "Document was not saved", e);
}
});
}
public void loadNote(View v){
mDocRef.get()
.addOnSuccessListener(new OnSuccessListener<DocumentSnapshot>() {
#Override
public void onSuccess(DocumentSnapshot documentSnapshot) {
if(documentSnapshot.exists()){
String title = documentSnapshot.getString(QUOTE_KEY);
String description = documentSnapshot.getString(AUTHOR_KEY);
//Map<String, Object> note = documentSnapshot.getData();
textViewData.setText("Title" + title + "\n" + "Description: " + description);
}else{
Toast.makeText(MainActivity.this, "Document does not exits", Toast.LENGTH_SHORT);
}
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this, "ERROR", Toast.LENGTH_SHORT).show();
Log.d(TAG, e.toString());
}
});
}
}
In the imgae you can see that im recieving "null"
As per my comment
String title = documentSnapshot.getString("QUOTE_KEY");
String description = documentSnapshot.getString("AUTHOR_KEY");
In your code, when you are adding the values, you are declaring a string value. However, when you are retrieving the values, you have declared string variable with different value. Therefore, it can't find what you are looking for.
I am new in android, I am trying to develop a simple system in android and using the cloud firestore beta as the database. I have already done the registration part which is writing the data(email & password) in the database. but I do not know the process for the login as i want the system to read the data from the database and match with the emails and passwords from the database. Can anyone help me? Thanks in advance.
The registration activity is given below:
public class RegisterActivity extends AppCompatActivity {
private Button btnRegister;
private EditText edtxtEmail;
private EditText edtxtTpnumber;
private EditText edtxtDepartment;
private EditText edtxtPassword;
private EditText edtxtConfirmpassword;
private FirebaseFirestore rFireStore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
rFireStore = FirebaseFirestore.getInstance();
btnRegister = (Button) findViewById(R.id.btnregister);
edtxtEmail = (EditText) findViewById(R.id.edtxtemail);
edtxtTpnumber = (EditText) findViewById(R.id.edtxttpnumber);
edtxtDepartment = (EditText) findViewById(R.id.edtxtdepartment);
edtxtPassword = (EditText) findViewById(R.id.edtxtpassword);
edtxtConfirmpassword = (EditText) findViewById(R.id.edtxtconfirmPassword);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Email = edtxtEmail.getText().toString();
String TPnumber = edtxtTpnumber.getText().toString();
String Department = edtxtDepartment.getText().toString();
String Password = edtxtPassword.getText().toString();
String ConfirmPassword = edtxtConfirmpassword.getText().toString();
Map<String, String> userMap = new HashMap<>();
userMap.put("Email Address", Email);
userMap.put("TP Number", TPnumber);
userMap.put("Department", Department);
userMap.put("Password", Password);
userMap.put("Confirm Pass", ConfirmPassword);
rFireStore.collection("Users").document("Students").set(userMap).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});
/*rFireStore.collection("Users").add(userMap).addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText(RegisterActivity.this, "Data Saved!!", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(RegisterActivity.this, "Data Failed!!", Toast.LENGTH_SHORT).show();
}
});*/
}
});
}
}
For login you can use this:
for (QueryDocumentSnapshot documentSnapshot : task.getResult()) {
if (task.isSuccessful()) {
//task result = 1
}
}
if (task.getResult().size() == 0) {
//task result = 0
}
public class Post extends AppCompatActivity {
private static final String TAG = null;
private TextView titleView;
private Button create_post_button;
private EditText post_title,post_description;
private FirebaseAuth mAuth;
private ProgressBar progressBar;
private FirebaseFirestore db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post);
mAuth=FirebaseAuth.getInstance();
db = FirebaseFirestore.getInstance();
progressBar = (ProgressBar) findViewById(R.id.progressBar2);
titleView=(TextView) findViewById(R.id.titleView);
post_title=(EditText) findViewById(R.id.post_title);
post_description=(EditText) findViewById(R.id.post_description);
create_post_button=(Button)findViewById(R.id.create_post_button);
create_post_button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
createPost();
}
});
}
public void createPost() {
String title_val = post_title.getText().toString().trim();
String post_description_val = post_description.getText().toString().trim();
String user_id=mAuth.getCurrentUser().getUid();
if (!TextUtils.isEmpty(title_val) && !TextUtils.isEmpty(post_description_val)) {
progressBar.setVisibility(View.VISIBLE);
Map<String, String> posts = new HashMap<>();
posts.put("description",post_description_val);
posts.put("title", title_val);
posts.put("user_id", user_id);
progressBar.setVisibility(View.GONE);
db.collection("posts")
.add(posts)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText( Post.this,"Success", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w( TAG,"Error adding document", e);
}});}}}
Its not being inserted into db,neither it gives any error.I don't understand where the error is!I don't know what is wrong since everything is from android main page.If it is some logic error please let me know!
Some help would be appreciated! Thanks in advance!
The problem is because you're accessing the variables wrong when checking for empty title and description, here:
if (!TextUtils.isEmpty(title) && !TextUtils.isEmpty(description_val)) {
it should be:
public void createPost() {
String title_val = title.getText().toString().trim();
String post_description_val = description.getText().toString().trim();
String user_id=mAuth.getCurrentUser().getUid();
if (!title_val.isEmpty() && !post_description_val.isEmpty()) {
progressBar.setVisibility(View.VISIBLE);
Map<String, String> posts = new HashMap<>();
posts.put("description",description_val);
posts.put("title", title);
posts.put("user_id", user_id);
progressBar.setVisibility(View.GONE);
db.collection("posts")
.add(posts)
.addOnSuccessListener(new OnSuccessListener<DocumentReference>() {
#Override
public void onSuccess(DocumentReference documentReference) {
Toast.makeText( Post.this,"Success", Toast.LENGTH_SHORT).show();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.w( TAG,"Error adding document", e);
}
});
}
}
EDIT:
For testing purposes your rules should look like this, later you need to update them to make them more secure:
I have an activity where i want to send a custom message to a sub-group in my database when a button is clicked. I tried to check for a user_id and send the message to those user id's, My problem is that when i click the button(status) it only sends that message to one person.
This is my Activity:
public class messageActivity extends AppCompatActivity {
private Button status;
private DatabaseReference mRootRef;
private String mCurrentUserId;
private String userName;
private String user_id;
private String message;
private FirebaseAuth mAuth;
private DatabaseReference mUserRef;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
FirebaseApp.initializeApp(this);
mRootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
gettingIntent();
status = (Button)findViewById(R.id.rescue);
status.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
addUpdateMessage();
addTeamUpdateChat();
Toast.makeText(getApplicationContext(), "Team Update message was successfully sent",Toast.LENGTH_LONG).show();
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Status");
toolbar.setTitleTextColor(android.graphics.Color.WHITE);
if (mAuth.getCurrentUser() != null) {
mUserRef = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
mUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
userName = dataSnapshot.child("name").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void checkUser() {
if (mCurrentUserId == null) {
sendToStart();
}else{
Toast.makeText(getApplicationContext(), "Logged in",Toast.LENGTH_SHORT).show();
}
}
private void gettingIntent() {
Intent intent =getIntent();
user_id = intent.getStringExtra("user_id");
}
private void addTeamUpdateChat() {
String current_user_ref="Team_Updates/"+mCurrentUserId+"/"+user_id;
String reciever_user_ref= "Team_Updates/"+user_id+"/"+mCurrentUserId;
DatabaseReference team_push_key = mRootRef.child("Emergency_Messages").child(mCurrentUserId).child(user_id).push();
String push_key = team_push_key.getKey();
Map messageMap = new HashMap();
messageMap.put("userName", userName + " Is now a new Member of the team.");
messageMap.put("type","text");
messageMap.put("from",mCurrentUserId);
messageMap.put("seen",false);
messageMap.put("time", ServerValue.TIMESTAMP);
Map messageUserMap = new HashMap();
messageUserMap.put(current_user_ref+ "/"+push_key,messageMap);
messageUserMap.put(reciever_user_ref+ "/"+push_key,messageMap);
mRootRef.updateChildren(messageUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!=null){
Log.d("TAG",databaseError.getMessage().toString());
}
}
});
}
private void addUpdateMessage() {
mRootRef.child("Team_Updates_Chat").child(mCurrentUserId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(!dataSnapshot.hasChild(user_id)){
Map chatAddMap = new HashMap();
chatAddMap.put("seen",false);
chatAddMap.put("timestamp", ServerValue.TIMESTAMP);
Map chatUserMap = new HashMap();
chatUserMap.put("Team_Updates_Chat/"+mCurrentUserId+"/"+user_id, chatAddMap);
chatUserMap.put("Team_Updates_Chat/"+user_id+"/"+mCurrentUserId, chatAddMap);
mRootRef.updateChildren(chatUserMap, new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError!= null){
Toast.makeText(MenuActivity.this, "Error: "+databaseError.getMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
} else{
mCurrentUserId = mAuth.getCurrentUser().getUid();
}
}
#Override
protected void onStop() {
super.onStop();
}
private void sendToStart() {
Intent startIntent = new Intent(messageActivity.this, Home.class);
startActivity(startIntent);
finish();
}
}
I'm Still learning Programming in Android Studio, Is there Any suggestions on how i should approach this?
You are sending a message only to single user because you are getting only a single user. To send a message to multiple users, you need to loop to get all those users and then send the message to all of them.
Hello Guys i need you I have a problem with Firebase Realtime Database I put the data successful to the Firebase but when I try to retrieve it from Firebase I got a problem there is how I put the data
private void user_info(String user_id, String user_display_name) {
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
HashMap<String, String> userMap = new HashMap<>();
userMap.put("Name",user_display_name);
userMap.put("Balls","30");
userMap.put("Level","1");
mProgressDialog.setMessage("Please Wait...");
mDatabase.setValue(userMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
}
else
Toast.makeText(WelcomeActivity.this, ""+task.getException(), Toast.LENGTH_SHORT).show();
mProgressDialog.dismiss();
}
});
}
And how I try to retrieve the data
private FirebaseUser mUser;
private DatabaseReference mDatabase;
private String level,level1;
private int lev,i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_acticity);
//Image
mImg_level1 = (ImageView)findViewById(R.id.mImg_lev1);
mImg_level2 = (ImageView)findViewById(R.id.mImg_lev2);
mImg_level3 = (ImageView)findViewById(R.id.mImg_lev3);
mImg_level4 = (ImageView)findViewById(R.id.mImg_lev4);
mImg_level5 = (ImageView)findViewById(R.id.mImg_lev5);
mImg_level6 = (ImageView)findViewById(R.id.mImg_lev6);
mImg_level7 = (ImageView)findViewById(R.id.mImg_lev7);
mImg_level8 = (ImageView)findViewById(R.id.mImg_lev8);
mImg_level9 = (ImageView)findViewById(R.id.mImg_lev9);
mImg_level10 = (ImageView)findViewById(R.id.mImg_lev10);
mImg_level11 = (ImageView)findViewById(R.id.mImg_lev11);
//Firebase
mUser = FirebaseAuth.getInstance().getCurrentUser();
String user_id = mUser.getUid();
mDatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(user_id);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
The toast don't show anything because it null
Change this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
to this :-
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
level = dataSnapshot.child("Level").getValue().toString();
if (level.equals("1")){
level1 = "1";
}
Toast.makeText(this, level1, Toast.LENGTH_SHORT).show();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The reason this works is that Firebase downloads asynchronously and your code lines execute synchronously.