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;
}
}
Related
Well, I'm having listview containing audio files, Audio playing is working fine but seekbar is not updating, when i click at any item! last position item seekbar is getting updating and playing. I didn't find the exact solution. Here is my code.
public class AudioAdapter extends android.widget.BaseAdapter
{
final ViewHolder holder;
Uri uri;
private Dialog dialog;
TextView cur_val;
Activity act;
private Boolean isButtonClicked=false;
private LruCache<String, Bitmap> mMemoryCache;
private Context mcontext;
AppUtils appUtils;
MediaPlayer mp=new MediaPlayer();
ArrayList<HashMap<String, String>> listname;
ProgressBar pb;
int downloadedSize = 0;
int totalSize = 0;
String media,title;
public AudioAdapter(Context context,Activity act, ArrayList<HashMap<String, String>> value)
{
mcontext=context;
listname=value;
this.act = act;
// Memory Cache
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
final int cacheSize = maxMemory / 8;
mMemoryCache = new LruCache<String, Bitmap>(cacheSize)
{
#Override
protected int sizeOf(String key, Bitmap bitmap) {
// The cache size will be measured in kilobytes rather than
// number of items.
return bitmap.getByteCount() / 1024;
}
};
appUtils = new AppUtils(mcontext);
holder = new ViewHolder();
}
#Override
public int getCount() {
return listname.size();
}
#Override
public Object getItem(int position) {
return listname.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
convertView=View.inflate(mcontext, R.layout.audioreff, null);
holder.title=(TextView)convertView.findViewById(R.id.audiotitle);
holder.postedby=(TextView)convertView.findViewById(R.id.postedby);
holder.postedon=(TextView)convertView.findViewById(R.id.date);
holder.likes=(TextView)convertView.findViewById(R.id.likes);
holder.play=(Button)convertView.findViewById(R.id.butplay);
holder.seekBar=(SeekBar)convertView.findViewById(R.id.seekBar);
holder.seekBar.setMax(99);
holder.seekBar.setEnabled(false);
convertView.setTag(holder);
HashMap<String, String> result=listname.get(position);
final String titlee=result.get("title");
String postedy=result.get("postedby");
String postedon=result.get("datetime");
String likes=result.get("likes");
final String medi=result.get("media");
holder.title.setText(titlee);
holder.postedby.setText(postedy);
holder.postedon.setText(postedon);
holder.likes.setText(likes);
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// isButtonClicked = !isButtonClicked; // toggle the boolean flag
// v.setBackgroundResource(isButtonClicked ? R.drawable.buttonplay : R.drawable.pausebutton);
showProgress();
media=medi;
title=titlee;
Toast.makeText(mcontext,media+position, Toast.LENGTH_SHORT).show();
Log.d("",AppConstantsUtils.BASE_URL+medi);
new Thread(new Runnable() {
#Override
public void run() {
downloadFile();
}
}).start();
}
});
return convertView;
}
static class ViewHolder
{
TextView title,postedby,likes,postedon;
Button play;
SeekBar seekBar;
}
private void downloadFile(){
try {
URL url = new URL(AppConstantsUtils.BASE_URL+media);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true);
//connect
urlConnection.connect();
final String folder_main = "Apna";
//set the path where we want to save the file
/* File SDCardRoot =new File(Environment.getExternalStorageDirectory(),folder_main);
if (!SDCardRoot.exists()) {
SDCardRoot.mkdirs();
}
//create a new file, to save the downloaded file
File file = new File(SDCardRoot,title);*/
File wallpaperDirectory = new File(Environment.getExternalStorageDirectory(),folder_main);
//have the object build the directory structure, if needed.
wallpaperDirectory.mkdirs();
//create a File object for the output file
final String perfection=title.replaceAll("\"","");
File outputFile = new File(wallpaperDirectory, perfection+".mp3");
//now attach the OutputStream to the file object, instead of a String representation
FileOutputStream fileOutput = new FileOutputStream(outputFile);
//Stream used for reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file which we are downloading
totalSize = urlConnection.getContentLength();
act.runOnUiThread(new Runnable() {
public void run() {
pb.setMax(totalSize);
}
});
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0;
while ( (bufferLength = inputStream.read(buffer)) > 0 ) {
fileOutput.write(buffer, 0, bufferLength);
downloadedSize += bufferLength;
// update the progressbar //
act.runOnUiThread(new Runnable() {
public void run() {
pb.setProgress(downloadedSize);
float per = ((float)downloadedSize/totalSize) * 100;
cur_val.setText("Downloaded " + downloadedSize + "KB / " + totalSize + "KB (" + (int)per + "%)" );
}
});
}
//close the output stream when complete //
fileOutput.close();
act.runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
try{
mp.setDataSource(Environment.getExternalStorageDirectory().getPath()+"/Apna/"+perfection+".mp3");//Write your location here
mp.prepareAsync();
// mp.start();
mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
mRunnable.run();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
} catch (final MalformedURLException e) {
showError("Error : MalformedURLException " + e);
Log.d("dfdsfsd", e.toString());
e.printStackTrace();
} catch (final IOException e) {
Log.d("dfdsfsd", e.toString());
showError("Error : IOException " + e);
e.printStackTrace();
}
catch (final Exception e) {
Log.d("dfdsfsd", e.toString());
showError("Error : Please check your internet connection " + e);
}
}
private void showError(final String err){
act.runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(mcontext, err, Toast.LENGTH_LONG).show();
Log.d("dfdsfsd", err);
}
});
}
private void showProgress(){
dialog = new Dialog(mcontext);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.myprogressdialog);
dialog.setTitle("Download Progress");
cur_val = (TextView) dialog.findViewById(R.id.cur_pg_tv);
cur_val.setText("Starting download...");
dialog.show();
pb = (ProgressBar)dialog.findViewById(R.id.progress_bar);
pb.setProgress(0);
pb.setProgressDrawable(mcontext.getResources().getDrawable(R.drawable.green_progress));
}
private Handler mHandler = new Handler();
private Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mp != null) {
//set max value
int mDuration = mp.getDuration();
holder.seekBar.setMax(mDuration);
//update total time text view
//set progress to current position
int mCurrentPosition = mp.getCurrentPosition();
holder.seekBar.setProgress(mCurrentPosition);
//update current time text view
//handle drag on seekbar
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mp != null && fromUser){
mp.seekTo(progress);
}
}
});
}
//repeat above code every second
mHandler.postDelayed(this, 10);
}
};
}
Don't make the views of a item of ListView global variables of the adapter. Because there is not only one item on the screen. If you make them global, the values of these variables will be filled with the list-item that will calls getView at last.
Instead you might keep them in array of views, and update corresponding values (like position of seekBar) on the basis of the position.
In short, your implementation is incorrect. First, you need to understand the working of ListView.
Change the getView() method
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
YourHolder holder=null;
if(convertView==null){
holder=new YourHolder();
convertView=View.inflate(mcontext, R.layout.audioreff, null);
holder.title=(TextView)convertView.findViewById(R.id.audiotitle);
holder.postedby=(TextView)convertView.findViewById(R.id.postedby);
holder.postedon=(TextView)convertView.findViewById(R.id.date);
holder.likes=(TextView)convertView.findViewById(R.id.likes);
holder.play=(Button)convertView.findViewById(R.id.butplay);
holder.seekBar=(SeekBar)convertView.findViewById(R.id.seekBar);
holder.seekBar.setMax(99);
holder.seekBar.setEnabled(false);
convertView.setTag(holder);
}else{
holder=(YourHolder)convertView.getTag();
}
HashMap<String, String> result=listname.get(position);
final String titlee=result.get("title");
String postedy=result.get("postedby");
String postedon=result.get("datetime");
String likes=result.get("likes");
final String medi=result.get("media");
holder.title.setText(titlee);
holder.postedby.setText(postedy);
holder.postedon.setText(postedon);
holder.likes.setText(likes);
holder.play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// isButtonClicked = !isButtonClicked; // toggle the boolean flag
// v.setBackgroundResource(isButtonClicked ? R.drawable.buttonplay : R.drawable.pausebutton);
showProgress();
media=medi;
title=titlee;
Toast.makeText(mcontext,media+position, Toast.LENGTH_SHORT).show();
Log.d("",AppConstantsUtils.BASE_URL+medi);
new Thread(new Runnable() {
#Override
public void run() {
downloadFile();
}
}).start();
}
});
return convertView;
}
Don't make holder variable global. If you make it as global the last item value of getView is keep there. In the above case, that problem solved. Just read the holder mechanism in list view.
This will help you
This is simple Android project that I did. I get no warnings or errors while running. But the ListView doesn't get populated. I don't understand what's going wrong.
Since I dont' understand where is the exact problem and copy-pasting all the code won't help, here is my project code repository: https://bitbucket.org/geejo/msk-v2
Any kind of help will be appreciated
MSKFragment.java
public class MSKFragment extends android.support.v4.app.Fragment implements android.support.v4.app.LoaderManager.LoaderCallbacks<Cursor>
{
private ServiceAdapter mServiceAdapter;
public static final int SERVICE_LOADER = 0;
private static final String[] SERVICE_COLUMNS =
{
ServiceContract.ServiceEntry.TABLE_NAME,
ServiceContract.ServiceEntry._ID,
ServiceContract.ServiceEntry.COLUMN_NAME,
ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME,
ServiceContract.ServiceEntry.COLUMN_PRICE
};
public static final int COL_ID = 0;
public static final int COL_NAME = 1;
public static final int COL_ORG_NAME = 2;
public static final int COL_PRICE = 3;
public MSKFragment()
{
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
getLoaderManager().initLoader(SERVICE_LOADER, null, this);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater)
{
inflater.inflate(R.menu.menu_fragment_msk, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_refresh)
{
//Moving functions to a helper class, so that when Activity starts the data can be displayed
updateServices();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
mServiceAdapter = new ServiceAdapter(getActivity(), null, 0);
View rootView = inflater.inflate(R.layout.fragment_msk, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listViewMainService);
listView.setAdapter(mServiceAdapter);
return rootView;
}
#Override
public void onStart()
{
super.onStart();
//Refresh called and service updated when activity starts
updateServices();
}
//Calling FetchServiceTask and executing it.
private void updateServices()
{
FetchServicesTask serviceTask = new FetchServicesTask(getActivity());
serviceTask.execute();
}
#Override
public android.support.v4.content.Loader<Cursor> onCreateLoader(int i, Bundle args)
{
Uri serviceUri = ServiceContract.ServiceEntry.buildServiceUri(i);
return new android.support.v4.content.CursorLoader(getActivity(), serviceUri, null, null, null, null);
}
#Override
public void onLoadFinished(android.support.v4.content.Loader<Cursor> loader, Cursor data)
{
mServiceAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(android.support.v4.content.Loader<Cursor> loader)
{
mServiceAdapter.swapCursor(null);
}
}
FetchServices.java (AsyncTasks)
public class FetchServicesTask extends AsyncTask<String, Void, Void>
{
private final String LOG_TAG = FetchServicesTask.class.getSimpleName();
private final Context mContext;
private boolean DEBUG = true;
public FetchServicesTask(Context context )
{
mContext = context;
}
private String[] getServicesDatafromJson(String serviceJsonStr) throws JSONException
{
final String MSK_NAME = "name";
final String MSK_PRICE = "price";
final String MSK_ORG_NAME = "organizationName";
final String MSK_POSTED_USER = "postedUser";
final String MSK_PROFILE = "profile";
int totalResults = 25;
String resultStrs[] = new String[totalResults];
try
{
JSONArray serviceArray = new JSONArray(serviceJsonStr);
Vector<ContentValues> cVVector = new Vector<ContentValues>(serviceArray.length());
for(int i=0;i<serviceArray.length();i++)
{
String name, organizationName;
int price;
JSONObject serviceObject = serviceArray.getJSONObject(i);
name = serviceObject.getString(MSK_NAME);
price = serviceObject.getInt(MSK_PRICE);
JSONObject postedUserObject = serviceObject.getJSONObject(MSK_POSTED_USER);
JSONObject profileObject = postedUserObject.getJSONObject(MSK_PROFILE);
organizationName = profileObject.getString(MSK_ORG_NAME);
ContentValues serviceValues = new ContentValues();
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_NAME, name);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_ORGANIZATION_NAME, organizationName);
serviceValues.put(ServiceContract.ServiceEntry.COLUMN_PRICE, price);
cVVector.add(serviceValues);
}
int inserted = 0;
if(cVVector.size()>0)
{
ContentValues[] cvArray = new ContentValues[cVVector.size()];
cVVector.toArray(cvArray);
inserted = mContext.getContentResolver().bulkInsert(ServiceContract.ServiceEntry.CONTENT_URI, cvArray);
}
Log.d(LOG_TAG, "FetchServicesTask Complete. " + inserted + " Inserted");
}
catch(JSONException e)
{
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
/////////////////////////////// NETWORKING BOILER PLATE ///////////////////////////
#Override
protected Void doInBackground(String... params)
{
if (params.length == 0)
{
return null;
}
HttpURLConnection urlConnection = null; //Streaming data using HTTP
String serviceJsonStr = null; //raw JSON response
BufferedReader reader = null; //read text from character i/p stream
int pageNo = 1;
int numResults = 5;
try
{
//-------------------------CONNECTION--------------------//
final String SERVICE_BASE_URL = "http://myservicekart.com/public/";
final String SEARCH_BASE_URL = "http://myservicekart.com/public/search?";
final String SEARCH_PARAM = "search";
final String PAGE_PARAM = "pageno";
/*Using a helper class UriBuilder for building and manipulating URI references*/
Uri builtServiceUri = Uri.parse(SERVICE_BASE_URL);
Uri builtSearchUri = Uri.parse(SEARCH_BASE_URL).buildUpon().
appendQueryParameter(SEARCH_PARAM, "").
appendQueryParameter(PAGE_PARAM, Integer.toString(pageNo)).
build();
URL searchUrl = new URL(builtSearchUri.toString());
Log.v(LOG_TAG, "Built SearchUri" +builtSearchUri.toString());
urlConnection = (HttpURLConnection) searchUrl.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
//------------------------BUFFERING---------------------//
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if(inputStream==null)
{
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while((line = reader.readLine()) != null)
{
buffer.append(line + "\n");
}
if(buffer.length()==0)
{
return null;
}
serviceJsonStr = buffer.toString();
getServicesDatafromJson(serviceJsonStr);
Log.v(LOG_TAG, "Services JSON String: " +serviceJsonStr);
}
catch(IOException e)
{
Log.e(LOG_TAG, "Error cannot connect to URL", e);
return null;
}
catch (JSONException e)
{
e.printStackTrace();
}
finally
{
if(urlConnection!=null)
{
urlConnection.disconnect();
}
if(reader!=null)
{
try
{
reader.close();
}
catch (final IOException e)
{
Log.e(LOG_TAG,"Error closing stream",e);
}
}
}
return null;
}
}
ServiceAdapter.java
public class ServiceAdapter extends CursorAdapter
{
public ServiceAdapter(Context context, Cursor c, int flags)
{
super(context, c, flags);
}
private String convertCursorRowToUXFormat(Cursor cursor)
{
return cursor.getString(MSKFragment.COL_NAME) + "-" + cursor.getString(MSKFragment.COL_ORG_NAME) +
" - " + cursor.getInt(MSKFragment.COL_PRICE);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent)
{
View view = LayoutInflater.from(context).inflate(R.layout.list_item_main, parent, false);
return view;
}
#Override
public void bindView(View view, Context context, Cursor cursor)
{
TextView tv = (TextView)view;
tv.setText(convertCursorRowToUXFormat(cursor));
}
}
change the method newView() in ServiceAdapter.java to :
public View newView(Context context, Cursor cursor, ViewGroup parent){
View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
return view;}
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 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);
}
});
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;
}
.....
}
}