The image does not display Firebase Storage - android

what am I doing wrong? In this code, I load the image into Firebase Storage and then try to display it. But for some reason the display does not work. It loads it to Storage, but does not want to display it. Can Uri not take it right? As for me, for some reason, the red line underlines this line:
downloadUrl = taskSnapshot.getDownloadUrl();
What's wrong here?
public class EditProfile extends Fragment{
private static final int GALLERY_INTENT=2;
private EditText editProfileName;
private EditText editProfilePhone;
private EditText editProfileNick;
private ImageView image;
private Uri downloadUrl;
private Button saveBtn;
private final int LENGTH = 1000;
private FirebaseUser user;
private ProgressDialog progressDialog;
public EditProfile() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View v = inflater.inflate(R.layout.fragment_edit_profile, container, false);
image=(ImageView)v.findViewById(R.id.edit_profile_photo);
user= FirebaseAuth.getInstance().getCurrentUser();
editProfileName=(EditText)v.findViewById(R.id.edit_profile_name);
editProfilePhone=(EditText)v.findViewById(R.id.edit_profile_phone);
saveBtn=(Button)v.findViewById(R.id.edit_profile_save);
progressDialog = new ProgressDialog(getContext());
saveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
chageProfile();
}
});
image.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setImage();
}
});
return v;
}
public void setImage(){
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent,GALLERY_INTENT);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==GALLERY_INTENT && resultCode==RESULT_OK){
progressDialog.setTitle("Uploading");
progressDialog.show();
Uri uri = data.getData();
StorageReference storageReference=FirebaseStorage.getInstance().getReference();
StorageReference file=storageReference.child(user.getUid()+"/photo.jpg");
file.putFile(uri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
// Get a URL to the uploaded content
downloadUrl = taskSnapshot.getDownloadUrl();
UserProfileChangeRequest profileUpdates = new UserProfileChangeRequest.Builder()
.setPhotoUri(downloadUrl)
.build();
user.updateProfile(profileUpdates).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
progressDialog.dismiss();
Toast.makeText(getApplicationContext(),"Фото добавлено",Toast.LENGTH_SHORT).show();
}
});
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception exception) {
// Handle unsuccessful uploads
// ...
}
});
}
image.setImageURI(user.getPhotoUrl());
}
}

Related

Not able to upload image on real time database, working in fragments in android studio

public class statusFragment extends Fragment {
//StatusfragmentBinding binding;
TopStatusAdapter statusAdapter;
ArrayList<UserStatus> userStatuses;
///we are creating customize fragment where first layut is created then class creat to attach then to the activities by creating classes while in simple activities creation both layout and activity is created at same time
ImageButton camerastatus;
RecyclerView statusList;
ProgressDialog dialog;
// for uploading
FirebaseDatabase database;
private FirebaseStorage firebaseStorage;
private StorageReference storageReference;
private FirebaseAuth firebaseAuth;
private static int PICK_IMAGE = 123;
private Uri imagepath;
private String ImageUriAcessToken;
userprofile user; //user obj
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.statusfragment,container,false);
dialog = new ProgressDialog(getContext());
dialog.setMessage("Uploading Image...");
dialog.setCancelable(false);
//like specific
database= FirebaseDatabase.getInstance();
userStatuses= new ArrayList<>();//need to remove from TopstatusAdapter
statusList = view.findViewById(R.id.statusList);
camerastatus= view.findViewById(R.id.camerastatus);
statusAdapter= new TopStatusAdapter(getContext(),userStatuses);
LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
layoutManager.setOrientation(RecyclerView.VERTICAL);
statusList.setLayoutManager(layoutManager);
statusList.setAdapter(statusAdapter);
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
//before like video
database.getReference().child("status").child(firebaseAuth.getUid())
.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
user = snapshot.getValue(userprofile.class);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
camerastatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//before:
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(intent, 75);
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode,#Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data != null) {
if(data.getData() != null) {
//firebase to upload data
FirebaseStorage storage = FirebaseStorage.getInstance();
Date date = new Date();
StorageReference reference = storage.getReference().child("SImages").child(firebaseAuth.getUid()).child("Status Pic");
reference.putFile(data.getData()).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
#Override
public void onComplete(#NonNull Task<UploadTask.TaskSnapshot> task) {
if(task.isSuccessful()) {
reference.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
#Override
public void onSuccess(Uri uri) {
//dialog.dismiss();
UserStatus userStatus = new UserStatus();
userStatus.setName(user.getUsername());
userStatus.setLastUpdated(date.getTime());
HashMap<String,Object> obj=new HashMap<>();
obj.put("name", userStatus.getName());
obj.put("lastUpdated", userStatus.getLastUpdated());
String imageUrl = uri.toString();
Status status = new Status(imageUrl, userStatus.getLastUpdated());
database.getReference().child("status").child("stories").updateChildren(obj);
database.getReference().child("stories").child("status")
.child("stories")
.push()
.setValue(status);
}
});
}
}
});
}
}
}
}[image1[\]\[1\]][1]
[1]: https://i.stack.imgur.com/6eCEz.jpg
this is a status fragment , i want to make a module like WhatsApp status, here in the code above i am uploading the image on firebase storage that is working fine , image is being uploaded but in real-time database the image is not being uploaded.
I have attached the screenshot of my storage where data is being uploaded and also the screenshot of real time database where image is not being uploaded .

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

