Android Java - Glide 在自定义适配器中不工作

Android Java - Glide doesn't working in custom adapter

我尝试使用 Glide 将 URL 中的图像放入自定义适配器中的 ImageView 中。但它向我展示了不可见的图像。当我尝试从 drawable 文件夹中设置图像时它工作正常,但是当我使用 Glide 时它消失了。我在互联网 (Udacity) 上看到了其他示例,它看起来一样,但我的应用程序不显示图像。我搜索了很多,但仍然没有找到解决方案。感谢大家的帮助

MainActivity.class:

public class MainActivity extends AppCompatActivity {
    //Authentication
    private FirebaseAuth auth;
    private FirebaseAuth.AuthStateListener authStateListener;

    //Database
    private FirebaseFirestore db;

    String photo;

    String LOG_TAG = "MainActivity";

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

        Authenticate();
        showPosts();

        ImageView imageView = findViewById(R.id.image);
    }

    private void Authenticate(){
        //connect the app to Firebase
        auth = FirebaseAuth.getInstance();
        db = FirebaseFirestore.getInstance();
        //check if the user is log in
        authStateListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user == null) {
                    // Choose authentication providers
                    List<AuthUI.IdpConfig> providers = Arrays.asList(
                            new AuthUI.IdpConfig.EmailBuilder().build(),
                            new AuthUI.IdpConfig.GoogleBuilder().build());
                    // Create and launch sign-in intent
                    startActivityForResult(AuthUI.getInstance().createSignInIntentBuilder().setAvailableProviders(providers).build(), 1);
                }
            }
        };
    }

    public void showPosts(){
        final ArrayList<Post> posts = new ArrayList<>();
        final PostAdapter postAdapter = new PostAdapter(this, posts);

        ListView list = (ListView) findViewById(R.id.posts);
        list.setAdapter(postAdapter);

        CollectionReference ref = db.collection("posts");
        //get post info
        ref.limit(25).get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                for(QueryDocumentSnapshot doc : task.getResult()){
                    final String text = doc.getString("context");
                    String userId = doc.getString("userID");
                    photo = doc.getString("photo");
                    Log.e(LOG_TAG, photo);
                    DocumentReference userRef = db.collection("users").document(userId);

                    //get OP info
                    userRef.get().addOnCompleteListener(new OnCompleteListener<DocumentSnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
                            String userFirstName = task.getResult().getString("firstName");
                            String userLastName = task.getResult().getString("lastName");
                            postAdapter.add(new Post(text, userFirstName + " " + userLastName, "url"));
                        }
                    });
                }
            }
        });

    }

    public void addPost(View v){
        startActivity(new Intent(this, AddPostActivity.class));
        finish();
    }

    @Override
    protected void onPause() {
        super.onPause();
        auth.removeAuthStateListener(authStateListener);
    }

    @Override
    protected void onResume() {
        super.onResume();
        auth.addAuthStateListener(authStateListener);
    }

Post.class:

public class Post {
    private String mText;
    private String mUserName;
    private String mPhotoURL;

    public Post(String text, String userName){
        mText = text;
        mUserName = userName;
    }

    public Post(String text, String userName, String photoURL){
        mText = text;
        mUserName = userName;
        mPhotoURL = photoURL;
    }

    public String getText() {
        return mText;
    }

    public String getUserName() {
        return mUserName;
    }

    public String getPhotoURL() {
        return mPhotoURL;
    }

}

PostAdapter.class:

public PostAdapter(Activity context, ArrayList<Post> posts){
        super(context, 0, posts);
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if(listItemView == null){
            listItemView = LayoutInflater.from(getContext()).inflate(R.layout.post_view, parent, false);
        }

        Post postItem = getItem(position);

        TextView text = (TextView) listItemView.findViewById(R.id.textBox);
        text.setText(postItem.getText());

        TextView id = (TextView) listItemView.findViewById(R.id.userId);
        id.setText(postItem.getUserName());

        ImageView imageView = (ImageView) listItemView.findViewById(R.id.imageView);

        if(postItem.getPhotoURL() != null){
            Glide.with(imageView.getContext()).load(postItem.getPhotoURL()).into(imageView);
        }else{
            imageView.setVisibility(View.GONE);
        }

        return listItemView;
    }

我发现了问题。我在 ImageView

的宽度和高度中设置了固定值

尝试添加监听器,以便在onLoadFailed回调中了解Glide异常。

    Glide.with(imageView.getContext())
            .load(postItem.getPhotoURL())
            .listener(new RequestListener<Drawable>() {
        @Override
        public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
            Log.e(TAG, "onLoadFailed: called ==" + e);
            return false;
        }

        @Override
        public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
            Log.e(TAG, "onResourceReady: called");
            return false;
        }
    }).into(imageView);

变化:

postAdapter.add(new Post(text, userFirstName + " " + userLastName, "url"));

收件人:

postAdapter.add(new Post(text, userFirstName + " " + userLastName, photo));

我建议您添加日志以查看 URL 是否为空:

Log.v("PhotoLog", "URL: "+ photo);