2

アダプターを使用して画像を適切に imageView に表示するのに多くの問題がありました。したがって、基本的には JSON 文字列があり、それを解析して各画像の URL を取得しています。次に、各画像をタイトル付きでリスト ビュー形式で表示したいと考えています。

このコードをオンラインで見つけたところ、画像を1つだけ表示する必要がある場合は完全に機能しますが、これを動的に行う必要がある場合は機能しません。誰でもそれを機能させる方法についていくつかの良い提案がありますか? 参照用にコードの一部を添付しました。

ありがとうございました!!!

 //results => JSON string
 ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
 for(int i = 0; i < results.length(); i++){
 JSONObject c = results.getJSONObject(i);

// Storing each json item in variable
cover = c.getString(TAG_COVER);
String title = c.getString(TAG_TITLE);

try {

    URL urlS = new URL(cover);
    new MyDownloadTask().execute(urlS);

    }catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>(); 

// adding each child node to HashMap key => value
map.put(TAG_COVER, cover);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
resultList.add(map);
}
}
   } catch (JSONException e) {
e.printStackTrace();
  } 

/**
 * Updating parsed JSON data into ListView
 * */
ListAdapter adapter = new SimpleAdapter(this, resultList,
        R.layout.list_item,
        new String[] {TAG_TITLE}, new int[] {
        R.id.title});

setListAdapter(adapter);

そして、ここに私が見つけた画像ダウンロードコードがあります:

private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
    @Override
    protected Bitmap doInBackground(URL... params) {
        URL url = params[0];
        Bitmap bitmap = null;
        try {
            URLConnection connection = url.openConnection();
            connection.connect();
            InputStream is = connection.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);
            bis.close();
            //is.close(); THIS IS THE BROKEN LINE
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

        return bitmap;
    }


    protected void onPostExecute(Bitmap bitmap) {
        if (bitmap != null) {
            ImageView myImage = (ImageView) findViewById(R.id.list_image);
            myImage.setImageBitmap(bitmap);
        } else {
            Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
        }

    }       
}
4

1 に答える 1