Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/191.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/firebase/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android Firebase检索图像Url_Android_Firebase_Image Uploading_Firebase Storage - Fatal编程技术网

Android Firebase检索图像Url

Android Firebase检索图像Url,android,firebase,image-uploading,firebase-storage,Android,Firebase,Image Uploading,Firebase Storage,我想从我上传到Firebase的图像中获取下载URL,但当我稍后尝试加载它时,我只得到一个未找到的异常: public class ProfileActivity extends AppCompatActivity{ private static final int CHOOSE_IMAGE = 200; //Initialize items EditText inputUsername, inputBirthday; FloatingActionButton mainaction; Floa

我想从我上传到Firebase的图像中获取下载URL,但当我稍后尝试加载它时,我只得到一个未找到的异常:

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));
}
public class ProfileActivity扩展了AppCompative活动{
私有静态最终int选择_IMAGE=200;
//初始化项目
EditText输入用户名,输入生日;
浮动操作按钮主操作;
浮动操作按钮homeaction;
浮动动作按钮轮廓动作;
StorageReference profileimageRef;
字符串profileimageurl;
按钮操作保存配置文件;
FirebaseAuth mAuth;
ProgressBar ProgressBar;
图像视图轮廓图像;
布尔开放;
Uri图像;
@凌驾
创建时受保护的void(@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=findviewbyd(R.id.fab_profile);
inputUsername=findViewById(R.id.input\u用户名);
inputBirthday=findViewById(R.id.input\u birthday);
actionSaveProfile=findviewbyd(R.id.action\u save\u profile);
profileimage=findviewbyd(R.id.profile\u image);
progressBar=findViewById(R.id.progressBar);
mAuth=FirebaseAuth.getInstance();
//展开、折叠菜单
mainaction.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
如果(!isfabopen)
{
ShowFab();
}否则
{
CloseFab();
}
}
});
profileimage.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
showImageChooser();
}
});
homeaction.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
startActivity(新意图(ProfileActivity.this、MainActivity.class));
}
});
actionSaveProfile.setOnClickListener(新视图.OnClickListener(){
@凌驾
公共void onClick(视图v){
saveUserData(v);
}
});
loadUserData();
}
私有void loadUserData(){
FirebaseUser=mAuth.getCurrentUser();
//如果找不到个人资料图片
if(user.getPhotoUrl()!=null)
{
字符串photoUrl=user.getPhotoUrl().toString();
//设置个人资料图片
用(这个)滑翔
.load(user.getPhotoUrl().toString())
.插入(图像);
}
//如果没有找到用户名
if(user.getDisplayName()!=null)
{
字符串username=user.getDisplayName();
//插入显示名称
inputUsername.setText(user.getDisplayName());
}
}
私有void saveUserData(视图v)
{
字符串名称=inputUsername.getText().toString().trim();
字符串birthday=inputBirthday.getText().toString().trim();
//检查是否有内容
if(name.isEmpty())
{
Snackbar.make(v,R.string.message\u username\u为空,Snackbar.LENGTH\u SHORT)
.setAction(“Action”,null).show();
inputUsername.requestFocus();
}else if(birthday.isEmpty()){
Snackbar.make(v,R.string.message\u生日\u空,Snackbar.LENGTH\u短)
.setAction(“Action”,null).show();
inputBirthday.requestFocus();
}
//获取用户
FirebaseUser=mAuth.getCurrentUser();
//上传信息
if(user!=null&&profileimageurl!=null)
{
UserProfileChangeRequest profileChangeRequest=新建UserProfileChangeRequest.Builder()
.setDisplayName(名称)
.setPhotoUri(Uri.parse(profileimageurl))
.build();
Log.wtf(“ImageURL3”,profileimageurl);
//显示进度条
progressBar.setVisibility(View.VISIBLE);
user.updateProfile(profileChangeRequest).addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
//隐藏进度条
progressBar.setVisibility(View.GONE);
if(task.issusccessful())
{
Toast.makeText(ProfileActivity.this,R.string.message_profile_updated,Toast.LENGTH_SHORT).show();
}否则
{
Toast.makeText(ProfileActivity.this,task.getException().getLocalizedMessage(),Toast.LENGTH_SHORT).show();
}
}
});
}
}
//从showImageChooser获取活动结果时
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
super.onActivityResult(请求代码、结果代码、数据);
//检查结果是否正常
if(requestCode==CHOOSE_IMAGE&&resultCode==RESULT_OK&&data!=null&&data.getData()!=null)
{
//保存图像的uri
uriProfileImage=data.getData();
尝试
{
位图Bitmap=MediaStore.Images.Media.getBitmap(getContentResolver(),uriProfileImage);
profileimage.setImageBitmap(位图);
上传到Firebase();
}捕获(例外情况除外)
{
例如printStackTrace();
}
}
}
私有void上传到firebase(){
//选择目标文件名、文件夹
profileimageRef=FirebaseStorage.getInstance().getReference(“profilepictures/”+System.currentTimeMillis()+”.jpg”);
Log.wtf(“ImageURL”,profileimageRef.toString());
//上传图像
if(uriProfileImage!=null)
{
//显示进度条
progressBar.setVisibility(View.VISIBLE);
profileimageRef.putFile(uriProfileImage).addOnCompleteListener(新的OnCompleteListener(){
@凌驾
未完成的公共void(@NonNull任务){
//隐藏进度条
progressBar.setVisibility(View.GONE);
//检查是否成功
if(task.issusccessful())
{
//设置配置文件图像url
    <?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>
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();
                    }

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

}