简体   繁体   English

无法使用 picasso 从 firebase 检索图像字符串

[英]Unable to retrieve image string from firebase using picasso

I am making a chat app and using firebase to upload data, including the user's name, status and image as Strings.我正在制作一个聊天应用程序并使用 firebase 上传数据,包括用户的姓名、状态和图像作为字符串。 Name and status are working fine but the image is not loading at all.名称和状态工作正常,但图像根本无法加载。 I think the code is correct but it is not able to retrieve the id of the image.我认为代码是正确的,但它无法检索图像的 id。 The images are being uploaded in firebase without any issues.图像正在上传到 firebase 中,没有任何问题。 I am using Picasso to retrieve them.我正在使用毕加索来检索它们。 Please can you suggest why am I not able to retrieve the image?请您建议为什么我无法检索图像? This is my code这是我的代码

public class SettingsActivity extends AppCompatActivity {

private DatabaseReference mUserDatabase;
private FirebaseUser mCurrentUser;
private CircleImageView mDisplayImage;
private TextView mName;
private TextView mStatus;
private Button mStatusBtn;
private Button mImageBtn;

private static final int GALLERY_PICK=1;
private StorageReference mImageStorage;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);

    mDisplayImage=(CircleImageView) findViewById(R.id.settings_image);
    mName= (TextView) findViewById(R.id.settings_display_name);
    mStatus=(TextView) findViewById(R.id.setting_status);
    mStatusBtn=(Button) findViewById(R.id.settings_status_btn);
    mImageBtn=(Button)findViewById(R.id.settings_img_btn);

    mImageStorage= FirebaseStorage.getInstance().getReference();

    mCurrentUser= FirebaseAuth.getInstance().getCurrentUser();
    String current_uid=mCurrentUser.getUid();



    mUserDatabase= FirebaseDatabase.getInstance().getReference().child("Users").child(current_uid);

    mUserDatabase.keepSynced(true);

    mUserDatabase.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            final String image=dataSnapshot.child("image").getValue().toString();
            final String name = dataSnapshot.child("name").getValue().toString();
            String status = dataSnapshot.child("status").getValue().toString();
            String thumb_image=dataSnapshot.child("thumb_image").getValue().toString();

            mName.setText(name);
            mStatus.setText(status);

            if(!image.equals("default")) {

               

                Picasso.get().load(image).networkPolicy(NetworkPolicy.OFFLINE)
                        .placeholder(R.drawable.dog).into(mDisplayImage, new Callback() {
                    @Override
                    public void onSuccess() {

                        Toast.makeText(SettingsActivity.this,"Success",Toast.LENGTH_LONG).show();

                    }

                    @Override
                    public void onError(Exception e) {

                        Picasso.get().load(image).networkPolicy(NetworkPolicy.OFFLINE)
                                .placeholder(R.drawable.dog).into(mDisplayImage);

                    }
                });

            }


        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {

        }
    });

    mStatusBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String status_value=mStatus.getText().toString().trim();
            Intent status_intent=new Intent(SettingsActivity.this,StatusActivity.class);
            status_intent.putExtra("status_value",status_value);
            startActivity(status_intent);
        }
    });

    mImageBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent galleryIntent= new Intent();
            galleryIntent.setType("image/*");
            galleryIntent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(galleryIntent,"Select Image "),GALLERY_PICK);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if(requestCode==GALLERY_PICK&& resultCode==RESULT_OK){

        Uri imageUri=data.getData();
        CropImage.activity(imageUri)
                .setAspectRatio(1,1)
                .start(SettingsActivity.this);

    }

    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);
        if (resultCode == RESULT_OK) {

            final AlertDialog dialog = new AlertDialog.Builder(SettingsActivity.this).create();
            dialog.setTitle("Uploading image...");
            dialog.setMessage("Please wait while we upload your image");
            dialog.setCanceledOnTouchOutside(false);
            dialog.show();

            Uri resultUri = result.getUri();

            final File thumb_filePath= new File(resultUri.getPath());

            String current_user_id=mCurrentUser.getUid();

            Bitmap thumb_bitmap = new Compressor(SettingsActivity.this)
                    .setMaxWidth(200)
                    .setMaxHeight(200)
                    .setQuality(75)
                    .compressToBitmap(thumb_filePath);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            thumb_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            final byte[] thumb_byte = baos.toByteArray();

            StorageReference filepath=mImageStorage.child("profile_images").child(current_user_id + ".jpg");
            final StorageReference thumb_filepath=mImageStorage.child("profile_images").child("thumbs").child(current_user_id + ".jpg");

            filepath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {

                    if(task.isSuccessful()){

                        final String download_url= task.getResult().getStorage().getDownloadUrl().toString();

                        UploadTask uploadTask=thumb_filepath.putBytes(thumb_byte);
                        uploadTask.addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                            @Override
                            public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> thumb_task) {

                                String thumb_downloadUrl=thumb_task.getResult().getStorage().getDownloadUrl().toString();

                                if(thumb_task.isSuccessful()){

                                    Map update_hashMap=new HashMap<>();
                                    update_hashMap.put("image",download_url);
                                    update_hashMap.put("thumb_image",thumb_downloadUrl);

                                    mUserDatabase.updateChildren(update_hashMap).addOnCompleteListener(new OnCompleteListener<Void>() {
                                        @Override
                                        public void onComplete(@NonNull Task<Void> task) {
                                            if(task.isSuccessful()){
                                                dialog.dismiss();
                                                Toast.makeText(SettingsActivity.this,"Success Uploading thumbnail", Toast.LENGTH_LONG).show();

                                            }
                                        }
                                    });

                                }

                                else {
                                    Toast.makeText(SettingsActivity.this,"Error in uploading thumbnail",Toast.LENGTH_LONG).show();
                                    dialog.dismiss();
                                }

                            }
                        });

                        mUserDatabase.child("image").setValue(download_url).addOnCompleteListener(new OnCompleteListener<Void>() {
                            @Override
                            public void onComplete(@NonNull Task<Void> task) {

                                if(task.isSuccessful()){

                                    dialog.dismiss();
                                    Toast.makeText(SettingsActivity.this,"Successfuly Uploaded.",Toast.LENGTH_LONG).show();
                                }

                            }
                        });
                    }
                    else{

                        Toast.makeText(SettingsActivity.this,"Error in uploading",Toast.LENGTH_LONG).show();
                        dialog.dismiss();
                    }

                }
            });
        } else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
            Exception error = result.getError();
        }
    }
}