Image is not retrieved in ImageView of RecyclerView from Firebase

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()

Displaying images from Firebase DB that's stored in Firebase Storage

I am making a fitness android application and I am storing progress images of Users using the Firebase Storage. A reference to the Firebase Database is also made with the URL of the image thats found in Firebase Storage.
I am attempting to retrieve the images and show them in a GridLayout but am recieveing a 'Bound to Type Error'
I am displaying the images using a recyclerView.
I am also using Picasso to load the image.
Photo Activity
public class PhotosActivity extends BaseActivity {
#BindView(R.id.activity_photos_fab)
FloatingActionButton newPhoto;
private StorageReference mStorage;
private ProgressDialog mProgressDialog;
RecyclerView recyclerView;
FirebaseRecyclerAdapter adapter;
private static final int GALLERY_INTENT = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_photos);
ButterKnife.bind(this);
mStorage = FirebaseStorage.getInstance().getReference();
mProgressDialog = new ProgressDialog(this);
recyclerView = (RecyclerView) findViewById(R.id.activity_photos_recyclerView);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == GALLERY_INTENT && resultCode == RESULT_OK) {
mProgressDialog.setTitle("Uploading..");
mProgressDialog.show();
// Get the URI of the photo
Uri uri = data.getData();
StorageReference filepath = mStorage.child("Photos").child(userEmail).child(uri.getLastPathSegment());
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
// Add the photo to the database
// if successful then show a toast to say a photo has been added
filepath.putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
Toast.makeText(getApplicationContext(), "You added a photo", Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}
});
String photoURL = filepath.getDownloadUrl().toString();
bus.post(new PhotoService.AddPhotoRequest(photoURL, userEmail));
}
}
#Override
protected void onResume() {
super.onResume();
Firebase photosReference = new Firebase(Utils.FIRE_BASE_PHOTOS_REFERENCE + userEmail);
Query sortQuery = photosReference.orderByKey();
adapter = new FirebaseRecyclerAdapter<Photo, PhotoViewHolder>(Photo.class,
R.layout.list_individual_photo,
PhotoViewHolder.class,
sortQuery) {
#Override
protected void populateViewHolder(PhotoViewHolder photoViewHolder, Photo photo, int i) {
photoViewHolder.populate(PhotosActivity.this, photo);
}
};
GridLayoutManager layoutManager = new GridLayoutManager(getApplicationContext(), 4);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
}
#Override
protected void onPause() {
super.onPause();
adapter.cleanup();
}
#OnClick(R.id.activity_photos_fab)
public void setNewPhoto() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType("image/*");
startActivityForResult(intent, GALLERY_INTENT);
}
}
PhotoViewHolder
public class PhotoViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.list_individual_photo_imageView)
ImageView photoImage;
#BindView(R.id.list_individual_photo_progressBar)
ProgressBar photoProgressBar;
public PhotoViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void populate (Context context, Photo photo) {
itemView.setTag(photo);
Picasso.with(context).load(photo.getPhotoURl())
.fit()
.centerCrop()
.into(photoImage, new Callback() {
#Override
public void onSuccess() {
photoProgressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
}
});
}
}
LivePhotoService
public class LivePhotoService extends BaseLiveService {
#Subscribe
public void getPhotos(final PhotoService.GetPhotoRequest request) {
final PhotoService.GetPhotoResponse response = new PhotoService.GetPhotoResponse();
response.valueEventListener = request.firebase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
response.photo = dataSnapshot.getValue(Photo.class);
if(response.photo != null) {
bus.post(response);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(application.getApplicationContext(), firebaseError.getMessage(), Toast.LENGTH_LONG).show();
}
});
}
}
Photo Object
public class Photo {
private String photoID;
private String photoURl;
private HashMap<String, Object> photoDate;
private String ownerEmail;
public Photo(String photoID, String photoURl, HashMap photoDate, String ownerEmail) {
this.photoID = photoID;
this.photoURl = photoURl;
this.photoDate = photoDate;
this.ownerEmail = ownerEmail;
}
public String getPhotoID() {
return photoID;
}
public String getPhotoURl() {
return photoURl;
}
public HashMap getPhotoDate() {
return photoDate;
}
public String getOwnerEmail() {
return ownerEmail;
}
}
Consider using Firebase-UI Android library which gives you ability to load images from storage ref directly. In your case it would look something like this
I'm not sure if Picasso is supported but you can use Glide
For example:
mStorageRef = FirebaseStorage.getInstance().getReference();
Glide.with(this /* context */)
.using(new FirebaseImageLoader())
.load(mStorageRef + "/Photos/" + userId)
.error(R.drawable.default)
.into(imageView);

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