我想从我上传到Firebase的图片中获取DownloadUrl,但是当我稍后尝试加载时,我只会收到一个未找到的异常:
public class ProfileActivity extends AppCompatActivity{
private static final int CHOOSE_IMAGE = 200;
//Initialize items
EditText inputUsername, inputBirthday;
FloatingActionButton mainaction;
FloatingActionButton homeaction;
FloatingActionButton profileaction;
StorageReference profileimageRef;
String profileimageurl;
Button actionSaveProfile;
FirebaseAuth mAuth;
ProgressBar progressBar;
ImageView profileimage;
Boolean isfabopen;
Uri uriProfileImage;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
isfabopen = false;
mainaction = findViewById(R.id.fab_expand);
homeaction = findViewById(R.id.fab_home);
profileaction = findViewById(R.id.fab_profile);
inputUsername = findViewById(R.id.input_username);
inputBirthday = findViewById(R.id.input_birthday);
actionSaveProfile = findViewById(R.id.action_save_profile);
profileimage = findViewById(R.id.profile_image);
progressBar = findViewById(R.id.progressbar);
mAuth = FirebaseAuth.getInstance();
//Expand, collapse menu
mainaction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(!isfabopen)
{
ShowFab();
}else
{
CloseFab();
}
}
});
profileimage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showImageChooser();
}
});
homeaction.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
});
actionSaveProfile.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
saveUserData(v);
}
});
loadUserData();
}
private void loadUserData() {
FirebaseUser user = mAuth.getCurrentUser();
//If no profile picture found
if(user.getPhotoUrl() != null)
{
String photoUrl = user.getPhotoUrl().toString();
//Set profile picture
Glide.with(this)
.load(user.getPhotoUrl().toString())
.into(profileimage);
}
//If no username found
if(user.getDisplayName() != null)
{
String username = user.getDisplayName();
//Insert display name
inputUsername.setText(user.getDisplayName());
}
}
private void saveUserData(View v)
{
String name = inputUsername.getText().toString().trim();
String birthtday = inputBirthday.getText().toString().trim();
//Check if has content
if(name.isEmpty())
{
Snackbar.make(v, R.string.message_username_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputUsername.requestFocus();
}else if(birthtday.isEmpty()) {
Snackbar.make(v, R.string.message_birthday_empty, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
inputBirthday.requestFocus();
}
//Get user
FirebaseUser user = mAuth.getCurrentUser();
//Upload information
if(user != null && profileimageurl != null)
{
UserProfileChangeRequest profileChangeRequest = new UserProfileChangeRequest.Builder()
.setDisplayName(name)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
Log.wtf("ImageURL3", profileimageurl);
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
user.updateProfile(profileChangeRequest).addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
if(task.isSuccessful())
{
Toast.makeText(ProfileActivity.this, R.string.message_profile_updated, Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage(), Toast.LENGTH_SHORT).show();
}
}
});
}
}
//When got activity result from showImageChooser
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Check if result is ok
if(requestCode == CHOOSE_IMAGE && resultCode == RESULT_OK && data !=null && data.getData() != null)
{
//Save uri of image
uriProfileImage = data.getData();
try
{
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uriProfileImage);
profileimage.setImageBitmap(bitmap);
uploadToFirebase();
}catch (Exception ex)
{
ex.printStackTrace();
}
}
}
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
}
}
private void showImageChooser()
{
//Create chooser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
//Start chooser activity and wait for result
startActivityForResult(Intent.createChooser(intent, getString(R.string.label_profile_pic_chooser)), CHOOSE_IMAGE);
}
private void ShowFab() {
//Bool for menu open
isfabopen = true;
//Set buttons visible
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(135f);
//Expanding to top
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_100)).rotation(0f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_55)).rotation(0f);
}
private void CloseFab() {
//Bool for menu closed
isfabopen = false;
//Hide buttons
homeaction.setVisibility(View.VISIBLE);
profileaction.setVisibility(View.VISIBLE);
//Rotate main button
mainaction.animate().rotation(0f);
//Collapsing
homeaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
profileaction.animate().translationY(getResources().getDimension(R.dimen.standard_0)).rotation(135f);
}
//Check if user is logged in
@Override
protected void onStart() {
super.onStart();
//Check if user is already loggged in
if(mAuth.getCurrentUser() == null)
{
finish();
startActivity(new Intent(ProfileActivity.this, LoginActivity.class));
}
}
@Override
public void onBackPressed() {
super.onBackPressed();
//Go back to home activity
finish();
startActivity(new Intent(ProfileActivity.this, MainActivity.class));
}
}
XML代码:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<RelativeLayout
android:id="@+id/relativeLayout2"
android:layout_width="match_parent"
android:layout_height="200dp"
android:background="@color/colorPrimary"
android:backgroundTint="@color/colorPrimary"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/profile_image"
android:layout_width="156dp"
android:layout_height="156dp"
android:src="@drawable/camera_placeholder"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
<RelativeLayout
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/relativeLayout2">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:paddingLeft="@dimen/standard_23"
android:paddingRight="@dimen/standard_23">
<EditText
android:id="@+id/input_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorProfileAccent"
android:hint="@string/label_username"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="@color/colorProfileAccent"
android:textColorHint="@color/colorProfileAccent" />
<EditText
android:id="@+id/input_birthday"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorProfileAccent"
android:hint="@string/label_birthday"
android:inputType="textPersonName"
android:paddingBottom="15dp"
android:textColor="@color/colorProfileAccent"
android:textColorHint="@color/colorProfileAccent" />
<Button
android:id="@+id/action_save_profile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="7dp"
android:background="@drawable/rounded_btn_profile"
android:text="@string/apply_changes"
android:textColor="@color/colorProfileText" />
</LinearLayout>
<ProgressBar
android:id="@+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:visibility="gone" />
</RelativeLayout>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/coordinatorLayout"
android:layout_width="wrap_content"
android:layout_height="197dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent">
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_home"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_23"
android:rotation="90"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="@drawable/ic_home" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_profile"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/standard_23"
android:rotation="0"
android:translationY="@dimen/standard_55"
android:visibility="gone"
app:fabSize="mini"
app:srcCompat="@drawable/ic_account_box" />
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab_expand"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
app:fabSize="normal"
app:srcCompat="@drawable/ic_add" />
</android.support.design.widget.CoordinatorLayout>
</android.support.constraint.ConstraintLayout>
我只得到一个java.io.FileNotFoundException:没有这样的文件或目录异常。之前我尝试使用Success-Listener保存它,如下所示:https://stackoverflow.com/a/50743192/6274419。但这也没有奏效,因为较新的Firebase版本中不存在该功能。
一般情况下,我想显示一张个人资料图片和用户名,这些图片会保存到Firebase并在下次应用程序启动时检索。
提前致谢!
答案 0 :(得分:0)
在firebase中上传图片需要一些时间。因此,只有在图像完全保存在数据库中时才能检索图像。请调用OnSuccess中的loadUserData()方法,让我知道它是否有效。
private void uploadToFirebase() {
//Select destination filename, folder
profileimageRef = FirebaseStorage.getInstance().getReference("profilepictures/" + System.currentTimeMillis() + ".jpg");
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
@Override
public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
//Hide progressbar
progressBar.setVisibility(View.GONE);
//Check if was successful
if(task.isSuccessful())
{
//Set profile image url
profileimageurl = task.getResult().toString();
loadUserData();
Log.wtf("ImageURL2", profileimageurl);
}else
{
Toast.makeText(ProfileActivity.this, task.getException().getLocalizedMessage() , Toast.LENGTH_SHORT).show();
}
}
});
答案 1 :(得分:0)
现在使用另一个结构/方法解决它,使用UploadTask检索网址:
private void uploadToFirebase() {
FirebaseStorage storage = FirebaseStorage.getInstance();
StorageReference storageRef = storage.getReference();
//Select destination filename, folder
final StorageReference profileimageRef = storageRef.child("profilepictures/" + System.currentTimeMillis() + ".jpg");
UploadTask uploadTask = profileimageRef.putFile(uriProfileImage);
Log.wtf("ImageURL", profileimageRef.toString());
//Upload image
if(uriProfileImage != null)
{
//Show progressbar
progressBar.setVisibility(View.VISIBLE);
Task<Uri> uriTask = uploadTask.continueWithTask(new Continuation<UploadTask.TaskSnapshot, Task<Uri>>() {
@Override
public Task<Uri> then(@NonNull Task<UploadTask.TaskSnapshot> task) throws Exception {
if (!task.isSuccessful())
{
throw task.getException();
}
return profileimageRef.getDownloadUrl();
}
}).addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
progressBar.setVisibility(View.GONE);
if(task.isSuccessful()) {
profileimageurl = task.getResult().toString();
}
}
});
}
}