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:
Related
I have implemented the code to upload the user photo to storage and retrieve it to the firestore and realtimeDB. the problem is when I set the imageuri to database :
then I'm (or user) updating a photo to firebase, the URI is successfully updated to the profile string..(firestore) and image srting (realtimeDB). but after some time/after the app closes, the photo not loading properly.(or its gone), it didn't use the firebase token as the download Uri.
its like this :
content://com.android.providers.media.documents/document/image%3A81399
then I attached another code to get the updated image URL from storage. But another problem
for now, Both Databases didn't store the URLs
I have attached the code below.
public class ProfileFragment extends Fragment {
public ProfileFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
CircleImageView profileImageView;
FragmentProfileBinding binding;
private Uri photoUri;
private String imageUrl;
FirebaseFirestore firestore;
FirebaseStorage storage;
FirebaseAuth auth;
StorageReference storageReference;
DocumentReference documentReference;
DatabaseReference DBreference;
String currentUserId;
User user; //class
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
binding = FragmentProfileBinding.inflate(inflater, container, false);
firestore = FirebaseFirestore.getInstance();
auth = FirebaseAuth.getInstance();
storage = FirebaseStorage.getInstance();
auth = FirebaseAuth.getInstance();
FirebaseUser fUser = FirebaseAuth.getInstance().getCurrentUser();
currentUserId = fUser.getUid();
documentReference = firestore.collection("Users").document(currentUserId);
storageReference = FirebaseStorage.getInstance().getReference().child("Profile Pictures");
DBreference = FirebaseDatabase.getInstance().getReference().child("Users");
update = binding.updateBtn;
profileImageView= binding.profilePhoto;
clickListener();
return binding.getRoot();
}
private void clickListener() {
profileImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
//noinspection deprecation
startActivityForResult(intent, 3);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
progressDialog.show();
StorageReference reference = storage.getReference().child("Profile Pictures")
.child(FirebaseAuth.getInstance().getUid());
reference.putFile(photoUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
storageReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
imageUrl = uri.toString();
updateUserProfileToFirestore();
updateUserProfileToDataBase();
}
});
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(#NonNull #NotNull UploadTask.TaskSnapshot snapshot) {
long totalSi = snapshot.getTotalByteCount();
long transferS = snapshot.getBytesTransferred();
long totalSize = (totalSi / 1024);
long transferSize = transferS / 1024;
progressDialog.setMessage("Uploaded " + ((int) transferSize) + "KB / " + ((int) totalSize) + "KB");
}
});
}
});
}
#SuppressWarnings("deprecation")
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
if (data.getData() != null) {
photoUri = data.getData();
// profileImageView.setImageURI(imageUri);
}
Toast.makeText(getContext(), "Photo selected!", Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(getContext(), "Error"+e, Toast.LENGTH_SHORT).show();
}
}
private void updateUserProfileToFirestore() {
Map<String, Object> profile = new HashMap<>();
profile.put("profile", imageUrl);
final DocumentReference sDoc = firestore.collection("Users").document(FirebaseAuth.getInstance().getUid());
firestore.runTransaction(new Transaction.Function<Void>() {
#Override
public Void apply(#NonNull Transaction transaction) throws FirebaseFirestoreException {
DocumentSnapshot snapshot = transaction.get(sDoc);
transaction.update(sDoc, profile);
// transaction.update(sDoc, "name", binding.nameBox.getText() );
return null;
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
progressDialog.setMessage("updated!");
progressDialog.dismiss();
Toast.makeText(getContext(), "Photo Updated!", Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.setMessage("Can't upload");
progressDialog.dismiss();
Toast.makeText(getContext(), "Failed to update, try again later", Toast.LENGTH_SHORT).show();
}
});
// final DatabaseReference
}
// Realtime database
private void updateUserProfileToDataBase() {
HashMap<String, Object> map = new HashMap<>();
map.put("image", imageUrl);
DBreference.child(FirebaseAuth.getInstance().getUid())
.updateChildren(map)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
}
}).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(getContext(), "Success", Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull #NotNull Exception e) {
Toast.makeText(getContext(), "Failed!", Toast.LENGTH_SHORT).show();
}
});
}
}
Solved! It's based on the storage reference. just changed to "reference".
because I already declared the storage reference. but I entered it twice
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
}
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);
}
});
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.