Android studio 加载图片 url 到 listview

标签 android android-studio asynchronous bitmap phpmyadmin

我想用文本和图像填充 ListView 。 我的 mysql 数据库以 JSON 格式接收此信息。 我有一个名为“FOTO”的字段,我在其中存储了照片的路径,例如:“http://....../1.png”。

我使用这段代码得到了 android.os.NetworkOnMainThreadException,但我不知道如何做不同的事情。

我解析 JSON 并将值传递给列表适配器。我还需要传递图标以便位图值,但我需要从服务器下载它。

public class DisplayListView extends AppCompatActivity {
    final static String TAG = "sb.dl";
    String json_string;
    JSONObject jsonObject;
    JSONArray jsonArray;
    TeamAdapter teamAdapter;
    ListView listView;
    Bitmap icon = null;

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

        teamAdapter = new TeamAdapter(this, R.layout.row_layout);
        listView = (ListView) findViewById(R.id.listview);
        listView.setAdapter(teamAdapter);

        json_string = getIntent().getExtras().getString("json_data");
        Log.d(TAG, "json_string " + json_string);

        try {
            jsonObject = new JSONObject(json_string);
            jsonArray = jsonObject.getJSONArray("risposta");
            int count = 0;

            String nome, num, data;

            while (count < jsonArray.length()) {
                JSONObject JO = jsonArray.getJSONObject(count);
                nome = JO.getString("NOME");
                num = JO.getString("NUMERO");
                data = JO.getString("DATA_NASCITA");
                String url = JO.getString("FOTO");

                icon = LoadImageFromWebOperations(url);

                Team team = new Team(nome, num, data, icon);
                teamAdapter.add(team);

                count++;
            }

        } catch (JSONException e) {
            e.printStackTrace();
            Log.d("Simone", e.toString());
            Log.d("Simone", e.getMessage());
        }
    }

    public static Bitmap LoadImageFromWebOperations() {
        try {
            URL url = new URL("url");
            Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
            return bmp;
        } catch (Exception e) {
            Log.d(TAG, "bitmap error: " + e.toString());
            Log.d(TAG, "bitmap error: " + e.getMessage());
            return null;
        }
    }

}

最佳答案

我遇到了同样的问题。 我用下载位图的 AsyncTask 解决了问题。

我使用了这段代码:

class ImageDownloaderTask extends AsyncTask<String, Void, Bitmap> {

    private final WeakReference<ImageView> imageViewReference;

    public ImageDownloaderTask(ImageView imageView) {
        imageViewReference = new WeakReference<ImageView>(imageView);
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        return downloadBitmap(params[0]);
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {
        if (isCancelled()) {
            bitmap = null;
        }

        if (imageViewReference != null) {
            ImageView imageView = imageViewReference.get();
            if (imageView != null) {
                if (bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                } else {
                    Drawable placeholder = null;
                    imageView.setImageDrawable(placeholder);
                }
            }
        }
    }

    private Bitmap downloadBitmap(String url) {
        HttpURLConnection urlConnection = null;
        try {
            URL uri = new URL(url);
            urlConnection = (HttpURLConnection) uri.openConnection();

            final int responseCode = urlConnection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return null;
            }

            InputStream inputStream = urlConnection.getInputStream();
            if (inputStream != null) {
                Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                return bitmap;
            }
        } catch (Exception e) {
            urlConnection.disconnect();
            Log.w("ImageDownloader", "Errore durante il download da " + url);
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
        }
        return null;
    }
}

你称它为:

new ImageDownloaderTask(holder.imageView).execute(urlPhoto);

希望这有帮助:)

关于Android studio 加载图片 url 到 listview,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37642720/

相关文章:

Android 6.0 错误处理 drawCircle 方法

javascript - 当 async prop Promise 解析时如何更新 React 组件?

javascript - node.js 在客户端 <--> Web 服务器流中的什么位置?

android - 在Android Studio中进行测试时,应用不断停止

javascript - 在函数内部修改变量后,为什么变量未更改? -异步代码引用

android - 我想像 iphone HUD 进度条一样显示自定义对话框

java - 第一次按下时 KEYCODE_BACK 不起作用

android - WallpaperService#onCreateEngine 重置或重新启动

android - 将 BaseGameUtils 添加到 Android Studio

android - Gradle 项目同步失败。 Unresolved 依赖关系