Мне нужна помощь в AsyncTask. Я загружаю несколько изображений из URL, используя async, и он загружает все изображения одновременно. Проблема, с которой я сталкиваюсь, заключается в том, что когда пользователь сталкивается с проблемой подключения к Интернету, а изображения не загружаются: у меня есть цикл внутри doInBackground для извлечения URL-адресов, загрузки и сохранения его на SD-карту, в случае успешной загрузки я обновлю бит флага до 1 в локальной БД и если нет, то должно быть 0. Проблема заключается в том, что doInBackground возвращает либо последнее значение из цикла, либо, если используется arraylist для хранения флагов, то отправляет весь arraylist для обновления до 1. Но я хочу, чтобы только идентификатор загруженных изображений отправлялся в метод onPost Execute () и только этот идентификатор должен быть обновлен до 1. Я знаю, что после того, как поток завершает свою задачу, он отправляет результат в onPostExecute (), но я не получаю его, при проверке его состояния он все еще показывает, что работает. Как я могу решить это.
Я хочу, если изображения не загружаются, я хочу установить бит флага в его значение по умолчанию, равное 0, и если бит загружен в 1.
import java.util.ArrayList;
import java.util.List;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import static android.view.View.INVISIBLE;
public class Download_Activity extends AppCompatActivity {
private static final int EXTERNAL_STORAGE_PERMISSION_CONSTANT = 100;
private List<Model_Download> recList;
String file_url;
String folder_main = "Xs_Images";
File file; // = your file
String mimetype; // = your file's mimetype. MimeTypeMap may be useful.
Button download_Btn;
myDbAdapter helper;
int id1,id;
View v;
int downloadStatus=1;
int status=0;
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
//int[] arr=new int[recList.size()];
ArrayList<Integer> ids=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_);
recList = new ArrayList<Model_Download>();
recList = (ArrayList) getIntent().getParcelableArrayListExtra("downloads");
download_Btn=(Button)findViewById(R.id.download);
helper = new myDbAdapter(this);
if (ActivityCompat.checkSelfPermission(Download_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(Download_Activity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, EXTERNAL_STORAGE_PERMISSION_CONSTANT);
}
}
public void downloadImageFromUrl(View view){
if (ActivityCompat.checkSelfPermission(Download_Activity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this,"No Permission",Toast.LENGTH_SHORT).show();
} else {
// new MyAsyncTask().execute();
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, file_url);
// Log.d("async","status "+asyncStatus);
/* try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}*/
// MyAsyncTask asyncTask = new MyAsyncTask();
// asyncTask.execute();
// downloadImageFromUrl();
// MyAsyncTask asyncTask = new MyAsyncTask();
// asyncTask.execute();
}
}
class MyAsyncTask extends AsyncTask<String, String, ArrayList<Integer>> {
private ProgressDialog progressDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
this.progressDialog = new ProgressDialog(Download_Activity.this);
this.progressDialog.setMessage("Downloading file…");
this.progressDialog.setIndeterminate(false);
this.progressDialog.setMax(100);
this.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
this.progressDialog.setCancelable(false);
this.progressDialog.show();
}
@Override
protected ArrayList<Integer> doInBackground(String... parms) {
// download_Btn.setVisibility(INVISIBLE);
for(Model_Download mddd:recList) {
Status status=(getStatus());
Log.d("status2","ids "+status);
String url_select = mddd.getPic_id();
id=mddd.getImages_id();
/* Log.d("id","pic id 1: "+id);
for(int i=0;i<recList.size();i++)
{
arr[i]=id=mddd.getImages_id();
Log.d("array","ids "+arr[i]);
}*/
try {
URL url = new URL(url_select);
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//urlConnection.setRequestMethod(REQUEST_METHOD);
urlConnection.setReadTimeout(READ_TIMEOUT);
urlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
//and connect!
urlConnection.connect();
//set the path where we want to save the file in this case, going to save it on the root directory of the sd card.
// File SDCardRoot = Environment.getExternalStorageDirectory();
File f = new File(Environment.getExternalStorageDirectory(), folder_main);
if (!f.exists()) {
f.mkdirs();
}
/* File folder = getFilesDir();
File f1= new File(folder, "doc_download");
f.mkdir();*/
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd'T'HHmmss", Locale.ENGLISH);
String timeStamp = dateFormat.format(new Date());
String filename = "image-" + timeStamp + ".jpg";
//create a new file, specifying the path, and the filename which we want to save the file as.
file = new File(f, filename);
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
int lengthOfFile = urlConnection.getContentLength();
//variable to store total downloaded bytes
long downloadedSize = 0;
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ((bufferLength = inputStream.read(buffer)) > 0) {
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
publishProgress("" + (int) ((downloadedSize * 100) / lengthOfFile));
Log.d("url", "Progress: " + (int) ((downloadedSize * 100) / lengthOfFile));
//this is where you would do something to report the prgress, like this maybe
// updateProgress(downloadedSize, totalSize);
/* MediaScannerConnection.scanFile(Download_Activity.this,
new String[] { file.toString() }, null,
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String folder_main, Uri uri) {
Log.i("ExternalStorage", "Scanned " + folder_main + ":");
Log.i("ExternalStorage", "-> uri=" + uri);
}
});*/
}
} catch (Exception e) {
e.printStackTrace();
}
Log.d("id","single id: "+id);
Status status1=getStatus();
Log.d("status","ids "+status);
helper.updateStatus(id);
ids.add(id);
// viewdata1(v);
//return String.valueOf(id);
}
return null;
}
protected void onProgressUpdate(String... progress) {
// setting progress percentage
progressDialog.setProgress(Integer.parseInt(progress[0]));
}
@Override
protected void onPostExecute(ArrayList<Integer> id) {
// id=mddd.getImages_id();
Log.d("id","pic id is: "+id);
super.onPostExecute(id);
this.progressDialog.dismiss();
/* if(getStatus() == AsyncTask.Status.FINISHED) {
}*/
/* for(int i : id) {
Log.d("ArrayList","pic id is: "+i);
update(i);
}*/
Toast.makeText(getApplicationContext(),"Image Downloaded to sd card XXX Folder",Toast.LENGTH_LONG).show();
// MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);
// next_Btn.setVisibility(View.VISIBLE);
MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);
/*next_Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MediaScannerConnection.scanFile(Download_Activity.this, new String[]{file.getPath()}, null, null);
}
});*/
/* cancel(true);
onCancelled();*/
Status status1=getStatus();
Log.d("cancel","ids "+status1);
viewdata(v);
}
}
@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Really Exit?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.no, null)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
Log.d("DB", "before ");
viewdata1(v);
//helper.getImagesFromDB(String.valueOf(status));
Log.d("DB", "after ");
finish();
}
}).create().show();
}
public void update(int image_id)
{
/* for (Model_Download md : recList) {
int ids = md.getImages_id();
id1 = md.getImages_id();
Log.d("urls", "wallet " + ids);*/
helper.updateStatus(image_id);
Messages.message(getApplicationContext(), "Updated");
}
public void viewdata(View view)
{
String data = helper.getData();
/* Log.d("data","updated status is : ");
Log.d("data","urls stored "+data);*/
Messages.message(this,data);
}
public void viewdata1(View view)
{
List<Model_Photos> data = helper.getURLS();
for(Model_Photos d : data) {
int id= d.getImages_id();
String url=d.getModelViewPhotoURL();
// Log.d("data","updated status is : ");
/* Log.d("database1", "data " + d);
Log.d("database1", "id is " + id);
Log.d("database1", "urls is " + url);*/
//Messages.message(this, d);
}
}
}