コードや構造の何が問題なのかよくわかりません。AsyncTask を使用して画像をダウンロードし、その間に進行状況バーを表示したいと考えていました。しかし、私はそれを行ういくつかの異なる方法を試しました。それでも失敗し、何が問題なのかわかりません。私の構造の流れは
ContentID は、画像のコンテンツ ID を格納する文字列配列です。
主な問題: URL から画像をダウンロードして電話に保存することはできましたが、ダウンロードした画像はすべて同じ画像です。それは異なるイメージであるべきです、それは私が期待したものではありません.
二次的な問題: アプリケーションが画像をダウンロードしている間、進行状況バーがポップアップしますが、進行状況バーは進行状況を更新しませんでした。0% のままで、ダウンロードが完了すると消えます。
私が述べたように、一次および二次の問題の原因を知りたかったのです。私のコードの何が問題なのかわかるかもしれない場合は、コメントまたは回答を残してください。どんな助けでも大歓迎です。
if(isSyncSuccess){
SetConstant.IMAGE_EXIST = 1;
pDialog = new ProgressDialog(GalleryScreen.this);
pDialog.setMessage("Downloading file. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setProgress(0);
pDialog.setMax(contentId.length);
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(true);
if (contentId.length>0){
Log.i(TAG, "contentid.length:" +contentId.length);
for (int i=0;i<contentId.length;i++){
if(helper.databaseChecking(useremail, contentId[i])){
contentdownload = i;
SetConstant.CONTENT_ID = contentId[i];
String URL = SetConstant.URL_DOWNLOAD_CONTENT+contentId[i];
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute(URL);
}
private class DownloadFile extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... sUrl){
Bitmap bm;
InputStream in;
try{
in = new java.net.URL(sUrl[0]).openStream();
bm = BitmapFactory.decodeStream(new PatchInputStream(in));
File storage = new File(Environment.getExternalStorageDirectory() + File.separator + "/Image/");
Log.i(TAG,"storage:" +storage);
Log.i(TAG,"storage:" +storage.getAbsolutePath());
if(!storage.exists()){
storage.mkdirs();
}
String FileName = "/"+SetConstant.CONTENT_ID+".jpg";
FileOutputStream fos = new FileOutputStream(storage + FileName);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fos);
String filepath = storage + FileName;
File filecheck = new File (filepath);
long fileSize = filecheck.length();
fos.flush();
fos.close();
Log.i(TAG, "bm:" +bm);
Log.i(TAG, "fos:" +fos);
Log.i(TAG, "filesize:" +fileSize);
Log.i(TAG, "filepath:" +filepath);
}
catch(IOException e1){
e1.printStackTrace();
}
return null;
}
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog.show();
}
@Override
protected void onProgressUpdate(Integer... progress){
super.onProgressUpdate(progress);
pDialog.setProgress(progress[0]);
}
protected void onPostExecute(String result){
super.onPostExecute(result);
pDialog.dismiss();
}
}
編集
これで、アプリケーションが画像をダウンロードできるようになり、プログレス バーも機能するようになりました。しかし、別の問題は、アプリケーションがダウンロードを完了できなかったときにエラー メッセージを返す方法です。現在、アプリケーションのダウンロードに失敗すると、アプリケーションがクラッシュします。doInBackground 側で実行するべきではないと考えていました。しかし、他にどこでチェックを行うことができますか? アプリケーションをクラッシュさせる代わりに、エラー メッセージとして返して、ユーザーに再試行を要求する方法はありますか?