data is not sent to firebase storage how to fix? - android

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.

Related

How to associate each Firebase user with their own recyclerView Data

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");

I need to get user image from firebase to show it on ViewHolder after user uplaoded thier image in profile activity

I have a profile activity that user upload their profile images, user uploads 2 images ( back and front) the images are showing fine in the profile activity, but I also want to show one of this image (back or front) in another activity ( ViewHolder activity ). I have tried many things but couldn't figure out as i am only testing how firebase works, I really appreciate if someone can help me here.
Here is my profile activity where user upload images to firebase.
public class ProfileActivity extends AppCompatActivity implements View.OnClickListener{
private ImageView backimage;
private CircleImageView profileimage;
TextView totalscore,correctattempts,totalattempts,user_name,java_score,python_score,php_score,android_score,phone_number;
private Uri filepath;
private final int PICK_IMAGE_REQUEST = 71;
private int id;
StorageReference storageReference;
DatabaseReference users,defaultimages,scoretbl;
String Storage_Path = "All_Image_Uploads/";
// Root Database Name for Firebase Database.
public static final String Database_Path = "All_Image_Uploads_Database";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_profile);
storageReference = FirebaseStorage.getInstance().getReference();
users = FirebaseDatabase.getInstance().getReference("Users");
defaultimages = FirebaseDatabase.getInstance().getReference("Database_Path");
java_score=findViewById(R.id.javascore);
phone_number=findViewById(R.id.user_phonenumber);
python_score=findViewById(R.id.pythonscore);
php_score=findViewById(R.id.phpscore);
android_score =findViewById(R.id.androidscore);
backimage = findViewById(R.id.header_cover_image);
profileimage=findViewById(R.id.user_profile_photo);
totalattempts=findViewById(R.id.questionsattempted);
correctattempts=findViewById(R.id.correctattempts);
totalscore=findViewById(R.id.totalscore);
user_name =findViewById(R.id.user_profile_name);
backimage.setOnClickListener(this);
profileimage.setOnClickListener(this);
user_name.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
user_name.setText(Common.currentUser.getUserName());
phone_number.setText(Common.currentUser.getEmail());
users.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
/* String score=dataSnapshot.child(Common.currentuser.getUsername()).child("totalScore").getValue().toString();
totalscore.setText(score);
String tattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("questionsAttempted").getValue().toString();
totalattempts.setText(tattempts);
String cattempts=dataSnapshot.child(Common.currentuser.getUsername()).child("correctAttempts").getValue().toString();
correctattempts.setText(cattempts);
phone_number.setText(Common.currentuser.getEmail());
*/
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtobackimage").getValue().toString())
.into(backimage);
Picasso.with(getBaseContext()).load(dataSnapshot.child(Common.currentUser.getUserName()).child("pathtoprofileimage").getValue().toString())
.into(profileimage);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
/*
scoretbl.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.child("Java").exists())
java_score.setText(dataSnapshot.child("Java").child("score").getValue().toString());
if(dataSnapshot.child("Python").exists())
python_score.setText(dataSnapshot.child("Python").child("score").getValue().toString());
if(dataSnapshot.child("PHP").exists())
php_score.setText(dataSnapshot.child("PHP").child("score").getValue().toString());
if(dataSnapshot.child("Android").exists())
android_score.setText(dataSnapshot.child("Android").child("score").getValue().toString());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
*/
}
private void chooseImage() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,PICK_IMAGE_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST&&resultCode ==RESULT_OK
&& data !=null && data.getData()!= null){
filepath = data.getData();
if(id==R.id.header_cover_image)
Picasso.with(this).load(filepath).into(backimage);
else
Picasso.with(this).load(filepath).into(profileimage);
}
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.header_cover_image:{
id = R.id.header_cover_image;
chooseImage();
uploadImageback();
break;
}
case R.id.user_profile_photo:{
id = R.id.user_profile_photo;
chooseImage();
uploadImageprofile();
break;
}
}
}
private void uploadImageback() {
final StorageReference backref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"back");
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading..");
progressDialog.show();
backref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
backref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtobackimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+"%");
}
});
}
}
private void uploadImageprofile() {
if(filepath!=null){
final ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.setTitle("Uploading.. ");
progressDialog.show();
final StorageReference profileref = storageReference.child("images/").
child(Common.currentUser.getUserName()+"/"+ Common.currentUser.getUserName()+"profile");
profileref.putFile(filepath).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
progressDialog.dismiss();
profileref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
users.child(Common.currentUser.getUserName()).child("pathtoprofileimage").setValue(uri.toString());
Toast.makeText(ProfileActivity.this,"Profile Uploaded",Toast.LENGTH_LONG).show();
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(ProfileActivity.this,"Profile not Uploaded",Toast.LENGTH_LONG).show();
}
});
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
progressDialog.dismiss();
Toast.makeText(ProfileActivity.this,"Failure",Toast.LENGTH_LONG).show();
}
}).addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress = (100.0*taskSnapshot.getBytesTransferred()/taskSnapshot.getTotalByteCount());
progressDialog.setMessage("Uploaded "+(int)progress+" %");
}
});
}
}
}
and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity
public class RankingViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView name_text,score_text;
private ItemClickListener itemClickListener;
public RankingViewHolder(View itemView) {
super(itemView);
name_text = (TextView) itemView.findViewById(R.id.name_text);
score_text = (TextView) itemView.findViewById(R.id.score_text);
itemView.setOnClickListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
}
and the Fragment activity
public class RankingFragment extends Fragment {
View myFragment;
FirebaseDatabase database;
RecyclerView rankingList;
LinearLayoutManager layoutManager;
FirebaseRecyclerAdapter<Ranking,RankingViewHolder> adapter;
DatabaseReference questionScore,rankingTable;
int sum = 0; //score is default by zero
public static RankingFragment newInstance(){
RankingFragment rankingFragment = new RankingFragment();
return rankingFragment ;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
database = FirebaseDatabase.getInstance();
questionScore = database.getReference("Question_Score");
rankingTable = database.getReference("Ranking");
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myFragment = inflater.inflate(R.layout.fragment_ranking,container,false);
rankingList = (RecyclerView) myFragment.findViewById(R.id.ranking_list);
layoutManager = new LinearLayoutManager(getActivity());
rankingList.setHasFixedSize(true);
//Using orderByChild method , this will sort the ranking in ascending order
//reverse the data by using layout manager
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
rankingList.setLayoutManager(layoutManager);
updateScore(Common.currentUser.getUserName(), new RankingCallBack<Ranking>() {
#Override
public void callBack(Ranking ranking) {
//Ranking Score update
rankingTable.child(ranking.getUserName())
.setValue(ranking);
// showRanking();
}
});
adapter = new FirebaseRecyclerAdapter<Ranking, RankingViewHolder>(
Ranking.class,
R.layout.ranking_layout,
RankingViewHolder.class,
rankingTable.orderByChild("score")
) {
#Override
protected void populateViewHolder(RankingViewHolder viewHolder, final Ranking model, int position) {
viewHolder.name_text.setText(model.getUserName());
viewHolder.score_text.setText(String.valueOf(model.getScore()));
//prevent crash when user click
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
Intent scoreDetail = new Intent(getActivity(),Score_Detail.class);
scoreDetail.putExtra("viewUser",model.getUserName());
startActivity(scoreDetail);
}
});
}
};
adapter.notifyDataSetChanged();
rankingList.setAdapter(adapter);
return myFragment;
}
private void updateScore(final String userName, final RankingCallBack<Ranking> callBack) {
questionScore.orderByChild("user").equalTo(userName)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot data:dataSnapshot.getChildren())
{
Question_Score quest = data.getValue(Question_Score.class);
sum += Integer.parseInt(quest.getScore());
}
Ranking ranking = new Ranking(userName,sum);
callBack.callBack(ranking);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
and here is my Ranking class
public class Ranking {
private String userName;
private long score;
private String urlProfilePic;
public Ranking(){
}
public Ranking(String userName, long score, String pathtobackimage ) {
this.userName = userName;
this.score = score;
this.urlProfilePic = pathtobackimage;
}
public String getUrlProfilePic() {
return urlProfilePic;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
}
Here the screen shot to help more how I wanted
I put my comment in answer field because of this restriction: 'You must have 50 reputation to comment'.
Anyway, back to your question. One solution would be to save the current user 'key' to a SharedPreference file. In your new Activity, use that 'key' to retrieve the data from Firebase.
EDIT: Added solution
Quoted: "...and I want to show one of these image in my ViewHolder activity as you can see the text view (name and score are showing) which is coming from a ranking Fragment activity..."
Solution: Search for fixme. In RankingViewHolder class, add:
public class RankingViewHolder extends ...
//...
public TextView name_text, score_text;
public ImageView profileImageView; //fixme
//...
public RankingViewHolder(View itemView) {
//...
score_text = (TextView) itemView.findViewById(R.id.score_text);
profileImageView = (ImageView) itemView.findViewById(R.id.profile_image_view); //fixme
//...
Inside populateViewHolder()
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext()) //fixme
.load(Common.currentUser.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView); //fixme
Inside RankingFragment class, since you are already using Common.currentUser.getUserName(), might as well create another variable under it to store the url link to the user's profile picture, and retrieve the link via Common.currentUser.getUrlProfilePic().
EDIT#2:
The images stored in FB storage have this links:
gs://FIXME_FIREBASE.com/images/userName/userNameback.jpeg
gs://FIXME_FIREBASE.com/images/userName/userNameprofile.jpeg
However to use in Picasso, need this kind of links:
https://firebasestorage.googleapis.com/v0/b/FIXME/o/FIXME/images/userName/userNameback.jpeg?alt=media&token=FIXME
Question is how to get that?
One solution is that after you successfully upload the image, get the download url (example below).
The tricky part is that the download url is not immediately available, and you have to use .getMetadata(), .getDownloadUrl() to do that.
Once the url is received, you have to figure out how to save this link to the user's profile in your FB database.
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
StorageMetadata storageMetadata = taskSnapshot.getMetadata();
StorageReference reference = storageMetadata.getReference();
reference.getDownloadUrl() // Get the download URL for the file
.addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
Log.i(TAG, uri.toString()); //fixme: save this to user's profile
}
});
}
Inside populateViewHolder, you are using Ranking model that contains the username and score.
Modify that Ranking model class to add an additional String variable urlProfilePic that contains the url to the user's image (above result), and generate the getter for it called getUrlProfilePic(). Then you can use it in this way inside the populateViewHolder:
viewHolder.score_text.setText(String.valueOf(model.getScore()));
Picasso.with(getContext())
.load(model.getUrlProfilePic()) //fixme
.into(viewHolder.profileImageView);

