I have a listview with base adapter. each row in my list view contains image, title, download and view button and progress bar. initially progress bar and view button's visibility is GONE. when user press download button, progress bar should be visible. As soon as download is completed, download button should be gone and view button should visible.
My problem is: i am not able to change visibility of views from asynctask.
Here is my code.
public class PdfListAdapter extends BaseAdapter {
ArrayList<PdfDetails> arylstPdf = new ArrayList<PdfDetails>();
Context context;
String extStorageDirectory;
ViewHolder holder;
Activity activity;
public PdfListAdapter(Context context, ArrayList<PdfDetails> arylstPdf) {
super();
this.arylstPdf = arylstPdf;
this.context = context;
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
holder = new ViewHolder();
}
#Override
public int getCount() {
return arylstPdf.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
activity = (Activity) context;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.layout_pdf_list, null);
holder.tvPdfTitle = (TextView) convertView
.findViewById(R.id.tvPdfTitle);
holder.imgPdfImage = (ImageView) convertView
.findViewById(R.id.imgPdfImage);
holder.btnDownload = (Button) convertView
.findViewById(R.id.btnDownload);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.pbDownload = (ProgressBar) convertView
.findViewById(R.id.pbDownload);
holder.tvProgress = (TextView) convertView.findViewById(R.id.tvProgress);
holder.llProgress = (LinearLayout) convertView.findViewById(R.id.llProgress);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
File file = new File(extStorageDirectory + "/pdf", arylstPdf.get(
position).getPostTitle()
+ ".pdf");
if (file.exists()) {
holder.btnDownload.setVisibility(View.GONE);
holder.btnView.setVisibility(View.VISIBLE);
} else {
holder.btnDownload.setVisibility(View.VISIBLE);
holder.btnView.setVisibility(View.GONE);
}
holder.tvPdfTitle.setText(arylstPdf.get(position).getPostTitle());
ImageLoader objImageLoader = new ImageLoader(context);
objImageLoader.DisplayImage(arylstPdf.get(position).getAttachedImage(),
holder.imgPdfImage);
holder.btnDownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// NOT WORKING
holder.llProgress.setVisibility(View.VISIBLE);
Async async = new Async();
async.execute(Integer.toString(position));
}
});
holder.btnView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
readPDF(arylstPdf.get(position).getPostTitle());
}
});
return convertView;
}
class ViewHolder {
ImageView imgPdfImage;
TextView tvPdfTitle, tvProgress;
Button btnDownload;
Button btnView;
ProgressBar pbDownload;
LinearLayout llProgress;
}
class Async extends AsyncTask<String, String, String> {
File file, folder;
#Override
protected void onPreExecute() {
super.onPreExecute();
folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
}
#Override
protected String doInBackground(String... params) {
String fileName = arylstPdf.get(Integer.parseInt(params[0]))
.getPostTitle();
file = new File(folder, fileName + ".pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
int count;
try {
URL url = new URL(arylstPdf.get(Integer.parseInt(params[0]))
.getAttachedPdf());
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(Integer
.toString((int) ((total * 100) / lenghtOfFile)));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
holder.tvProgress.setText(progress[0]);
holder.pbDownload.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// NOT WORKING
holder.btnDownload.setVisibility(View.GONE);
holder.btnDownload.setVisibility(View.VISIBLE);
Toast.makeText(context, "Downloaded", Toast.LENGTH_SHORT).show();
}
}
}
Add a boolean flag in PdfDetails class change download and view button visibility in getView method.
so just change that boolean flag of that particular row in arraylist position.
and user adapter.notifyDataStateChanged();
Add getter setter method in PdfDetails class.
and in getView() method
use
PdfDetails detailBin = list.get(position);
if(detailBin.isDownloaded)
// view button visible and download button hide
else
// download button visible and view button hide
and in postExecute()
list.get(position).setDownload(true);
adapter.notifyDataStateChanged();
Instead of creating holder in the Adapter class itself can you let it be inside getView itself and pass it to AsyncTask constructor.
public class PdfListAdapter extends BaseAdapter {
ArrayList<PdfDetails> arylstPdf = new ArrayList<PdfDetails>();
Context context;
String extStorageDirectory;
Activity activity;
public PdfListAdapter(Context context, ArrayList<PdfDetails> arylstPdf) {
super();
this.arylstPdf = arylstPdf;
this.context = context;
extStorageDirectory = Environment.getExternalStorageDirectory()
.toString();
}
#Override
public int getCount() {
return arylstPdf.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater mInflater = LayoutInflater.from(context);
activity = (Activity) context;
final ViewHolder holder= null;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.layout_pdf_list, null);
holder = new ViewHolder();
holder.tvPdfTitle = (TextView) convertView
.findViewById(R.id.tvPdfTitle);
holder.imgPdfImage = (ImageView) convertView
.findViewById(R.id.imgPdfImage);
holder.btnDownload = (Button) convertView
.findViewById(R.id.btnDownload);
holder.btnView = (Button) convertView.findViewById(R.id.btnView);
holder.pbDownload = (ProgressBar) convertView
.findViewById(R.id.pbDownload);
holder.tvProgress = (TextView) convertView.findViewById(R.id.tvProgress);
holder.llProgress = (LinearLayout) convertView.findViewById(R.id.llProgress);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
File file = new File(extStorageDirectory + "/pdf", arylstPdf.get(
position).getPostTitle()
+ ".pdf");
if (file.exists()) {
holder.btnDownload.setVisibility(View.GONE);
holder.btnView.setVisibility(View.VISIBLE);
} else {
holder.btnDownload.setVisibility(View.VISIBLE);
holder.btnView.setVisibility(View.GONE);
}
holder.tvPdfTitle.setText(arylstPdf.get(position).getPostTitle());
ImageLoader objImageLoader = new ImageLoader(context);
objImageLoader.DisplayImage(arylstPdf.get(position).getAttachedImage(),
holder.imgPdfImage);
holder.btnDownload.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// NOT WORKING
holder.llProgress.setVisibility(View.VISIBLE);
Async async = new Async(holder);
async.execute(Integer.toString(position));
}
});
holder.btnView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
readPDF(arylstPdf.get(position).getPostTitle());
}
});
return convertView;
}
class ViewHolder {
ImageView imgPdfImage;
TextView tvPdfTitle, tvProgress;
Button btnDownload;
Button btnView;
ProgressBar pbDownload;
LinearLayout llProgress;
}
class Async extends AsyncTask<String, String, String> {
File file, folder;
ViewHolder holder;
public Async(ViewHolder holder) {
this.holder=holder;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
folder = new File(extStorageDirectory, "pdf");
folder.mkdir();
}
#Override
protected String doInBackground(String... params) {
String fileName = arylstPdf.get(Integer.parseInt(params[0]))
.getPostTitle();
file = new File(folder, fileName + ".pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
int count;
try {
URL url = new URL(arylstPdf.get(Integer.parseInt(params[0]))
.getAttachedPdf());
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
InputStream input = new BufferedInputStream(url.openStream(),
8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress(Integer
.toString((int) ((total * 100) / lenghtOfFile)));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onProgressUpdate(String... progress) {
holder.tvProgress.setText(progress[0]);
holder.pbDownload.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// NOT WORKING
holder.btnDownload.setVisibility(View.GONE);
holder.btnDownload.setVisibility(View.VISIBLE);
Toast.makeText(context, "Downloaded", Toast.LENGTH_SHORT).show();
}
}
}
You can not do any changes for UserInterface(UI) in other threads(Asynctasks) other than Main ui thread..
So you need to follow this
runOnUiThread(new Runnable() {
#Override
public void run() {
//Any UI changes can be done here
holder.btnDownload.setVisibility(View.GONE);
holder.btnView.setVisibility(View.VISIBLE);
}
});
Related
I am trying to download video file using async task. The video is downloading perfectly but the progress bar disappears before reaching the end and it starts downloading again. It doesn't happen when I am downloading image files.
Here is my code.
FileDownloadTask.Java
public class FileDownloadTask extends AsyncTask<String, Integer, String> {
private static final String TAG = FileDownloadTask.class.getSimpleName();
final DownloadInfo mInfo;
//public static String file_url = "http://www.gettyimages.ca/gi-resources/images/Homepage/Category-Creative/UK/UK_Creative_462809583.jpg";
//public static String file_url="http://imaze.net/apps/groups/123.mp4";
// Context context=getApplicationContext();
public FileDownloadTask(DownloadInfo info) {
mInfo = info;
}
#Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
ProgressBar bar = mInfo.getProgressBar();
if(bar != null) {
bar.setProgress(mInfo.getProgress());
bar.invalidate();
}
}
#Override
protected String doInBackground(String... f_url) {
int count;
try {
String root = Environment.getExternalStorageDirectory().toString();
System.out.println("Downloading");
URL url = new URL(mInfo.getFileUrl());
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
// Output stream to write file
File rootdirectory= new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES),"Youtube Videos");
if(!rootdirectory.exists())
{
rootdirectory.mkdirs();
}
String nameoffile= URLUtil.guessFileName(mInfo.getFileUrl(),null, MimeTypeMap.getFileExtensionFromUrl(mInfo.getFileUrl()));
File file= new File(rootdirectory,nameoffile);
file.createNewFile();
mInfo.setDownloadState(DownloadState.DOWNLOADING);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int)(total*1001)/lenghtOfFile);
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
// Intent intent=new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
// intent.setData(Uri.parse(file_url));
// getActivity().sendBroadcast(intent);
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
mInfo.setDownloadState(DownloadState.COMPLETE);
return null;
}
protected void onPostExecute(String file_url) {
mInfo.setDownloadState(DownloadState.COMPLETE);
}
#Override
protected void onPreExecute() {
mInfo.setDownloadState(DownloadState.DOWNLOADING);
}
}
DownloadInfo.Java
import android.util.Log;
import android.widget.ProgressBar;
public class DownloadInfo {
private final static String TAG = DownloadInfo.class.getSimpleName();
public enum DownloadState {
NOT_STARTED,
QUEUED,
DOWNLOADING,
COMPLETE
}
private volatile DownloadState mDownloadState = DownloadState.NOT_STARTED;
private String mFilename;
// private final String mFileUrl;
private Integer mFileSize;
private String mFileUrl="";
private volatile Integer mProgress;
// private final Integer mFileSize;
private volatile ProgressBar mProgressBar;
public DownloadInfo(String filename, String FileUrl) {
mFilename = filename;
mProgress = 0;
mFileUrl = FileUrl;
// mFileSize = mFileSize;
// mFileSize = size;
mProgressBar = null;
}
public ProgressBar getProgressBar() {
return mProgressBar;
}
public void setProgressBar(ProgressBar progressBar) {
Log.d(TAG, "setProgressBar " + mFilename + " to " + progressBar);
mProgressBar = progressBar;
}
public void setDownloadState(DownloadState state) {
mDownloadState = state;
}
public DownloadState getDownloadState() {
return mDownloadState;
}
public Integer getProgress() {
return mProgress;
}
public void setProgress(Integer progress) {
this.mProgress = progress;
}
//
// public Integer getFileSize() {
// return mFileSize;
// }
public Integer getFileSize() {
return mFileSize;
}
public void setFileSize(Integer FileSize) {
mFileSize = FileSize;
}
// public void setFileUrl(String FileUrl)
// {
// this.FileUrl = FileUrl;
// }
public String getFilename() {
return mFilename;
}
public String getFileUrl()
{
return mFileUrl;
}
}
DownloadInfoArrayAdapter.Java
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
// Simple class to make it so that we don't have to call findViewById frequently
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
Button button;
DownloadInfo info;
}
private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();
public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
List<DownloadInfo> objects) {
super(context, textViewResourceId, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
// We need to set the convertView's progressBar to null.
ViewHolder holder = null;
if(null == row) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.button = (Button)row.findViewById(R.id.downloadButton);
holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
holder.info.setProgressBar(null);
holder.info = info;
holder.info.setProgressBar(holder.progressBar);
}
holder.textView.setText(info.getFilename());
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(100);
info.setProgressBar(holder.progressBar);
holder.button.setEnabled(info.getDownloadState() == DownloadState.NOT_STARTED);
final Button button = holder.button;
holder.button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
info.setDownloadState(DownloadState.QUEUED);
button.setEnabled(false);
button.invalidate();
FileDownloadTask task = new FileDownloadTask(info);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
});
//TODO: When reusing a view, invalidate the current progressBar.
return row;
}
}
I want to read some book's data and show them in a listview and show book's picture using bitmap. I can show other information but I cant show picture and I cant finde why because I did what ever bitmapping needs and befor I use this AsyncTask method my pictures were showing!
and wonderful thing is when I click on an Item, download layout showing book's pic properly and when I Open AllBooksActivity from first place again, it is showing pics properly toO!!!
here is my AllBooksActivity code:
public class AllBooksActivity extends Activity {
public ListItem adapter;
public ListView allbooklist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_books);
new loadingbooks().execute();
}
private class loadingbooks extends AsyncTask<String, String, String> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllBooksActivity.this);
pDialog.setMessage("کتابها در حال بارگذاری، لطفا منتظر بمانید...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
String res = JSONCommands.readData(MainActivity.params);
return res;
}
#Override
protected void onPostExecute(String res) {
if(res != null){
pDialog.dismiss();
AllBooksActivity.this.getActionBar().setTitle(MainActivity.how);
allbooklist = (ListView) findViewById(R.id.list_all);
allbooklist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent in = new Intent(getApplicationContext(), DownloadActivity.class);
in.putExtra("MyClass", MainActivity.books_array.get(position));
startActivity(in);
}
});
adapter = new ListItem(AllBooksActivity.this, MainActivity.books_array);
allbooklist.setAdapter(adapter);
}
else {
pDialog.dismiss();
AlertDialog.Builder builder = new AlertDialog.Builder(AllBooksActivity.this)
.setTitle("خطا در برقراری ارتباط با سرور")
.setMessage("نمایش کتاب ناموفق :( اتصالات را بررسی کنید.");
builder.create().show();
}
}
}
here is my list adapter code:
public class ListItem extends BaseAdapter {
private int count;
private Context context;
private ArrayList<ShowBook> bookArray;
public ListItem(Context context, ArrayList<ShowBook> bookArray) {
this.count = bookArray.size();
this.context = context;
this.bookArray = bookArray;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return count;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
View row = inflater.inflate(R.layout.list_item, parent, false);
TextView namketabltxt, nevisandeltxt, mozooltxt, qeymatltxt;
ImageView tasvirlimg;
namketabltxt = (TextView) row.findViewById(R.id.ltxt_namketab);
nevisandeltxt = (TextView) row.findViewById(R.id.ltxt_nevisande);
mozooltxt = (TextView) row.findViewById(R.id.ltxt_mozoo);
qeymatltxt = (TextView) row.findViewById(R.id.ltxt_qeymat);
tasvirlimg = (ImageView)row.findViewById(R.id.limg_tasvir);
namketabltxt.setText(MainActivity.books_array.get(position).namketab);
nevisandeltxt.setText(MainActivity.books_array.get(position).nevisande);
mozooltxt.setText(MainActivity.books_array.get(position).mozoo);
qeymatltxt.setText(MainActivity.books_array.get(position).qeymat);
JSONCommands.getpic(MainActivity.books_array.get(position).tasvir, tasvirlimg);
return row;
}
}
here is my DownloadActivity code:
#SuppressLint("ShowToast") public class DownloadActivity extends Activity {
TextView namketabdtxt, nevisandedtxt, mozoodtxt, qeymatdtxt, uplodkonandedtxt;
ImageView tasvirdimg;
Button dlbtn;
RatingBar rb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
namketabdtxt = (TextView) findViewById(R.id.dtxt_namketab);
nevisandedtxt = (TextView) findViewById(R.id.dtxt_nevisande);
mozoodtxt = (TextView) findViewById(R.id.dtxt_mozoo);
uplodkonandedtxt = (TextView) findViewById(R.id.dtxt_uplodkonande);
qeymatdtxt = (TextView) findViewById(R.id.dtxt_qeymat);
tasvirdimg = (ImageView) findViewById(R.id.dimg_tasvir);
dlbtn = (Button)findViewById(R.id.btn_dl);
rb = (RatingBar) findViewById(R.id.ratingBar1);
final ShowBook book = (ShowBook) getIntent().getSerializableExtra("MyClass");
this.getActionBar().setTitle(book.namketab);
namketabdtxt.setText(book.namketab);
nevisandedtxt.setText(book.nevisande);
mozoodtxt.setText(book.mozoo);
uplodkonandedtxt.setText(book.uplodkonande);
qeymatdtxt.setText(book.qeymat);
JSONCommands.getpic(book.tasvir, tasvirdimg);
dlbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
DownloadFileFromURL downloader = new DownloadFileFromURL();
//downloader.setDownloadedFileName()
String name = book.fileketab.substring(book.fileketab.lastIndexOf("/") + 1);
downloader.setDownloadedFileName(name);
downloader.execute(JSONCommands.firstURL + book.fileketab);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.download, menu);
return true;
}
private class DownloadFileFromURL extends AsyncTask<String, String, String> {
private String downloadedfileName;
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "بارگذاری کتاب باموفقیت انجام شد", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "برای دیدن آن به کتابخانه مراجعه نمایید", Toast.LENGTH_LONG).show();
}
public void setDownloadedFileName(String downloadedfileName){
this.downloadedfileName = downloadedfileName;
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... surl) {
int count;
try {
URL url = new URL(surl[0]);
URLConnection conection = url.openConnection();
conection.connect();
// this will be useful so that you can show a typical 0-100%
// progress bar
int lenghtOfFile = conection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(url.openStream(),
8192);
// Output stream
//OutputStream output = new FileOutputStream(Environment
// .getExternalStorageDirectory().toString()
// + "/data/" + downloadedfileName);
OutputStream output = new FileOutputStream(getFilesDir()+File.separator +downloadedfileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
// publishProgress("" + (int) ((total * 100) / lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
}
/**
* After completing background task called
* **/
}
and here is my getpic code using Bitmap(this function is in my JSONCommands class and that is why I called them as "JSONCommands.getpic"):
public static void getpic(String str, ImageView tasvir){
Bitmap bitmap;
if(str != null){
bitmap = getBitmapFromURL(firstURL+ str);
if(bitmap!=null){
tasvir.setImageBitmap(bitmap);
}
else{
tasvir.setImageResource(R.drawable.p3_books);
}
}
else{
tasvir.setImageResource(R.drawable.p3_books);
}
}
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);
connection.disconnect();
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I cant find the solution and it drives me crazy:) please help, tank you.
I'm developing an Android app but I'm a newbie and I got stuck...
My ListView single element has an ImageView and some TextViews, but sometimes (when I scroll the page and there are more than 7-8 elements) it doesn't display the right image in the right row.
I'm using a custom Image Loader to manage the downloaded images.
Here's my Adapter:
public class AddVideogameActivityAdapter extends BaseAdapter {
private ArrayList<Videogame> videogames;
private Typeface typefaceMedium;
private Typeface typefaceLight;
private ImageLoader loader;
private LayoutInflater mInflater;
public AddVideogameActivityAdapter(Context context, ArrayList<Videogame> results) {
videogames = results;
mInflater = LayoutInflater.from(context);
typefaceMedium = Typeface.createFromAsset(context.getAssets(), "Roboto-Medium.ttf");
typefaceLight = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf");
loader = new ImageLoader(context);
}
public int getCount() {
return videogames.size();
}
public Object getItem(int position) {
return videogames.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_element,null);
holder = new ViewHolder();
holder.imgView = (ImageView) convertView.findViewById(R.id.thumbView);
holder.txtName = (TextView) convertView.findViewById(R.id.elementView);
holder.txtPlatform = (TextView) convertView.findViewById(R.id.elementView2);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
try {
Videogame vgame = (Videogame) videogames.get(position);
holder.txtName.setText(vgame.getTitle());
holder.txtName.setTypeface(typefaceMedium);
holder.txtPlatform.setText(videogames.get(position).getPlatform());
holder.txtPlatform.setTypeface(typefaceLight);
holder.imgUrl = videogames.get(position).getImage();
loader.display(holder.imgUrl, holder.imgView, R.drawable.youtube_icon);
}
catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPlatform;
public String imgUrl;
ImageView imgView;
}
}
Sorry for my english and thank you for your help!
EDIT:
Here's also the Loader:
public class ImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
public ImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new TCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private 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) {
e.printStackTrace();
return null;
}
}
}
}
RE-EDIT
Activity code:
public class AddVideogameActivity extends ListActivity {
private TextView searchField = null;
private final Handler handler = new Handler();
private ArrayList<Videogame> videogamesList = null;
private static AddVideogameActivity mContext = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
mContext = this;
searchField = (TextView) findViewById(R.id.searchField);
searchField.setMaxLines(1);
searchField.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
searchField.setHint("");
}
});
// Setup the list view and its listener
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(MainActivity.TAG,
"AddBookActivity ---> AddButton:onClick()");
// Sets typefaces for TextView
String videogameId = videogamesList.get(position).getId();
String videogameName = videogamesList.get(position).getTitle();
String thumbnail = videogamesList.get(position).getThumbnail();
String description = videogamesList.get(position)
.getDescription();
String image = videogamesList.get(position).getImage();
String platform = videogamesList.get(position).getPlatform();
if (videogameName != null && videogameName.length() > 0
&& thumbnail != null && thumbnail.length() > 0
&& description != null && description.length() > 0
&& image != null && image.length() > 0
&& platform != null && platform.length() > 0) {
if (ListsManager.getInstance().addVideogame(
new Videogame(videogameId, videogameName,
thumbnail, image, description, platform)) == 0) {
Log.d(MainActivity.TAG,
"AddBookActivity --> Videogame:[" + videogameId
+ "#" + videogameName + "]");
Toast toast = Toast.makeText(mContext, "["
+ videogameName + "] Saved !",
Toast.LENGTH_LONG);
toast.show();
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Videogame already in the list ! ");
Toast toast = Toast.makeText(mContext,
"Error! Videogame already in the list!",
Toast.LENGTH_LONG);
toast.show();
}
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Invalid Videogame Name or Thumbnail or Id or Deck");
Toast toast = Toast
.makeText(
mContext,
"Error ! Invalid Videogame Name or Thumbnail or Id or Deck",
Toast.LENGTH_LONG);
toast.show();
}
Intent newIntent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(newIntent);
}
});
// Setup the search button and its listener
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Search Game ...");
String searchInputString = searchField.getText().toString();
if (searchInputString != null && searchInputString.length() > 0) {
try {
String requestURL = ("http://www.giantbomb.com/api/search/?api_key=fcf60d6d67b98b0d17b3905d1a90b3fd31ed1e8e&format=json&query="
+ Uri.encode(searchInputString) + "&resources=game");
// String requestURL =
// String.format("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=Music&orderby=relevance&q=%s",Uri.encode(searchInputString));
Log.d(com.example.ludos2_0.MainActivity.TAG, requestURL);
DownloadGiantBombJSONData giantbombAsyncTask = new DownloadGiantBombJSONData();
giantbombAsyncTask.execute(new String[] { requestURL });
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
if (videogamesList == null)
videogamesList = new ArrayList<Videogame>();
else
updateVideogamesListView(videogamesList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_book, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
public void updateVideogamesListView(ArrayList<Videogame> values) {
AddVideogameActivityAdapter adapter = new AddVideogameActivityAdapter(this, values);
setListAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
The other classes involved in building the ListView are the REST classes and the AsyncTask class that downloads and parses the JSon files.
What does your ListView look like, does it look like this:
<ListView android:id="#id/android:list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" ></ListView>
Especially the id of the ListView. Check your layout file, probably the bug exists there.
In the above image, there is a list view which contains list of items that the user can download. This is the image which tells user that he can download the file. On completion of download, the image will change to . My problem is when I download a file, the status image(which denotes that download has completed) gets changed for another row, instead, it should change for the row that I had selected. At present, if I download first file in the list, the image gets changed for 4th or 5th item in the list. Also, when I try to download any other file from the list. it opens up last downloaded file(This is functionality of the app that if file is already downloaded, then open it in pdf reader),i.e., if I download 1st file in the list and then go for second item,then instead of downloading 2nd file, it opens up last downloaded file. More over, if I scroll the listview, the status of download gets changed for other items in the list also. Below,is my adapter code:
public class DownloadListAdapter extends BaseAdapter {
Context ctx;
public ArrayList<DownloadListDao> mDownloadList;
String readMoreLink;
public static final String TAG = "DownloadListAdapter";
ProgressDialog mProgressDialog;
private boolean isSDCardPresent;
File tieDir;
int downloadState[];
public DownloadListAdapter(Context ctx,
ArrayList<DownloadListDao> mDownloadList) {
this.ctx = ctx;
this.mDownloadList = mDownloadList;
downloadState = new int [mDownloadList.size()];
for(int i = 0; i < mDownloadList.size(); i++) {
downloadState[i] = 0;
}
tieDir = new File(Environment.getExternalStorageDirectory().toString()
+ "/tie");
}// Constructor
public int getCount() {
return this.mDownloadList.size();
}// getCount
public Object getItem(int position) {
return this.mDownloadList.get(position);
}// getItem
public long getItemId(int position) {
return 0;
}// getItemId
static class ViewHolder {
TextView txtTitle, txtTheme, txtDate;
ImageView imgDownload;
}// ViewHolder
ViewHolder holder;
public View getView(final int position, View convertView, ViewGroup parent) {
final String url = mDownloadList.get(position).getUrl();
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(
R.layout.downlist_adapter, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.txtTitle);
holder.txtTheme = (TextView) convertView
.findViewById(R.id.txtTheme);
holder.txtDate = (TextView) convertView.findViewById(R.id.txtDate);
holder.imgDownload = (ImageView) convertView
.findViewById(R.id.imgDload);
holder.imgDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File mediaFile = null;
if (url != null && !url.equals("null") && !url.equals("")) {
String fileName = url.toString().substring(
url.toString().lastIndexOf("/") + 1,
url.toString().length());
mediaFile = new File(tieDir, fileName);
}
processFile(mediaFile, url, position);
int pos = (Integer)v.getTag();
downloadState[pos] = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
if (mDownloadList != null && mDownloadList.size() > 0) {
if (mDownloadList.get(position).getTitle() != null
&& !mDownloadList.get(position).getTitle().equals("null")
&& !mDownloadList.get(position).getTitle().equals("")) {
holder.txtTitle.setText(mDownloadList.get(position).getTitle());
}
if (mDownloadList.get(position).getTheme() != null
&& !mDownloadList.get(position).getTheme().equals("null")
&& !mDownloadList.get(position).getTheme().equals("")) {
holder.txtTheme.setText(mDownloadList.get(position).getTheme());
}
if (mDownloadList.get(position).getDate() != null
&& !mDownloadList.get(position).getDate().equals("null")
&& !mDownloadList.get(position).getDate().equals("")) {
holder.txtDate.setText(mDownloadList.get(position).getDate());
}
if (downloadState[position] == 1) {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dloaded));
} else {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dload));
}
}
holder.imgDownload.setTag(position);
return convertView;
}// getView
protected void downloadFile(String url, int position, String fileName) {
Log.v(TAG, "Preparing to download");
mProgressDialog = new ProgressDialog(ctx);
mProgressDialog.setMessage("Dowloading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
isSDCardPresent = Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED);
if (!isSDCardPresent) {
noSDCardAlert(ctx);
} else {
if ((tieDir.exists()) && (tieDir != null)) {
if (NetworkConnection.isOnline(ctx)) {
if (tieDir.isDirectory()) {
Log.v(TAG, "if tie dir URL:::" + url);
new DownloadAudioAsync(ctx, position, fileName).execute(url);
}
} else {
((DownloadListActivity) ctx)
.OpenNetErrDialog("Please check your internet connection...");
}
} else {
boolean isDirectoryCreated = tieDir.mkdirs();
if (isDirectoryCreated) {
Log.v(TAG, "if tie not dir URL:::" + url);
if (NetworkConnection.isOnline(ctx)) {
new DownloadAudioAsync(ctx, position, fileName).execute(url);
} else {
((DownloadListActivity) ctx)
.OpenWiFiDialog("Please check your internet connection...");
}
}
}
}
}
private void noSDCardAlert(Context ctx) {
AlertDialog.Builder ad = new AlertDialog.Builder(ctx);
ad.setMessage("No sd card present..");
ad.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
if (!((DownloadDetail) ctx).isFinishing()) {
ad.show();
}
}
public void OpenDialog(String messageID) {
final Dialog dialog = new Dialog(ctx,
android.R.style.Theme_Translucent_NoTitleBar);
dialog.setContentView(R.layout.dialog_base);
dialog.getWindow().getAttributes().windowAnimations = android.R.style.Animation_Dialog;
dialog.setCancelable(false);
TextView alertMessage = (TextView) dialog.findViewById(R.id.txtMessage);
Button btnOK = (Button) dialog.findViewById(R.id.btnOk);
btnOK.setText("Show");
alertMessage.setText(messageID);
dialog.show();
btnOK.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
protected void showPdf(File mediaFile) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(mediaFile), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
ctx.startActivity(intent);
}
public class DownloadAudioAsync extends AsyncTask<String, String, String> {
Context ctx;
int pos;
private ProgressDialog pd;
String fileName;
public DownloadAudioAsync(Context ctx, int pos, String fileName) {
this.ctx = ctx;
this.pos = pos;
this.fileName = fileName;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Log.v(TAG, "inside on pre execute");
pd = new ProgressDialog(ctx);
pd.setMessage("Downloading...\nPlease wait..");
pd.show();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
Log.v(TAG,
"inside do in background with url::"
+ aurl[0].toString());
aurl[0] = aurl[0].replaceAll(" ", "%20");
URL url = new URL(aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
fileName = URLDecoder.decode(fileName, "UTF-8");
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(tieDir + "/"
+ fileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress("" + (int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String unused) {
if (!((DownloadListActivity) ctx).isFinishing()) {
pd.dismiss();
updateView(pos);
}
}
private void updateView(int pos) {
View v = ((DownloadListActivity) ctx).menuListView.getChildAt(pos
- ((DownloadListActivity) ctx).menuListView
.getFirstVisiblePosition());
ImageView imgDloadBtn = (ImageView) v.findViewById(R.id.imgDload);
imgDloadBtn.setImageDrawable(ctx.getResources().getDrawable(
R.drawable.ic_dloaded));
notifyDataSetChanged();
}
}
private void processFile(File mediaFile, String url, int pos) {
if (url != null && !url.equals("null") && !url.equals("")) {
if (mediaFile != null) {
Log.v(TAG, "in processFile FileName " + mediaFile.getName());
Log.v(TAG, "in processFile Position " + pos);
if(!mediaFile.exists()) {
Log.v(TAG, "in processFile Media file doesn't exists");
downloadFile(url, pos, mediaFile.getName());
} else {
Log.v(TAG, "in processFile Media file exists");
try {
showPdf(mediaFile);
} catch (ActivityNotFoundException anfe) {
OpenDialog("PDF Reader is not installed on your device.");
}
}
}
}
}
}// DownloadAdapter
I had read this post for recycling the view(Thanks to Knickedi for in depth explaination). But, I can't figure out where is actual problem.
Issue with getview Method which keep recreating whenever you scroll your view, to handle exact position you have to play with setTag & getTag,check below few stackvoerflow answers to understand setTag & getTag:
Button in ListView using ArrayAdapter
Getting radio button value from custom list in android
and even store downloaded state into one booleanarray like below:
int boxState[];
within adapter constructor, set zero initially:
for (int i = 0; i < getData.size(); i++) {
boxState[i] = 0;
}
within adapter getview method:
holder.imgDownload.setTag(position);
Now you click on download button set value as 1 (Inside onclick of button):
pos = (Integer) v.getTag();
boxState[pos]=1;
At last when you scroll your view check condition into following way(put below code inside getview method):
if (boxState[position] == 0) {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dloaded)); //which aren't downloaded
} else {
holder.imgDownload.setImageDrawable(ctx.getResources()
.getDrawable(R.drawable.ic_dload)); // which are downloaded.
}
I have grid containing images. On click of images, downloading of book starts. If the download is in progress and if i am clicking that image only the download getting started. Due to this the resultant file is corrupted. The downloading task has been put on the onClick event of image. I have tried to make first image clickable false then setEnable false. but both the way didn't work for me. The image click is working even download is in progress. Please guide.
For details,Here is my codes:
public class GridViewAdapter extends BaseAdapter {
ImageView imageView;
private Context context;
private int item;
private LayoutInflater layoutInflater;
GridViewAdapter(Context c, int griditem) {
this.context = c;
this.item = griditem;
this.layoutInflater = (LayoutInflater) c
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return bank.size();
}
#Override
public Object getItem(int position) {
return bank.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
View grid;
Display display = ((WindowManager) context
.getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
int orientation = display.getOrientation();
if (convertView == null) {
grid = new View(context);
grid = layoutInflater.inflate(item, null);
} else {
grid = (View) convertView;
}
final TextView title = (TextView) grid.findViewById(R.id.mgntitle);
title.setText(bank.get(position).getTitle());
imageView = (ImageView) grid.findViewById(R.id.thumbnail);
imageView.setImageResource(R.drawable.icon);
final ProgressBar progress = (ProgressBar) grid
.findViewById(R.id.progress);
final ImageView downloadmark = (ImageView) grid
.findViewById(R.id.downloadmark);
String pdfLink = bank.get(position).getPdfLink();
String filename = pdfLink.substring(pdfLink.lastIndexOf("/") + 1);
final File targetDir = new File(fileLocation + filename);
if(targetDir.exists()){
downloadmark.setVisibility(View.VISIBLE);
}
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!targetDir.exists()) {
if (isInternetConnected()) {
map.put(bank.get(position).getTitle(), progress);
new DownloadPdfFile(GridDisplayActivity.this, bank
.get(position).getPdfLink(), progress,
downloadmark, imageView).execute();
} else {
setAlertBox("You are not connected to Internet. Please switch your connection ON to be able to Downlaod Bespoken Magazines");
}
} else {
Toast.makeText(context, "File exists",
Toast.LENGTH_LONG).show();
// Book opening intent has to be fried here
}
}
});
imageView.setImageBitmap(BitmapFactory.decodeByteArray(
bank.get(position).getCoverPages(), 0, bank.get(position)
.getCoverPages().length));
if (!getPrefName(filename).equalsIgnoreCase("NA")) {
if (new File(fileLocation + filename).exists()) {
// tag.setImageResource(R.drawable.bookmark);
downloadmark.setVisibility(View.VISIBLE);
} else {
SharedPreferences pref = getApplicationContext()
.getSharedPreferences("BESPOKEN_PREF",
MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(filename, "NA");
editor.commit();
}
}
if (new File(fileLocation + filename).exists()) {
if (!getPrefName(filename).equalsIgnoreCase("NA")) {
// tag.setImageResource(R.drawable.bookmark);
// downloadmark.setVisibility(View.VISIBLE);
} else {
}
}
return grid;
}
}
private String getPrefName(String name) {
SharedPreferences pref = this.getSharedPreferences("BESPOKEN_PREF",
MODE_WORLD_WRITEABLE);
return pref.getString(name, "NA");
}
private void saveBookName(String title) {
SharedPreferences pref = this.getSharedPreferences("BESPOKEN_PREF",
MODE_WORLD_WRITEABLE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(title, title);
editor.commit();
}
private boolean isInternetConnected() {
connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mMobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
return mWifi.isConnected() || mMobile.isConnected();
}
private class DownloadPdfFile extends AsyncTask<Void, Integer, Void> {
private int progressupdate;
String link;
ProgressBar progress;
ImageView cover;
String file;
ImageView dwnloadmark;
public DownloadPdfFile(GridDisplayActivity activity, String link,
ProgressBar progressbar, ImageView dwnmrk, ImageView imageView) {
imageView.setEnabled(false);
progress = progressbar;
this.link = link;
this.cover = imageView;
this.dwnloadmark = dwnmrk;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
cover.setEnabled(false);
progress.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
file = link.substring(link.lastIndexOf("/") + 1);
InputStream is = null;
long startTime = 0;
int count;
// DownloadFromUrl(link, fileLocation + file,progress);
try {
URL url = new URL(link);
File dir = new File(fileLocation);
if (dir.exists()) {
} else {
Log.i("",
"---------targetDir not .exists()----------------4");
dir.mkdirs();
}
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileLocation + file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
return null;
}
#Override
protected void onProgressUpdate(Integer... prog) {
progressupdate = prog[0];
progress.setProgress(progressupdate);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dwnloadmark.setVisibility(View.VISIBLE);
// tag.setImageResource(R.drawable.bookmark);
progress.setVisibility(View.INVISIBLE);
saveBookName(file);
cover.setEnabled(true);
}
}
class DoBackgroundTask extends CustomAsyncTask<Void, Integer, Void> {
private static final String TAG = "DoBackgroundTask";
private int progressupdate;
String link;
private ProgressBar progress;
ImageView dwnloadmark;
ImageView cover;
String file;
GridDisplayActivity activity;
public DoBackgroundTask(GridDisplayActivity activity, String link,
ProgressBar progressbar, ImageView dwnmrk, ImageView img) {
super(activity);
img.setEnabled(false);
this.activity = activity;
progress = progressbar;
this.link = link;
this.dwnloadmark = dwnmrk;
this.cover = img;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
cover.setEnabled(false);
progress.setVisibility(View.VISIBLE);
}
#Override
protected void onActivityDetached() {
if (progress != null) {
//progress.setActivated(false);
// progress = null;
}
}
#Override
protected void onActivityAttached() {
//progress.setActivated(true);
progress.setVisibility(View.VISIBLE);
progress.setProgress(progressupdate);
// showProgressDialog();
}
#Override
protected Void doInBackground(Void... params) {
file = link.substring(link.lastIndexOf("/") + 1);
InputStream is = null;
long startTime = 0;
int count;
// DownloadFromUrl(link, fileLocation + file,progress);
try {
URL url = new URL(link);
File dir = new File(fileLocation);
if (dir.exists()) {
} else {
dir.mkdirs();
}
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(fileLocation + file);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
publishProgress((int) ((total * 100) / lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("ImageManager",
"download ready in"
+ ((System.currentTimeMillis() - startTime) / 1000)
+ " sec");
return null;
}
#Override
protected void onProgressUpdate(Integer... prog) {
progressupdate = prog[0];
if (mActivity != null) {
progress.setProgress(progressupdate);
} else {
Log.d(TAG, "Progress updated while no Activity was attached.");
}
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
dwnloadmark.setVisibility(View.VISIBLE);
cover.setEnabled(true);
saveBookName(file);
if (mActivity != null) {
progress.setVisibility(View.INVISIBLE);
Toast.makeText(mActivity, "AsyncTask finished",
Toast.LENGTH_LONG).show();
} else {
}
}
}
public class GridViewAdapter extends BaseAdapter {
private boolean _buttonPressed = false;
.....
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(_buttonPressed){
return;
}
_buttonPressed = true;
.........
.....
private class DownloadPdfFile extends AsyncTask<....> {
.....
#Override
protected void onPostExecute(....) {
_buttonPressed = false;
}
.....
}
}