I'm creating an app that display notes list in a recyclerView. I connected the app with firebase authentication and realtime database.
The Realtime Database JSON tree looks like this:
The problem is that I want "Notes" to be part of "Users" which is not the case, because when I login to my app, I found the same Notes in every user account. I want the notes to be displayed for a specific user when they create them.
Here is my code:
SignupActivity.java
public class SignupActivity extends AppCompatActivity {
private static final String TAG = "";
private static final int RC_SIGN_IN = 9001;
EditText mName, mEmail,mPassword;
Button mSignupBtn;
FirebaseAuth mAuth;
ProgressBar progressBar;
View mViewHelper;
GoogleSignInButton button;
GoogleSignInClient mGoogleSignInClient;
FirebaseAuth.AuthStateListener mAuthListner;
FirebaseFirestore fStore;
String userID;
#Override
protected void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListner);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
TextView textView = findViewById(R.id.textView);
textView.setText(Html.fromHtml(getString(R.string.agree_terms)));
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
mEmail = findViewById(R.id.et_email_address);
mPassword = findViewById(R.id.et_password);
mName = findViewById(R.id.et_name);
mSignupBtn = findViewById(R.id.create_btn);
progressBar = findViewById(R.id.loading_spinner);
mViewHelper = findViewById(R.id.view_helper);
button = findViewById(R.id.login_google_btn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
signIn();
}
});
mAuth = FirebaseAuth.getInstance();
fStore = FirebaseFirestore.getInstance();
mSignupBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String email = mEmail.getText().toString().trim();
String password = mPassword.getText().toString().trim();
final String name = mName.getText().toString();
if(TextUtils.isEmpty(email)) {
mEmail.setError("Email is required.");
return;
}
if(TextUtils.isEmpty(name)) {
mName.setError("Name is required.");
return;
}
if(TextUtils.isEmpty(password)) {
mPassword.setError("Password is required.");
return;
}
if(password.length() < 6) {
mPassword.setError("Password Must be >= 6 Characters");
return;
}
progressBar.setVisibility(View.VISIBLE);
mViewHelper.setVisibility(View.VISIBLE);
mSignupBtn.setVisibility(View.INVISIBLE);
// register the user in firebase
mAuth.createUserWithEmailAndPassword(email,password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if(task.isSuccessful()) {
Toast.makeText(SignupActivity.this, "User Created", Toast.LENGTH_SHORT).show();
userID = mAuth.getCurrentUser().getUid();
DocumentReference documentReference = fStore.collection("users").document(userID);
DatabaseReference current_user_db = FirebaseDatabase.getInstance().getReference().child("Users").child(userID);
Map<String, Object> user = new HashMap<>();
user.put("name", name);
user.put("email", email);
user.put("image", "default");
user.put("thumb_image", "default");
current_user_db.setValue(user);
documentReference.set(user).addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void aVoid) {
Log.d(TAG, "onSuccess: user Profile is created for "+ userID);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.d(TAG, "onFailure: "+ e.toString());
}
});
Intent intent = new Intent(SignupActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
finish();
}
else{
Toast.makeText(SignupActivity.this, "Error !" + task.getException().getMessage(), Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
mViewHelper.setVisibility(View.INVISIBLE);
mSignupBtn.setVisibility(View.VISIBLE);
}
});
}
});
mAuthListner = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
if (firebaseAuth.getCurrentUser() != null) {
startActivity(new Intent(SignupActivity.this, MainActivity.class));
}
}
};
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken("886475354465-j5suema9gt5mhi2fhli0un9vsn1olvaa.apps.googleusercontent.com")
.requestEmail()
.build();
mGoogleSignInClient = GoogleSignIn.getClient(this, gso);
}
private void signIn() {
Intent signInIntent = mGoogleSignInClient.getSignInIntent();
startActivityForResult(signInIntent, RC_SIGN_IN);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
if (requestCode == RC_SIGN_IN) {
Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
try {
// Google Sign In was successful, authenticate with Firebase
GoogleSignInAccount account = task.getResult(ApiException.class);
firebaseAuthWithGoogle(account);
} catch (ApiException e) {
// Google Sign In failed, update UI appropriately
Log.w(TAG, "Google sign in failed", e);
// ...
}
}
}
private void firebaseAuthWithGoogle(GoogleSignInAccount account) {
AuthCredential credential = GoogleAuthProvider.getCredential(account.getIdToken(), null);
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
// Sign in success, update UI with the signed-in user's information
Log.d(TAG, "signInWithCredential:success");
//updateUI(user);
} else {
// If sign in fails, display a message to the user.
Log.w(TAG, "signInWithCredential:failure", task.getException());
Toast.makeText(SignupActivity.this, "Aut Fail", Toast.LENGTH_SHORT).show();
//updateUI(null);
}
// ...
}
});
}
}
NotesAdapter.java
public class NotesAdapter extends RecyclerView.Adapter<NotesAdapter.MyHolder>
{
List<Listdata> noteslist;
private Context context;
public NotesAdapter(List<Listdata> noteslist,Context context)
{
this.context=context;
this.noteslist=noteslist;
}
#NonNull
#Override
public MyHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item,viewGroup,false);
MyHolder myHolder=new MyHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(#NonNull MyHolder myHolder, int position) {
Listdata data=noteslist.get(position);
myHolder.title.setText(data.getTitle());
myHolder.desc.setText(data.getDesc());
}
#Override
public int getItemCount() {
return noteslist.size();
}
class MyHolder extends RecyclerView.ViewHolder {
TextView title,desc;
public MyHolder(#NonNull View itemView) {
super(itemView);
title=itemView.findViewById(R.id.title);
desc=itemView.findViewById(R.id.desc);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Listdata listdata=noteslist.get(getAdapterPosition());
Intent i=new Intent(context, StreamActivity.class);
i.putExtra("id",listdata.id);
i.putExtra("title",listdata.title);
i.putExtra("desc",listdata.desc);
context.startActivity(i);
}
});
}
}
}
AddNotesActivity.java
public class AddNotesActivity extends AppCompatActivity {
EditText title,desc;
String titlesend,descsend;
private DatabaseReference mDatabase;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_notes);
title=findViewById(R.id.title);
desc=findViewById(R.id.desc);
mDatabase = FirebaseDatabase.getInstance().getReference();
}
public void AddNotes(View view) {
titlesend=title.getText().toString();
descsend=desc.getText().toString();
if(TextUtils.isEmpty(titlesend) || TextUtils.isEmpty(descsend)){
return;
}
AddNotes(titlesend,descsend);
}
private void AddNotes(String titlesend, String descsend)
{
String id=mDatabase.push().getKey();
Listdata listdata = new Listdata(id,titlesend, descsend);
mDatabase.child("Notes").child(id).setValue(listdata).
addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
Toast.makeText(AddNotesActivity.this, "Notes Added", Toast.LENGTH_SHORT).show();
startActivity(new Intent(getApplicationContext(),NotesActivity.class));
}
});
}
}
NotesActivity.java
public class NotesActivity extends AppCompatActivity {
// Firebase instance variables
private FirebaseAuth mFirebaseAuth;
private FirebaseUser mFirebaseUser;
//HomeScreen variables
RecyclerView recyclerView;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
List<Listdata> list =new ArrayList<>();
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
recyclerView=findViewById(R.id.recyclerview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(NotesActivity.this);
recyclerView.setLayoutManager(layoutManager);
// Initialize Firebase Auth
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseUser = mFirebaseAuth.getCurrentUser();
// Notes Screen
final NotesAdapter notesAdapter=new NotesAdapter(list,this);
recyclerView.setAdapter(notesAdapter);
FloatingActionButton fab = findViewById(R.id.fab);
firebaseDatabase=FirebaseDatabase.getInstance();
databaseReference=firebaseDatabase.getReference("Notes");
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot dataSnapshot1: dataSnapshot.getChildren())
{
Listdata listdata=dataSnapshot1.getValue(Listdata.class);
list.add(listdata);
}
notesAdapter.notifyDataSetChanged();
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(getApplicationContext(), AddNotesActivity.class));
}
});
// end NotesScreen
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mFirebaseAuth.getCurrentUser();
if(currentUser == null){
sendToStart();
}
}
private void sendToStart() {
Intent startIntent = new Intent(NotesActivity.this, LoginActivity.class);
startActivity(startIntent);
finish();
}
Please I need help on how should I modify my code to display the notes for a specific user when they create them. documentation links will be much appreciated.
you simply need to change this line of code from AddNotesActivity.java
mDatabase.child("Notes").child(id)
to
mDatabase.child("Users").child(userID).child("Notes").child(id)
and don't forget to retrieve the data in NotesActivity.java
databaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(userID).child("Notes");
Related
private ImageView imageprofilregmen;
private EditText nameEditmen;
private Button buttonsavenamemen;
private StorageReference storageprofilpicsRef;
private FirebaseStorage storage;
private Uri imageUri;
private String myUri = "";
private String checker = "";
private StorageTask uploadTask;
private FirebaseAuth mAuth;
private DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_men);
imageprofilregmen = (ImageView) findViewById(R.id.imageprofilregmen);
nameEditmen = (EditText) findViewById(R.id.nameEditmen);
buttonsavenamemen = (Button) findViewById(R.id.buttonsavenamemen);
storageprofilpicsRef = FirebaseStorage.getInstance().getReference().child("ProfileImage");
storage = FirebaseStorage.getInstance();
mAuth = FirebaseAuth.getInstance();
databaseReference = FirebaseDatabase.getInstance().getReference().child("UserMen-men");
buttonsavenamemen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (checker.equals("clicked")) {
ValidateControler();
} else {
}
}
});
imageprofilregmen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checker = "clicked";
CropImage.activity().setAspectRatio(1, 1).start(NameMenActivity.this);
}
});
getUserInfo();
}
private void ValidateControler() {
if (TextUtils.isEmpty(nameEditmen.getText().toString()))
Toast.makeText(this, "Введите ваше имя", Toast.LENGTH_SHORT).show();
else if (checker.equals("clicked")) ;
{
uploadProfilImage();
}
}
private void uploadProfilImage() {
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setTitle("Идет загрузка");
progressDialog.setMessage("Пожалуйста подождите");
progressDialog.show();
if (imageUri !=null){
final StorageReference fileRef= storageprofilpicsRef.child(mAuth.getCurrentUser().getUid()+"jpg");
uploadTask=fileRef.putFile(imageUri);
uploadTask.continueWithTask(new Continuation() {
#Override
public Object then(#NonNull Task task) throws Exception {
if (!task.isSuccessful()){
throw task.getException();
}
return fileRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task <Uri>task) {
if (task.isSuccessful()){
Uri downloadUri=task.getResult();
myUri=downloadUri.toString();
HashMap<String,Object> userMap=new HashMap<>();
userMap.put("uid",mAuth.getCurrentUser().getUid());
userMap.put("name",nameEditmen.getText().toString());
userMap.put("image",myUri);
databaseReference.child(mAuth.getCurrentUser().getUid()).updateChildren(userMap);
progressDialog.dismiss();
startActivity(new Intent(NameMenActivity.this,HomeActivity.class));
}
}
});
}
else {
Toast.makeText(this, "Изображение не выбрано", Toast.LENGTH_SHORT).show();
}
}
private void getUserInfo() {
databaseReference.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if (snapshot.exists()&&snapshot.getChildrenCount()>0)
{
String name=snapshot.child("name").getValue().toString();
nameEditmen.setText(name);
if (snapshot.hasChild("image")) {
String image = snapshot.child("image").getValue().toString();
Picasso.get().load(image).into(imageprofilregmen);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
I wrote such a code for data transfer. The imagecropper, picasso library is used. the compiler and android studio does not reveal any errors. imagecropper is launched, I select a photo, then the progress dialog goes on, but nothing happens.
I've tried searching the forums and YouTube but haven't been able to find anything.I expected that the photo will be sent to firebase storage and from there to imageview but nothing happens.
A video showing the problem:
video
public class ListActivity extends AppCompatActivity {
private ActivityListBinding binding;
private FirebaseAuth firebaseAuth;
private FirebaseFirestore firebaseFirestore;
PaketAdapter adapter;
ArrayList<Paket> paketArrayList;
String magaza;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityListBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
firebaseAuth = FirebaseAuth.getInstance();
firebaseFirestore = FirebaseFirestore.getInstance();
paketArrayList = new ArrayList<>();
binding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
adapter = new PaketAdapter(paketArrayList);
binding.recyclerView.setAdapter(adapter);
Intent intent = getIntent();
magaza = intent.getStringExtra("magaza");
getData();
}
public void getData(){
firebaseFirestore.collection(magaza).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error!=null){
Toast.makeText(ListActivity.this,error.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}else if (value!=null){
for (DocumentSnapshot documentSnapshot:value.getDocuments()){
Map<String,Object> data = documentSnapshot.getData();
name = (String) data.get("name");
String paketSayisi = (String) data.get("paketSayisi");
String angaryaSayisi = (String) data.get("angaryaSayisi");
//FieldValue tarih = (FieldValue) data.get("tarih");
//String magaza = (String) data.get("magaza");
Paket paket = new Paket(name,paketSayisi,angaryaSayisi);
paketArrayList.add(paket);
}
}
}
}); adapter.notifyDataSetChanged();
}
public void delete(View view){
for (int i=0;i<= paketArrayList.size();i++){
firebaseFirestore.collection(magaza).document(name).delete().addOnSuccessListener(new OnSuccessListener<Void>() {
#Override
public void onSuccess(Void unused) {
Toast.makeText(ListActivity.this,"SİLİNDİ",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ListActivity.this,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
});
}
in the application I made, the user selects the store from the spinner and in the other activity, the package information from that store appears. However, when I log in and switch to other activity, the data is not coming. When I go back and go again, the data appears. Does anyone know where I went wrong or what I should do?
public class LoginActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ActivityLoginBinding binding;
FirebaseAuth firebaseAuth;
String magaza;
Intent intenttoList;
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityLoginBinding.inflate(getLayoutInflater());
View view = binding.getRoot();
setContentView(view);
intent = new Intent(LoginActivity.this,ListActivity.class);
Intent gelenintent = getIntent();
String email =gelenintent.getStringExtra("email");
if (email.equals("")){
}else {
binding.username.setText(email);
}
binding.spinner.setOnItemSelectedListener(this);
firebaseAuth = FirebaseAuth.getInstance();
intenttoList = new Intent(LoginActivity.this,ListActivity.class);
magaza="";
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,R.array.magazaList,R.layout.support_simple_spinner_dropdown_item);
binding.spinner.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
public void logIn(View view){
if (magaza.equals("çöp")){
Toast.makeText(LoginActivity.this,"MAĞAZA SEÇMENİZ GEREKMEKTEDİR",Toast.LENGTH_LONG).show();
}else{
String username = binding.username.getText().toString();
String password = binding.passWord.getText().toString();
firebaseAuth.signInWithEmailAndPassword(username,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (adapterView.getItemAtPosition(i).toString().equals("MAĞAZA SEÇİN")){
Toast.makeText(LoginActivity.this,"MAĞAZA SEÇMENİZ GEREKLİDİR",Toast.LENGTH_LONG).show();
magaza ="çöp";
}else{
magaza =adapterView.getItemAtPosition(i).toString();
intent.putExtra("magaza",magaza);
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
Try this
firebaseAuth.signInWithEmailAndPassword(username,password).addOnSuccessListener(new OnSuccessListener<AuthResult>() {
#Override
public void onSuccess(AuthResult authResult) {
Intent intent = new Intent(this, ListActivity.class)
intent.putExtra("magaza",magaza);
startActivity(intent);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(LoginActivity.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
In the ListActivity.class call adapter.notifyDataSetChanged(); inside the addSnapshotListener callback.
firebaseFirestore.collection(magaza).addSnapshotListener(new EventListener<QuerySnapshot>() {
#Override
public void onEvent(#Nullable QuerySnapshot value, #Nullable FirebaseFirestoreException error) {
if (error!=null){
Toast.makeText(ListActivity.this,error.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}else if (value!=null){
for (DocumentSnapshot documentSnapshot:value.getDocuments()){
Map<String,Object> data = documentSnapshot.getData();
name = (String) data.get("name");
String paketSayisi = (String) data.get("paketSayisi");
String angaryaSayisi = (String) data.get("angaryaSayisi");
//FieldValue tarih = (FieldValue) data.get("tarih");
//String magaza = (String) data.get("magaza");
Paket paket = new Paket(name,paketSayisi,angaryaSayisi);
paketArrayList.add(paket);
}
adapter.notifyDataSetChanged();
}
}
});
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
public static final String ANONYMOUS = "anonymous";
public static final int RC_SIGN_IN = 1;
private static final int RC_PHOTO_PICKER = 2;
private String mUsername;
// Firebase instance variables
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference mMessagesDatabaseReference;
private ChildEventListener mChildEventListener;
private FirebaseAuth mFirebaseAuth;
private FirebaseAuth.AuthStateListener mAuthStateListener;
private FirebaseStorage mFirebaseStorage;
private StorageReference mChatPhotosStorageReference;
private FirebaseRemoteConfig mFirebaseRemoteConfig;
private RecyclerView recyclerView;
private FloatingActionButton floatingActionButton;
PhotosAdapter contactsAdapter;
List<Photos> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mUsername = ANONYMOUS;
recyclerView=(RecyclerView)findViewById(R.id.recyclerview);
floatingActionButton=(FloatingActionButton)findViewById(R.id.floatingactionbutton);
contactList = new ArrayList();
contactsAdapter=new PhotosAdapter(contactList,getApplicationContext());
// Initialize Firebase components
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseAuth = FirebaseAuth.getInstance();
mFirebaseStorage = FirebaseStorage.getInstance();
mFirebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
mMessagesDatabaseReference = mFirebaseDatabase.getReference().child("messages");
mChatPhotosStorageReference = mFirebaseStorage.getReference().child("chat_photos");
mAuthStateListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
onSignedInInitialize(user.getDisplayName());
} else {
// User is signed out
onSignedOutCleanup();
startActivityForResult(
AuthUI.getInstance()
.createSignInIntentBuilder()
.setIsSmartLockEnabled(false)
.setProviders(
AuthUI.EMAIL_PROVIDER,
AuthUI.GOOGLE_PROVIDER)
.build(),
RC_SIGN_IN);
}
}
};
recyclerView.setAdapter(contactsAdapter);
recyclerView.setLayoutManager(new GridLayoutManager(getApplicationContext(),5));
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/jpeg");
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), RC_PHOTO_PICKER);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RC_SIGN_IN) {
if (resultCode == RESULT_OK) {
// Sign-in succeeded, set up the UI
Toast.makeText(this, "Signed in!", Toast.LENGTH_SHORT).show();
} else if (resultCode == RESULT_CANCELED) {
// Sign in was canceled by the user, finish the activity
Toast.makeText(this, "Sign in canceled", Toast.LENGTH_SHORT).show();
finish();
}
}else if (requestCode == RC_PHOTO_PICKER && resultCode == RESULT_OK) {
Uri selectedImageUri = data.getData();
// Get a reference to store file at chat_photos/<FILENAME>
StorageReference photoRef = mChatPhotosStorageReference.child(selectedImageUri.getLastPathSegment());
// Upload file to Firebase Storage
photoRef.putFile(selectedImageUri)
.addOnSuccessListener(this, new OnSuccessListener<UploadTask.TaskSnapshot>() {
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// When the image has successfully uploaded, we get its download URL
Uri downloadUrl = taskSnapshot.getDownloadUrl();
// Set the download URL to the message box, so that the user can send it to the database
Photos friendlyMessage = new Photos(downloadUrl.toString());
mMessagesDatabaseReference.push().setValue(friendlyMessage);
}
});
}
}
#Override
protected void onResume() {
super.onResume();
mFirebaseAuth.addAuthStateListener(mAuthStateListener);
}
#Override
protected void onPause() {
super.onPause();
if (mAuthStateListener != null) {
mFirebaseAuth.removeAuthStateListener(mAuthStateListener);
}
}
private void onSignedInInitialize(String username) {
mUsername = username;
attachDatabaseReadListener();
}
private void onSignedOutCleanup() {
mUsername = ANONYMOUS;
}
private void attachDatabaseReadListener() {
if (mChildEventListener == null) {
mChildEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Photos friendlyMessage = dataSnapshot.getValue(Photos.class);
contactsAdapter.add(friendlyMessage);
}
public void onChildChanged(DataSnapshot dataSnapshot, String s) {}
public void onChildRemoved(DataSnapshot dataSnapshot) {}
public void onChildMoved(DataSnapshot dataSnapshot, String s) {}
public void onCancelled(DatabaseError databaseError) {}
};
mMessagesDatabaseReference.addChildEventListener(mChildEventListener);
}
}
}
PhotosAdapter
public class PhotosAdapter extends RecyclerView.Adapter<PhotosAdapter.MyViewHolder> {
private List<Photos> photosList;
private Context context;
public static final String Position="AdapterPosition";
public PhotosAdapter(List<Photos> contactsList, Context context) {
this.photosList = contactsList;
this.context = context;
}
#Override
public PhotosAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item, null);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder(PhotosAdapter.MyViewHolder holder, int position) {
Photos contacts = photosList.get(position);
Glide.with(context).load(contacts.getPhotoUrl()).into(holder.contactimageView);
}
#Override
public int getItemCount() {
return photosList.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
public ImageView contactimageView;
private final Context context;
public MyViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
contactimageView = (ImageView) itemView.findViewById(R.id.imageview);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
/* Intent intent = new Intent(context, ChatActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(Position,getAdapterPosition());
context.startActivity(intent);*/
}
public void add(Photos photos){
photosList.add(photos);
}
}
Photos
public class Photos {
private String photoUrl;
public Photos() {
}
public Photos(String photoUrl) {
this.photoUrl = photoUrl;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
This is my code. I am uploading an image on click of FloatingAction button to Firebase Storage.The image gets uploaded successfully, but I am not able to retrieve the image to the ImageView of my RecyclerView. What am I doing wrong? I am also able to see url of image in Storage.Still not able to retrieve message in imageview of recyclerview. Please help.......
you can try this also:-
yourFragment.isResumed()
My Database in firebase is in this format
I need that if a user login then for that particular UID I need his associated department name. So How to take the department name as a String.I use this code to fetch department name
String u_id=auth.getCurrentUser().getUid();
mdatabase=FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
user=mdatabase.getKey();
By this i don't get the result.Please provide solution
public class LoginPage extends AppCompatActivity {
private Button btnLogin;
private TextView ForgetText;
private EditText userText,PassText;
private String UserEmail,UserPassword;
private FirebaseAuth auth;
private FirebaseAuth.AuthStateListener mAuthlistener;
private ProgressBar progressBar;
private DatabaseReference mdatabase;
public String departmental;
//private Spinner dropdown;
Variables v=new Variables();
private String username,user;
private Intent i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_page);
auth=FirebaseAuth.getInstance();
btnLogin=(Button)findViewById(R.id.btn_login);
ForgetText=(TextView)findViewById(R.id.textView3);
userText=(EditText)findViewById(R.id.email2);
PassText=(EditText)findViewById(R.id.password2);
progressBar=(ProgressBar)findViewById(R.id.progressBar2);
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SignIn();
}
});
ForgetText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(LoginPage.this,ForgotPassword.class));
}
});
}
public void SignIn(){
UserEmail=userText.getText().toString().trim();
UserPassword=PassText.getText().toString().trim();
if (UserEmail.isEmpty()){
Toast.makeText(LoginPage.this,"Please Enter the Email
Id",Toast.LENGTH_LONG).show();
}
else if (UserPassword.isEmpty())
{
Toast.makeText(LoginPage.this,"Please enter Valid
Password",Toast.LENGTH_LONG).show();
}
else {
auth.signInWithEmailAndPassword(UserEmail, UserPassword)
.addOnCompleteListener(LoginPage.this, new
OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If
sign in succeeds
// the auth state listener will be notified and logic
to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
// there was an error
Toast.makeText(LoginPage.this,"Error in
logging!!",Toast.LENGTH_LONG).show();
} else
{
if(FirebaseAuth.getInstance().getCurrentUser().getEmail().equals(v.admin))
startActivity(new
Intent(LoginPage.this,AdminUser.class));
else {
String u_id =
auth.getInstance().getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Toast.makeText(LoginPage.this,u_id,Toast.LENGTH_LONG).show();
Toast.makeText(LoginPage.this,departmental,Toast.LENGTH_LONG).show();
/*i = new Intent(LoginPage.this, LoggedIn.class);
i.putExtra("hello_user",department);
startActivity(i);*/
}
Toast.makeText(LoginPage.this, "Logged In", Toast.LENGTH_LONG).show();
}
}
});
}
}
#Override
public void onBackPressed() {
super.onBackPressed();
}
}
Please use this code:
String u_id = auth.getCurrentUser().getUid();
mdatabase = FirebaseDatabase.getInstance().getReference().child("Users").child(u_id).child("department");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String department = (String) dataSnapshot.getValue();
Log.d("TAG", department);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
mdatabase.addListenerForSingleValueEvent(eventListener);
Hope it helps.
I'm currently working on a chat apps using Firebase. For Firebase auth, I'm using getImageUrl() to get image Uri from Firebase User,
but Picasso Library does not load any image to show also not getting any error, but when I use Direct link, it works perfectly.
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseUser User;
private ImageView profileImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
User = mAuth.getCurrentUser();
profileImg= (ImageView) findViewById(R.id.profileImage);
mAuthListener = new FirebaseAuth.AuthStateListener() {
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
TextView name = (TextView) findViewById(R.id.profilenameTv);
name.setText(user.getDisplayName());
profileImg = (ImageView) findViewById(R.id.profileImage);
Picasso.with(getApplicationContext()).load(user.getPhotoUrl()).fit().centerCrop().into(profileImg);
}else{
// User is signed out
startActivity(new Intent(getApplicationContext(),Signup.class));
}
}
};
}
Here is my EditProfile class:
public class editProfile extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mDatabase;
private DatabaseReference mRef;
private StorageReference mStorage;
private FirebaseUser User;
private Button submitBtn, changePassBtn, deleteBtn;
private ImageButton addProImage;
private EditText UsernameEt, currentPassEt, newPassEt ;
int REQUEST_CODE = 1;
private Uri PhotoDownloadUri ;
private Uri photoUri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_profile);
//firebase initilation
mAuth = FirebaseAuth.getInstance();
mStorage = FirebaseStorage.getInstance().getReference();
mDatabase = FirebaseDatabase.getInstance();
mRef = mDatabase.getReference();
User = mAuth.getCurrentUser();
//View initialization
//EditText
UsernameEt= (EditText) findViewById(R.id.usernameEt);
currentPassEt = (EditText) findViewById(R.id.curentPass);
newPassEt = (EditText) findViewById(R.id.newPass);
//Button
submitBtn = (Button) findViewById(R.id.sumitBtn);
changePassBtn = (Button) findViewById(R.id.ChangePassBtn);
deleteBtn = (Button) findViewById(R.id.deleteBtn);
//imageButton
addProImage = (ImageButton) findViewById(R.id.addProImg);
//add photo on start
Picasso.with(getApplicationContext()).load(User.getPhotoUrl()).fit().centerCrop().into(addProImage);
// request permission
requestPermission();
// open gallery
openGallery();
// delete mStorage data
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(User.getPhotoUrl() == PhotoDownloadUri){
mStorage.child("UserPhoto").child(photoUri.getLastPathSegment()).delete().addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
//photo replaced with default photo
addProImage.setImageDrawable(getDrawable(R.mipmap.ic_launcher));
Toast.makeText(getApplicationContext(), " Photo deleted Successfully ", Toast.LENGTH_SHORT).show();
}
}
});
}
}
});
// Add update user profile info
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Name =UsernameEt.getText().toString().trim();
String Photouri = PhotoDownloadUri.toString();
// Calling method
updateUserProfileInfo(Name,Photouri);
}
});
}//onCreate end here
#Override
protected void onStart() {
super.onStart();
}
//method for open gallery
private void openGallery(){
//image Button getting gallery intent
addProImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryPickIntent = new Intent(Intent.ACTION_PICK);
galleryPickIntent.setType("image/*");
startActivityForResult(galleryPickIntent,REQUEST_CODE);
}
});
}
//request permittion
private void requestPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE);
} else {
openGallery();
}
}
//on Activity result
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==REQUEST_CODE || requestCode ==RESULT_OK){
photoUri = data.getData();
// add photo to imageView
addProImage.setImageURI(photoUri);
//
//upload photo in firebase database
//
mStorage.child("UserPhoto").child(photoUri.getLastPathSegment()).putFile(photoUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
PhotoDownloadUri = taskSnapshot.getDownloadUrl();
Toast.makeText(getApplicationContext(), "successfully uploaded ", Toast.LENGTH_SHORT).show();
}
});
mStorage.child("UserPhoto").child(photoUri.getLastPathSegment()).getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//PhotoDownloadUri = uri;
}
});
}
}
//checking gallery permission
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
openGallery();
}
}
//update user profile info name and photo
public void updateUserProfileInfo(String name, String photoUri){
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(Uri.parse(photoUri))
.build();
User.updateProfile(profileUpdates)
.addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
//setting user profile data to firebase database
mRef.child("Users").child(User.getUid()).child("username").setValue(User.getDisplayName());
mRef.child("Users").child(User.getUid()).child("photouri").setValue(User.getPhotoUrl());
mRef.child("Users").child(User.getUid()).child("uid").setValue(User.getUid());
Toast.makeText(getApplicationContext(), " Profile Update Successful ", Toast.LENGTH_SHORT).show();
// add photo to edit
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
}
});
}
}
Screenshot of my result:
Try
String url = user.getPhotoUrl(); //"gs://bucket/images/stars.jpg"
// Create a reference to a file from a Google Cloud Storage URI
StorageReference gsReference = storage.getReferenceFromUrl(url);
gsReference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
// handle success
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle any errors
}
});