The items not appear in recyclerview

I face a problem when I send a comment, that comment does not appear in RecyclerView, I have to go back and reopen Activity again to see my reply.
BlogSingleActivity.java
public class BlogSingleActivity extends AppCompatActivity {
private String mPost_key = null;
DatabaseReference mDatabase;
private ImageView mBlogSingleImage;
private TextView mBlogSingleTitle;
private TextView mBlogSingleDesc;
private TextView mBlogSingleUsername, mNumbersOfComments;
private TextView mBlogSingleDate;
private DatabaseReference ReplayDatabase;
private RecyclerView mReplayBlogList;
private TextView emptyView;
FirebaseRecyclerAdapter<Blog, BlogViewHolder> mAdapter;
private EditText mReplayText;
private FirebaseAuth mAuth;
private FirebaseUser mCurrentUser;
private DatabaseReference mDatabaseUser;
private Uri mImagUri = null;
private static final int GALLERY_REQUEST = 2;
private StorageReference mStorage;
private ImageButton mselectImage;
Button sendBTN;
private ProgressDialog mProgress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blog_single);
mPost_key = getIntent().getExtras().getString("blog_id");
mDatabase = FirebaseDatabase.getInstance().getReference().child("Blog");
ReplayDatabase = FirebaseDatabase.getInstance().getReference().child("Replay");
mBlogSingleDesc = findViewById(R.id.singleBlogDesc);
mBlogSingleTitle = findViewById(R.id.post_Tittle);
mBlogSingleImage = findViewById(R.id.singleBlogImage);
mBlogSingleUsername = findViewById(R.id.singleBlogUsername);
mBlogSingleDate = findViewById(R.id.singleBlogDate);
mNumbersOfComments = findViewById(R.id.numberofcomments);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mReplayBlogList = findViewById(R.id.replay_blog_list);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
layoutManager.setReverseLayout(true);
layoutManager.setStackFromEnd(true);
mReplayBlogList.setLayoutManager(layoutManager);
mReplayBlogList.setNestedScrollingEnabled(false);
emptyView = findViewById(R.id.empty_view);
chickitem();
mAuth = FirebaseAuth.getInstance();
mCurrentUser = mAuth.getCurrentUser();
mDatabaseUser = FirebaseDatabase.getInstance().getReference().child("Users").child(mCurrentUser.getUid());
mReplayText = findViewById(R.id.ReplayField);
mStorage = FirebaseStorage.getInstance().getReference();
mselectImage = findViewById(R.id.replayImageSelect);
sendBTN = findViewById(R.id.send_BTN);
getfirebaseData();
mProgress = new ProgressDialog(this);
mselectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, GALLERY_REQUEST);
}
});
sendBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startReplay();
getfirebaseData();;
disappearKeyboard();
mReplayText.getText().clear();
mselectImage.setImageResource(R.mipmap.add_btn);
mselectImage.setBackgroundColor(getResources().getColor(R.color.image_background_color));
}
});
mDatabase.child(mPost_key).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String post_title = (String) dataSnapshot.child("tittle").getValue();
String post_desc = (String) dataSnapshot.child("desc").getValue();
String post_image = (String) dataSnapshot.child("image").getValue();
String post_username = (String) dataSnapshot.child("username").getValue();
Object post_date = dataSnapshot.child("date").getValue();
Blog timeStamp = new Blog();
timeStamp.setDate(post_date);
if (timeStamp.getDate() != null) {
String datee = timeStamp.getDate().toString();
long time = Long.parseLong(datee);
String timeAgo = TimeAgo.getTimeAgo(time);
mBlogSingleDate.setText(timeAgo);
}
mBlogSingleTitle.setText(post_title);
mBlogSingleDesc.setText(post_desc);
mBlogSingleUsername.setText(post_username);
Picasso.with(BlogSingleActivity.this)
.load(post_image)
.into(mBlogSingleImage);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void disappearKeyboard() {
InputMethodManager inputManager =
(InputMethodManager) this.
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
this.getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
private void startReplay() {
{
final String replay_val = mReplayText.getText().toString().trim();
//send date to firebase database
if (!TextUtils.isEmpty(replay_val) && mImagUri != null) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
StorageReference filepath = mStorage.child("Replay_Images").child(mImagUri.getLastPathSegment());
filepath.putFile(mImagUri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
if (mAuth.getCurrentUser() != null) {
#SuppressWarnings("VisibleForTests") final Uri downloadUrl = taskSnapshot.getDownloadUrl();
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replayimage").setValue(downloadUrl.toString());
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
});
} else if ((!TextUtils.isEmpty(replay_val))) {
mProgress.setMessage("جاري الإرسال....");
mProgress.show();
if (mAuth.getCurrentUser() != null) {
final DatabaseReference newPost = ReplayDatabase.child(mPost_key).push();
mDatabaseUser.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() != null) {
newPost.child("replay").setValue(replay_val);
newPost.child("replaydate").setValue(ServerValue.TIMESTAMP);
newPost.child("uid").setValue(mCurrentUser.getUid());
newPost.child("replayname").setValue(dataSnapshot.child("name").getValue()).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()) {
chickitem();
mAdapter.notifyDataSetChanged();
}
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mProgress.dismiss();
}
}
}
}
private void getfirebaseData() {
mAdapter = new FirebaseRecyclerAdapter<Blog, BlogViewHolder>(
Blog.class,
R.layout.replay_row,
BlogViewHolder.class,
ReplayDatabase.child(mPost_key)
) {
#Override
protected void populateViewHolder(final BlogViewHolder viewHolder, final Blog model, int position) {
viewHolder.setReplay(model.getReplay());
viewHolder.setReplayname(model.getReplayname());
viewHolder.setReplaydate(model.getReplaydate());
viewHolder.setReplayimage(getApplicationContext(), model.getReplayimage());
}
};
mReplayBlogList.setAdapter(mAdapter);
}
public static class BlogViewHolder extends RecyclerView.ViewHolder {
View mView;
ImageView replay_imagee;
TextView recive_replay, post_replayname, post_replaydate;
public BlogViewHolder(View itemView) {
super(itemView);
mView = itemView;
}
public void setReplay(String replay) {
recive_replay = mView.findViewById(R.id.replay_text);
recive_replay.setText(replay);
}
public void setReplayname(String replayname) {
post_replayname = mView.findViewById(R.id.replayer_name_field);
post_replayname.setText(replayname);
}
public void setReplaydate(Object relaydate) {
post_replaydate = mView.findViewById(R.id.post_replaydate);
Blog timeStamps = new Blog();
timeStamps.setDate(relaydate);
if (timeStamps.getDate()!=null){
String dateee = timeStamps.getDate().toString();
long times = Long.parseLong(dateee);
String timeAgoo = TimeAgo.getTimeAgo(times);
post_replaydate.setText(timeAgoo);
}
}
public void setReplayimage(final Context ctx, final String replayimage) {
replay_imagee = mView.findViewById(R.id.replay_image);
Picasso.with(ctx).load(replayimage).networkPolicy(NetworkPolicy.OFFLINE).into(replay_imagee, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError() {
Picasso.with(ctx).load(replayimage).into(replay_imagee);
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_REQUEST && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
CropImage.activity(imageUri)
.setGuidelines(CropImageView.Guidelines.ON)
.setAspectRatio(1, 1)
.start(this);
}
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
mImagUri = result.getUri();
mselectImage.setImageURI(mImagUri);
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
Exception error = result.getError();
}
}
}
private void chickitem() {
final AtomicInteger count = new AtomicInteger();
ReplayDatabase.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
long numChildren = dataSnapshot.child(mPost_key).getChildrenCount();
if (numChildren == 0) {
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("لا توجد تعليقات");
mReplayBlogList.setVisibility(View.INVISIBLE);
mNumbersOfComments.setText("لا توجد تعليقات");
} else {
mNumbersOfComments.setText("" + numChildren);
emptyView.setVisibility(View.VISIBLE);
emptyView.setText("التعليقات...");
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
#Override
public void onStart(){
super.onStart();
getfirebaseData();
}
#Override
public void onResume(){
super.onResume();
getfirebaseData();
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The screen looks like .
There are two comments. To see these comment I have to go back and reopen this Activity.
I'm not 100% sure about this, but I think you're missing the mReplayBlogList.notifyDataSetChanged(); after the line mReplayBlogList.setAdapter(mAdapter); in getfirebaseData().
Maybe you could give it a try. Let me know if it solved :)

How to fetch the department name for a particular User from Firebase in Android

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.

Picasso Library image loading not working with Firebase auth.getCurentUser.getPhotoUrl

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
}
});

Categories

Resources