I cant edit cover picture and profile picture using firebase storage. What's wrong in my program?

huangapple go评论86阅读模式
英文:

I cant edit cover picture and profile picture using firebase storage. What's wrong in my program?

问题

您的代码中存在一些问题,主要涉及到Firebase Storage的图像上传和下载问题。以下是问题的主要点:

  1. storageReference未进行初始化。
  2. uploadProfileCoverPhoto(Uri uri)方法中存在两次while (!uriTask.isSuccessful());,这会导致UI线程被阻塞,不推荐这种做法。
  3. pickFromCamera()方法中,您需要确保image_uri已正确设置为拍摄的图像URI。
  4. requestPermissionscheckSelfPermission的使用需要注意,您可以尝试在Fragment中使用requestPermissions而不是ActivityCompat.requestPermissions
  5. 如果应用在Android 10及以上版本上运行,您需要使用MediaStore中的新API来保存和获取图像。

您可以根据以下示例进行修改和改进:

// 在onCreateView方法中初始化storageReference
storageReference = FirebaseStorage.getInstance().getReference();

// 更新uploadProfileCoverPhoto方法
private void uploadProfileCoverPhoto(final Uri uri) {
    pd.show();

    String filePathAndName = storagePath + user.getUid() + "_" + System.currentTimeMillis();
    StorageReference storageReference2nd = storageReference.child(filePathAndName);
    
    storageReference2nd.putFile(uri)
            .addOnSuccessListener(taskSnapshot -> {
                // 上传成功后,获取下载链接
                storageReference2nd.getDownloadUrl()
                        .addOnSuccessListener(uri1 -> {
                            String downloadUrl = uri1.toString();
                            // 根据profileORCoverPhoto选择要更新的字段
                            HashMap<String, Object> result = new HashMap<>();
                            result.put(profileORCoverPhoto, downloadUrl);
                            
                            databaseReference.child(user.getUid()).updateChildren(result)
                                    .addOnSuccessListener(aVoid -> {
                                        pd.dismiss();
                                        Toast.makeText(getActivity(), "Image Updated...", Toast.LENGTH_SHORT).show();
                                    })
                                    .addOnFailureListener(e -> {
                                        pd.dismiss();
                                        Toast.makeText(getActivity(), "Error Updating Image...", Toast.LENGTH_SHORT).show();
                                    });
                        })
                        .addOnFailureListener(e -> {
                            pd.dismiss();
                            Toast.makeText(getActivity(), "Error Getting Image URL...", Toast.LENGTH_SHORT).show();
                        });
            })
            .addOnFailureListener(e -> {
                pd.dismiss();
                Toast.makeText(getActivity(), e.getMessage(), Toast.LENGTH_SHORT).show();
            });
}

// 修改pickFromCamera方法
private void pickFromCamera() {
    ContentValues values = new ContentValues();
    values.put(MediaStore.Images.Media.TITLE, "Temp Pic");
    values.put(MediaStore.Images.Media.DESCRIPTION, "Temp Description");
    
    image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    
    Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
    startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}

这些修改应该有助于解决图像上传和下载的问题。请根据您的实际需要进行调整和测试。如果还有其他问题,请随时提出。

英文:

I added user profile page in my project which is ProfileFragment.java and it's layout file is fragment_profile.xml. I want to update user information like name,description, profile pic and cover page. My program does not have error, name and description update successfully but cover and profile pictures does not update? What is wrong in my code?

This is my ProfileFragment.java

