【问题标题】:I want to show a picture from URL in my recyclerview [duplicate]我想在我的 recyclerview 中显示来自 URL 的图片 [重复]
【发布时间】:2021-11-16 15:31:41
【问题描述】:

我有一个从 API 填充的 recyclerview,有一个我想在我的 imageview 中显示的图片的 URL,我尝试了几种方法,它给出了网络线程异常,

我的适配器类,

 @Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
    ItemPayload model = list.get(position);
    Log.d("aaa",model.getTrack().getName().toString());

    String image = model.getTrack().getAlbum().getImages().get(position).getUrl();
    URL newurl = null;
    try {
        newurl = new URL(image);
    } catch (MalformedURLException e) {
        e.printStackTrace();
    }
    Bitmap mIcon_val = null;
    try {
        HttpURLConnection conn= (HttpURLConnection)newurl.openConnection();
        conn.setDoInput(true);
        conn.connect();
        int length = conn.getContentLength();
        int[] bitmapData =new int[length];
        byte[] bitmapData2 =new byte[length];
        InputStream is = conn.getInputStream();
        BitmapFactory.Options options = new BitmapFactory.Options();

        mIcon_val = BitmapFactory.decodeStream(is,null,options);

        holder.songCover.setImageBitmap(mIcon_val);
        
    } catch (IOException e) {
        e.printStackTrace();
    }



    holder.textSong.setText(model.getTrack().getName());
    holder.textArtist.setText(model.getTrack().getArtists().get(0).getName());
    holder.textTrack.setText(model.getTrack().getAlbum().getTotal_tracks().toString());
    String url = model.getTrack().getExternal_urls().getSpotify();
    holder.textSong.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent viewIntent =
                    new Intent("android.intent.action.VIEW", Uri.parse(url));
            viewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(viewIntent);
        }
    });

}

有人知道更简单的方法吗?或任何修复?

【问题讨论】:

标签: android android-studio url android-recyclerview android-imageview


【解决方案1】:

使用 HttpURLConnection 加载图像在主线程上加载并停止应用程序的处理或导致 ANR。建议您在后台线程中加载图片。
Glide library 是图片加载库,可以轻松为您完成任务。

使用滑动加载图片

  implementation 'com.github.bumptech.glide:glide:4.12.0'

示例代码

 Glide
    .with(myFragment)
    .load(url)
    .centerCrop()
    .placeholder(R.drawable.loading_spinner)
    .into(myImageView);

【讨论】:

    【解决方案2】:

    您也可以使用 Picasso 库。

    android manifest 中的权限

    <uses-permission android:name="android.permission.INTERNET" />
    

    在应用级 build.gradle 中添加 Picasso

    implementation 'com.squareup.picasso:picasso:2.5.2'
    

    加载图片

    Picasso.get().load(model.getTrack().getAlbum().getImages().get(position).getUrl()).into(holder.songCover);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-05
      • 2022-07-27
      • 1970-01-01
      • 1970-01-01
      • 2011-05-25
      • 2021-10-10
      • 1970-01-01
      相关资源
      最近更新 更多