This is the XML layout这是 XML 布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
android:background="#00BCD4"
tools:context=".SettingsActivity">

<de.hdodenhof.circleimageview.CircleImageView
    android:id="@+id/settings_image"
    android:layout_width="230dp"
    android:layout_height="224dp"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="72dp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.491"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"></de.hdodenhof.circleimageview.CircleImageView>

<TextView
    android:id="@+id/settings_display_name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="326dp"
    android:text="Display Name"
    android:textSize="30sp" />

<TextView
    android:id="@+id/setting_status"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="301dp"
    android:text="@string/default_status"
    android:textSize="25sp" />

<Button
    android:id="@+id/settings_img_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="204dp"
    android:text="Change Image" />

<Button
    android:id="@+id/settings_status_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginStart="152dp"
    android:layout_marginLeft="152dp"
    android:layout_marginBottom="119dp"
    android:text="Change Status" />

</RelativeLayout>

I think the main problem is the networkPolicy(NetworkPolicy.OFFLINE) .我认为主要问题是networkPolicy(NetworkPolicy.OFFLINE) You are basically skipping network and forcing Picasso for search in the disk.您基本上是跳过网络并强制毕加索在磁盘中进行搜索。 That's mean it is not communicating with firebase and thus the image is not loaded.这意味着它没有与 firebase 通信,因此没有加载图像。 For reference read the official documentation:参考阅读官方文档:

https://square.github.io/picasso/2.x/picasso/com/squareup/picasso/NetworkPolicy.html https://square.github.io/picasso/2.x/picasso/com/squareup/picasso/NetworkPolicy.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM