こんにちは。
熊本と申します。
ただいまListViewに画像を表示させようとしていてうまくいきません。
データはJSON形式で画像URL(String型)を受け取っています。
イメージアプリとしてはTwitterのようなものです。
流れとしては以下です。
1 DefaultHttpClientを使い非同期処理(AsyncTask)で通信を行う
2 レスポンスでJSON形式の画像URL(String型)を10件取得
3 取得したデータを解析して、ListViewのアイテムにBitmap型かDrawable型で渡す
4 ListView表示
工程3のString型で記されたURLからBitmapもしくはDrawableに変換する時に
エラーで強制終了です。
画像の処理は重いので別スレッドでした方がいいというのは
わかって、コード3でテストしてみてうまくいったのですが、
それをどううまくコード1に適応させるのかがわかりません。
よろしく、よろしくお願いします。
//==================================================//
【コード1】この処理をうまくやりたいです。CustomDataは画像やら文字列をSet,GetするClassです
//===================================================//
List<CustomData> objects = new ArrayList<CustomData>();
try {
JSONArray itemArray = new JSONArray(受け取ったJSON形式のString);
int count = itemArray.length(); //countは10(件)
JSONObject[] ImgObject = new JSONObject[count];
for (int i=0; i<count; i++){
ImgObject[i] = itemArray.getJSONObject(i);
}
CustomData[] item = new CustomData[ImgObject.length];
for (int i=0; i<ImgObject.length; i++){
String imagetext = ImgObject[i].getString(画像のキー);
image = getBitmapFromURL(imagetext); ←---------------①ここで強制終了
item[i] = new CustomData();
item[i].setImagaData(image);
objects.add(item[i]);
}
}
catch (JSONException e){
}
//================================//
【コード2】①のStringからBitmapへの変換メソッド
//================================//
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Log.d("TEST", "erro");
e.printStackTrace();
return null;
}
}
//==================================================//
【コード3】①が機能した時のテスト…こんな処理を上記の①の部分に入れたらいいの??
//==================================================//
public class MainActivity extends Activity {
private Bitmap image = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//-----[ローディングの描画は別スレッドで行う]
Thread thread = new Thread(new Progress());
thread.start();
}
public class Progress implements Runnable
{
public void run() {
try
{
Thread.sleep(5000);
//ここで画像を読み込む処理などを書く
image = getBitmapFromURL(画像のString);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
//-----[読み込み終了の通知]
handler.sendEmptyMessage(0);
}
}
private Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
//-----[ダイアログを閉じる]
//dialog.dismiss();
}
};
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
Log.d("TEST", "erro");
e.printStackTrace();
return null;
}
}
}