public class ProfileFragment extends Fragment {
//Log Statment
private static final String TAG = &quot;ProfileFragment&quot;;
//firebase auth
FirebaseAuth firebaseAuth;
FirebaseUser user;
FirebaseDatabase firebaseDatabase;
DatabaseReference databaseReference;
//firabase storage
StorageReference storageReference;
//profil resminin ve kapak resminin nerede depolanacağının yolu
String storagePath = &quot;Users_Profile_Cover_Imgs/&quot;;
//layout views
ImageView avatar, coverPhoto;
TextView nameTxt, emailTxt, descTxt;
FloatingActionButton fab;
//Progress Dialog
ProgressDialog pd;
//permissions
private static final int CAMERA_REQUESTED_CODE = 100;
private static final int STORAGE_REQUESTED_CODE = 200;
private static final int IMAGE_PICK_GALLERY_CODE = 300;
private static final int IMAGE_PICK_CAMERA_CODE = 400;
//izinler i&#231;in gerekli arrayler
String cameraPermissions[];
String storagePermissions[];
//se&#231;ilen resmin uri adresi
Uri image_uri;
//profil fotografı yoksa kapak fotografımı kontrol et
String profileORCoverPhoto;
public ProfileFragment() {
//boş public constructor gerekli
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view =  inflater.inflate(R.layout.fragment_profile, container, false);
//init firebase
firebaseAuth = FirebaseAuth.getInstance();
user = firebaseAuth.getCurrentUser();
firebaseDatabase = FirebaseDatabase.getInstance();
databaseReference = firebaseDatabase.getReference(&quot;Users&quot;);
//init layout views
avatar = view.findViewById(R.id.avatar);
coverPhoto = view.findViewById(R.id.coverPhoto);
nameTxt = view.findViewById(R.id.nameTxt);
emailTxt = view.findViewById(R.id.emailTxt);
descTxt = view.findViewById(R.id.descTxt);
fab = view.findViewById(R.id.fab);
pd = new ProgressDialog(getActivity());
//izin arrayleri
cameraPermissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE};
storagePermissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
/* giriş yapan kullanıcıların bilgilerini email yada uid kullanarak &#231;ekmek zorundayız
Kullanıcı detaylarını email adreslerini kullanarak &#231;ekicez
orderbyChild query kullanarak giriş yapılan email ile email key ini eşleştirerek kullanıcı detaylarına ulaşılıyor
*/
Query query = databaseReference.orderByChild(&quot;email&quot;).equalTo(user.getEmail());
query.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot snapshot) {
//gerekli veriler gelene kadar kontrol et
for (DataSnapshot ds: snapshot.getChildren()){
//verileri almak i&#231;in
String name = &quot;&quot;+ ds.child(&quot;name&quot;).getValue();
String email = &quot;&quot;+ ds.child(&quot;email&quot;).getValue();
String desc = &quot;&quot;+ ds.child(&quot;desc&quot;).getValue();
String image = &quot;&quot;+ ds.child(&quot;image&quot;).getValue();
String cover = &quot;&quot;+ ds.child(&quot;cover&quot;).getValue();
//set data
nameTxt.setText(name);
emailTxt.setText(email);
descTxt.setText(desc);
Log.d(TAG, &quot;onDataChange: \nName: &quot;+name+&quot; email: &quot;+ email);
try {
// resim alınırsa ayarla
Picasso.get().load(image).into(avatar);
} catch (Exception e){
// resim alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.add_photo_foreground).into(avatar);
}
try {
// kapak resimi alınırsa ayarla
Picasso.get().load(cover).into(coverPhoto);
} catch (Exception e){
// kapak resmi alınırken herangi bir sıkıntı varsa varsayılan olarak ayarla
Picasso.get().load(R.drawable.default_cover_photo).into(coverPhoto);
}
}
Log.d(TAG, &quot;onDataChange: Data is empty&quot;);
}
@Override
public void onCancelled(@NonNull DatabaseError error) {
Log.d(TAG, &quot;onCancelled: &quot;+error);
}
});
//fab button onClick &#246;zelliği ekleme
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//edit profile dialog g&#246;ster
showEditProfileDialog();
}
});
return view;
}
private void requestStoragePermission(){
//runtime depolama izinleri isteme
requestPermissions(storagePermissions, STORAGE_REQUESTED_CODE);
}
private void requestCameraPermission(){
//runtime depolama izinleri isteme
requestPermissions(cameraPermissions, CAMERA_REQUESTED_CODE);
}
private boolean checkStoragePermission(){
//depolama izinlerini kontrol et, etkinse true, değilse false d&#246;nd&#252;r
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return  result;
}
private boolean checkCameraPermission(){
//depolama izinlerini kontrol et, etkinse true, değilse false d&#246;nd&#252;r
boolean result = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
== (PackageManager.PERMISSION_GRANTED);
boolean result1 = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)
== (PackageManager.PERMISSION_GRANTED);
return  result &amp;&amp; result1;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Bu y&#246;ntem, kullanıcı izin isteği iletişim kutusundan izin ver veya reddet d&#252;ğmesine bastığında &#231;ağrılır
//burada izin durumlarını ele alınır(izin verildi ve reddedildi)
switch (requestCode){
case CAMERA_REQUESTED_CODE: {
//camera se&#231;ildiğinde &#246;nce izin alınmış mı diye kontrol eder
if (grantResults.length &gt; 0 ){
boolean cameraAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted  = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(cameraAccepted &amp;&amp; writeStorageAccepted){
//izinler etkinleştirildi
pickFromCamera();
}
else{
//izinler reddedildi
Toast.makeText(getActivity(),&quot;Please enable camera &amp;&amp; storage permission&quot;,Toast.LENGTH_SHORT).show();
}
}
}
break;
//galeri se&#231;ildiğinde &#246;nce izin alınmış mı diye kontrol eder
case STORAGE_REQUESTED_CODE: {
if (grantResults.length &gt; 0 ){
boolean cameraAccepted  = grantResults[0] == PackageManager.PERMISSION_GRANTED;
boolean writeStorageAccepted  = grantResults[1] == PackageManager.PERMISSION_GRANTED;
if(writeStorageAccepted){
//izinler etkinleştirildi
pickFromGallery();
}
else{
//izinler reddedildi
Toast.makeText(getActivity(),&quot;Please enable storage permission&quot;,Toast.LENGTH_SHORT).show();
}
}
}
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
//bu metot camera veya galeri den fotograf se&#231;ildikten sonra &#231;ağırılıyor
if (resultCode == RESULT_OK){
if (requestCode == IMAGE_PICK_GALLERY_CODE){
//resim geleriden se&#231;ildi, resmin uri&#39;sini al
image_uri = data.getData();
uploadProfileCoverPhoto(image_uri);
}
if (requestCode == IMAGE_PICK_CAMERA_CODE){
//resim cameradan se&#231;ildi, resmin uri&#39;sini al
uploadProfileCoverPhoto(image_uri);
}
}
super.onActivityResult(requestCode, resultCode, data);
}
//Editprofile dialog
private void showEditProfileDialog() {
// Profil resmi d&#252;zenle, kapak fotografı g&#246;sterme, isim d&#252;zenleme, a&#231;ıklama d&#252;zenleme
//Se&#231;enekleri dialogta g&#246;sterme
String options[] = {&quot;Edit Profile Picture&quot;, &quot;Edit Cover Photo&quot;, &quot;Edit Name&quot;, &quot;Edit Description&quot;};
//alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//başlık
builder.setTitle(&quot;Choose Action&quot;);
//dialog itemlerini ayarlama
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//dialog itemlere onClick &#246;zelliği ekleme
if (which == 0){
//profil d&#252;zenleme tıklandı
pd.setMessage(&quot;Updating Profile Picture&quot;);
//profil foto mu yoksa kapak foto mu konrol i&#231;in
profileORCoverPhoto = &quot;image&quot;; // profil resmini değiştirirken aynı değerlerin atandığından emin ol
showImagePicDialog();
}
else if (which == 1){
//kapak d&#252;zenleme tıklandı
pd.setMessage(&quot;Updating Cover Picture&quot;);
//profil foto mu yoksa kapak foto mu konrol i&#231;in
profileORCoverPhoto = &quot;cover&quot;; //kapak resmini değiştirirken aynı değerlerin atandığından emin ol
showImagePicDialog();
}
else if (which == 2){
//isim duzenleme tıklandı
pd.setMessage(&quot;Updating Name&quot;);
//veritabanında &quot;name&quot; g&#252;ncellenmesi i&#231;in motodun &#231;ağırılması
showNameDescUpdateDialog(&quot;name&quot;);
}
else if (which == 3){
//a&#231;ıklama d&#252;zenleme tıklandı
pd.setMessage(&quot;Updating Description&quot;);
showNameDescUpdateDialog(&quot;desc&quot;);
}
}
});
//dialog oluşturme ve g&#246;sterme
builder.create().show();
}
private void showNameDescUpdateDialog(final String key) {
//key parametresi &quot;name&quot; ve &quot;desc&quot; değerlerini alıyor
//custom dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(&quot;Update &quot;+key); //Update name or Update description..
//Dialog layoutunu ayarla
LinearLayout linearLayout = new LinearLayout(getActivity());
linearLayout.setOrientation(LinearLayout.VERTICAL);
linearLayout.setPadding(10,10,10,10);
//editText ekleme
final EditText editText = new EditText(getActivity());
editText.setHint(&quot;Enter &quot;+ key);
linearLayout.addView(editText);
builder.setView(linearLayout);
//dialog&#39;a update button ekle
builder.setPositiveButton(&quot;Update&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//input text from edit text
String value = editText.getText().toString().trim();
//kullanıcının bir şeyler girip girmediğini onayla
if (!TextUtils.isEmpty(value)){
pd.show();
HashMap&lt;String, Object&gt; result = new HashMap&lt;&gt;();
result.put(key, value);
databaseReference.child(user.getUid()).updateChildren(result)
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
//g&#252;ncellendi, dismiss progress
pd.dismiss();
Toast.makeText(getActivity(),&quot;Updated...&quot;,Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//error mesajı al ve g&#246;ster, dismiss progress
pd.dismiss();
Toast.makeText(getActivity(),&quot;&quot;+e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
else {
Toast.makeText(getActivity(), &quot;Please Enter &quot;+key, Toast.LENGTH_SHORT).show();
}
}
});
//dialog&#39;a cancel button ekle
builder.setNegativeButton(&quot;Cancel&quot;, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
//dialog&#39;u oluştur ve g&#246;ster
builder.create().show();
}
private void showImagePicDialog() {
//profil resmini cameradan ya da galeriden se&#231;me se&#231;enekleri ekleme
String options[] = {&quot;Camera&quot;, &quot;Gallery&quot;};
//alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
//başlık
builder.setTitle(&quot;Pick Image From&quot;);
//dialog itemlerini ayarlama
builder.setItems(options, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//dialog itemlere onClick &#246;zelliği ekleme
if (which == 0){
//camera tıklandı
// pd.setMessage(&quot;Updating Profile Picture&quot;);
//showImagePicDialog();
if (!checkCameraPermission()){
requestCameraPermission();
}
else{
pickFromCamera();
}
}
else if (which == 1){
//galeir tıklandı
//pd.setMessage(&quot;Updating Cover Picture&quot;);
if(!checkStoragePermission()){
requestStoragePermission();
}
else {
pickFromGallery();
}
}
}
});
//dialog oluşturme ve g&#246;sterme
builder.create().show();
}
private void uploadProfileCoverPhoto(final Uri uri) {
//Show progress dialog
pd.show();
//iki ayrı fonksiyon yerine profil resmi ve kapak resmi aynı fonksiyonda
//firabase storage&#39;da depolanan resmin yolu ve adı
String filePathAndName = storagePath+ &quot;&quot;+ profileORCoverPhoto + &quot;_&quot;+ user.getUid();
StorageReference storageReference2nd = storageReference.child(filePathAndName);
storageReference2nd.putFile(uri)
.addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//resim depoya y&#252;klendi, şimdi url&#39;sini al ve kullanıcı veritabanında sakla
Task&lt;Uri&gt; uriTask = taskSnapshot.getStorage().getDownloadUrl();
while (!uriTask.isSuccessful());
Uri downloadUri = uriTask.getResult();
//resmin y&#252;klenip y&#252;klenmediğini ve url&#39;nin alındığını kontrol edin
if (uriTask.isSuccessful()){
//resim y&#252;klendi
//kullanıcı veritabanına url&#39;i ekle/g&#252;ncelle
HashMap&lt;String, Object&gt; results = new HashMap&lt;&gt;();
//ilk parametre profileOrCoverPhote image veya cover değerlerine sahip
//ikinci parametre firebase storage&#39;da depolanan resmin url
results.put(profileORCoverPhoto, downloadUri.toString());
databaseReference.child(user.getUid()).updateChildren(results)
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
pd.dismiss();
Toast.makeText(getActivity(), &quot;Image Updated...&quot;, Toast.LENGTH_SHORT).show();
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
pd.dismiss();
Toast.makeText(getActivity(), &quot;Error Updating Image...&quot;, Toast.LENGTH_SHORT).show();
}
});
}
else {
//error
pd.dismiss();
Toast.makeText(getActivity(), &quot;Some error occured&quot;, Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
//bazı errorlar var, errorları al ve error mesajı g&#246;ster, dissmis dialog
pd.dismiss();
Toast.makeText(getActivity(), e.getMessage(),Toast.LENGTH_SHORT).show();
}
});
}
private void pickFromCamera() {
//cihaz kamerasından g&#246;r&#252;nt&#252; alma
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, &quot;Temp Pic&quot;);
values.put(MediaStore.Images.Media.DESCRIPTION, &quot;Temp Description&quot;);
//resim uri&#39;si
image_uri = getActivity().getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
//camera başlatılması
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, image_uri);
startActivityForResult(cameraIntent, IMAGE_PICK_CAMERA_CODE);
}
private void pickFromGallery() {
//galeriden resim se&#231;me
Intent galleryIntent = new Intent(Intent.ACTION_PICK);
galleryIntent.setType(&quot;image/*&quot;);
startActivityForResult(galleryIntent, IMAGE_PICK_GALLERY_CODE);
}
}

My AndroidManifes.xml is

&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;
&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;
package=&quot;com.gamze.pawsbook&quot;&gt;
&lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot;
android:maxSdkVersion=&quot;29&quot; /&gt;
&lt;uses-permission android:name=&quot;android.permission.CAMERA&quot;
android:maxSdkVersion=&quot;29&quot; /&gt;
&lt;application
android:allowBackup=&quot;true&quot;
android:icon=&quot;@mipmap/ic_launcher&quot;
android:label=&quot;@string/app_name&quot;
android:roundIcon=&quot;@mipmap/ic_launcher_round&quot;
android:supportsRtl=&quot;true&quot;
android:theme=&quot;@style/AppTheme&quot;&gt;
&lt;activity android:name=&quot;.LoginActivity&quot;&gt;&lt;/activity&gt;
&lt;activity android:name=&quot;.DashboardActivity&quot;&gt;
&lt;intent-filter&gt;
&lt;action android:name=&quot;android.intent.action.MAIN&quot; /&gt;
&lt;category android:name=&quot;android.intent.category.LAUNCHER&quot; /&gt;
&lt;/intent-filter&gt;
&lt;/activity&gt;
&lt;activity android:name=&quot;.RegisterActivity&quot; /&gt;
&lt;activity android:name=&quot;.MainActivity&quot;&gt;&lt;/activity&gt;
&lt;/application&gt;
&lt;/manifest&gt;

My build.gradle(module:app)

apply plugin: &#39;com.android.application&#39;
apply plugin: &#39;com.google.gms.google-services&#39;
android {
compileSdkVersion 29
defaultConfig {
applicationId &quot;com.gamze.pawsbook&quot;
minSdkVersion 22
targetSdkVersion 29
versionCode 1
versionName &quot;1.0&quot;
testInstrumentationRunner &quot;androidx.test.runner.AndroidJUnitRunner&quot;
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(&#39;proguard-android-optimize.txt&#39;), &#39;proguard-rules.pro&#39;
}
}
}
dependencies {
implementation fileTree(dir: &quot;libs&quot;, include: [&quot;*.jar&quot;])
implementation &#39;androidx.appcompat:appcompat:1.1.0&#39;
implementation &#39;androidx.constraintlayout:constraintlayout:1.1.3&#39;
implementation &#39;com.google.android.material:material:1.1.0&#39;
implementation &#39;androidx.legacy:legacy-support-v4:1.0.0&#39;
testImplementation &#39;junit:junit:4.12&#39;
androidTestImplementation &#39;androidx.test.ext:junit:1.1.1&#39;
androidTestImplementation &#39;androidx.test.espresso:espresso-core:3.2.0&#39;
// add the Firebase SDK for Google Analytics
implementation &#39;com.google.firebase:firebase-analytics:17.2.2&#39;
//Firebase authentication library
implementation &#39;com.google.firebase:firebase-auth:19.3.2&#39;
implementation &#39;com.google.android.gms:play-services-auth:18.1.0&#39;
//google sign in library
implementation &#39;com.google.android.gms:play-services-auth:18.1.0&#39;
//Firebase Realtime Database
implementation &#39;com.google.firebase:firebase-database:19.3.1&#39;
//Firebase Storage
implementation &#39;com.google.firebase:firebase-storage:19.1.1&#39;
//Picasso library (resimleri eklemek i&#231;in)
implementation &#39;com.squareup.picasso:picasso:2.71828&#39;
}

答案1

得分: 0

我建议尝试在将位图转换为ByteArrayOutputStream后保存位图,而不是URI

您可以按以下方式获取用户选择的位图 -

....
Bitmap newImage; // 将其设置为全局变量
....

@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode != RESULT_CANCELED) {
        switch (requestCode) {
            case 0: // 来自相机的图像
                if (resultCode == RESULT_OK && data != null) {
                    newImage = (Bitmap) data.getExtras().get("data");
                    userImage.setImageBitmap(newImage);
                    newImageSet = true;
                }

                break;
            case 1: // 来自相册/用户设备的图像
                if (resultCode == RESULT_OK && data != null) {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    if (selectedImage != null) {
                        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                                filePathColumn, null, null, null);
                        if (cursor != null) {
                            cursor.moveToFirst();
                            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                            String picturePath = cursor.getString(columnIndex);
                            newImage = BitmapFactory.decodeFile(picturePath);
                            userImage.setImageBitmap(newImage);
                            cursor.close();
                        }
                    }
                }
                break;
        }
    }
}

获取新图像位图后,可以按如下方式将位图放入Firebase。

public void saveImageToFirbase() {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    newImage.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
    StorageReference imgReference = FirebaseStorage.getInstance().getReference()
            .child("User Profile Image")
            .child(FirebaseAuth.getInstance().getCurrentUser().getUid() + ".jpeg");
    // 根据您的数据库结构调整imgReference

    imgReference.putBytes(byteArrayOutputStream.toByteArray())
            .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                    getDownloadUrl(imgReference);
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "onFailure: ", e.getCause());
                }
            });
}

这里的Bitmap.CompressFormat.JPEG, 40整数值将是压缩级别。

getDownloadUrl() 方法 -

private void getDownloadUrl(StorageReference storageReference) {
    storageReference.getDownloadUrl()
            .addOnSuccessListener(new OnSuccessListener<Uri>() {
                @Override
                public void onSuccess(Uri uri) {
                    setUserProfileUrl(uri);
                }
            });
}

最后,您可以更新用户的个人资料并设置图像URL -

private void setUserProfileUrl(Uri userProfileUrl) {
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder()
            .setPhotoUri(userProfileUrl).build();
    firebaseUser.updateProfile(userProfileChangeRequest)
            .addOnSuccessListener(new OnSuccessListener<Void>() {
                @Override
                public void onSuccess(Void aVoid) {
                    // 在您的视图中进行更多更新
                }
            })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.e(TAG, "onFailure: ", e.getCause());
                }
            });
}

愉快的编程!

英文:

I will suggest try to save Bitmap after converting it to ByteArrayOutputStream not URI.

You can get user selected Bitmap as follows -

....
Bitmap newImage;                 //make it a global variable
.....
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode != RESULT_CANCELED) {
switch (requestCode) {
case 0:                            //Image from Camera
if (resultCode == RESULT_OK &amp;&amp; data != null) {
newImage = (Bitmap) data.getExtras().get(&quot;data&quot;);
userImage.setImageBitmap(newImage);
newImageSet = true;
}
break;
case 1:                           //Image from gallery/user device
if (resultCode == RESULT_OK &amp;&amp; data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
newImage = BitmapFactory.decodeFile(picturePath);
userImage.setImageBitmap(newImage);
cursor.close();
}
}
}
break;
}
}
}

After getting new image bitmp this is how you can put Bitmap in Firstore.

public void saveImageToFirbase(){
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
newImage.compress(Bitmap.CompressFormat.JPEG, 40, byteArrayOutputStream);
StorageReference imgReference = FirebaseStorage.getInstance().getReference()
.child(&quot;User Profile Image&quot;)   
.child(FirebaseAuth.getInstance().getCurrentUser().getUid() + &quot;.jpeg&quot;);
//adjust imgReference according to your database structure 
imgReference.putBytes(byteArrayOutputStream.toByteArray())
.addOnSuccessListener(new OnSuccessListener&lt;UploadTask.TaskSnapshot&gt;() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
getDownloadUrl(imgReference);
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, &quot;onFailure: &quot;, e.getCause());
}
});
}

Here Bitmap.CompressFormat.JPEG, 40 integer value will be the level of compression.

Method getgetDownloadUrl() -

private void getDownloadUrl(StorageReference storageReference) {
storageReference.getDownloadUrl()
.addOnSuccessListener(new OnSuccessListener&lt;Uri&gt;() {
@Override
public void onSuccess(Uri uri) {
setUserProfileUrl(uri);
}
});
} 

And at least you can update user's Profile and set ImageUrl -

private void setUserProfileUrl(Uri userProfileUrl) {
FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
UserProfileChangeRequest userProfileChangeRequest = new UserProfileChangeRequest.Builder()
.setPhotoUri(userProfileUrl).build();
firebaseUser.updateProfile(userProfileChangeRequest)
.addOnSuccessListener(new OnSuccessListener&lt;Void&gt;() {
@Override
public void onSuccess(Void aVoid) {
//some more update in your view
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, &quot;onFailure: &quot;, e.getCause());
}
});
}

Happy Coding !

huangapple
  • 本文由 发表于 2020年8月8日 22:42:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63316661.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定