学校新聞のアプリを作る努力を続けています。私の最新の課題は、すべてのクラブと組織のロゴを、クラブに関するその他の詳細と共にアクティビティ内にある ImageView に表示することです。
明らかな理由から、これらの画像をすべてアプリ内に保存したくはありません。むしろ、URL から取得したいと考えています。これを行う方法は、次のスニペットになると思います。
Intent intent = getIntent();
Bitmap bm = null;
try {
bm = BitmapFactory.decodeStream((InputStream)new URL(intent.getStringExtra("keyLogo")).getContent());
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
detailsLogo.setImageBitmap(bm);
キャンパス内のすべてのクラブとその情報を含む、作成した XML ファイルから URL を取得しています。この方法では、アプリ内で何かを変更したい場合にのみ XML を変更する必要があります。
ここでの問題は、NetworkOnMainThread 例外をスローすることです。これをアクティビティ内の AsyncTask に入れて、そのように実行できますか? アドバイスをいただければ幸いです。
編集:リンクされた質問は私のニーズに答えません。それに対する答えの1つは近いですが、私の質問には、受け入れられた質問に含まれていない非同期タスクが特に必要です。
受け入れられた回答と他の部分を使用した完成したアクティビティは次のとおりです。
public class OrgDetails extends Activity {
/*******************************************************************
* Async Task
******************************************************************/
private class GetImageFromServer extends AsyncTask<String, Void, Bitmap> {
String url;
Context context;
private Bitmap image;
ImageView detailsLogo = (ImageView)findViewById(R.id.detailsLogo);
public GetImageFromServer(String url, Context context){
this.url = url;
this.context = context;
}
@Override
protected Bitmap doInBackground(String... params){
try{
URL urli = new URL(this.url);
URLConnection ucon = urli.openConnection();
image = BitmapFactory.decodeStream(ucon.getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image; //<<< return Bitmap
}
@Override
protected void onPostExecute(Bitmap result){
detailsLogo.setImageBitmap(result);
}
}
/*******************************************************************
* End Async Task
******************************************************************/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orgdetails);
TextView detailsSname = (TextView)findViewById(R.id.detailsSname);
TextView detailsLname = (TextView)findViewById(R.id.detailsLname);
TextView detailsDescription = (TextView)findViewById(R.id.detailsDescription);
Intent intent = getIntent();
detailsLname.setText(intent.getStringExtra("keyLname"));
detailsSname.setText(intent.getStringExtra("keySname"));
detailsDescription.setText(intent.getStringExtra("keyDescription"));
String str_url = intent.getStringExtra("keyLogo");
GetImageFromServer asyObj = new GetImageFromServer(str_url,OrgDetails.this);
asyObj.execute("");
}
}