I need to implement progress bar in an android project when an intent is passed through one activity another, and some a fair bit of data from the internet is being downloaded in second activity and as such there is a noticeable delay between when the user clicks on an item and when the Activity displays.
I've tried a few different approaches for this but nothing seems to work as desired. I am using the following code for it. And the progress dialog is going inside infinite loop.
public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> {
int myProgress;
#Override
protected void onPostExecute(Bitmap result) {
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(result);
dialog.cancel();
dialog.dismiss();
}
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
}
#Override
protected Bitmap doInBackground(String...paths) {
return DownloadFile(imageUrl);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
public Bitmap DownloadFile(String url){
URL myFileUrl;
Bitmap bitmap=null;
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap,70 , 70, true);
System.out.println("name of bitmap"+bitmap.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(e);
}
return bitmap;
}
And following is my adapter class
public class ImageAdapter extends BaseAdapter {
Context mContext;
private String[] stringOnTextView;
public ImageAdapter(Context c) {
mContext = c;
}
// BitmapManager.INSTANCE. setPlaceholder(BitmapFactory.decodeResource(
// context.getResources(), R.drawable.icon));
public ImageAdapter(Context Context,
String[] stringOnTextView) {
this.mContext=Context;
this.stringOnTextView=stringOnTextView;
}
public int getCount() {
return stringOnTextView.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("**************"+position);
View v = null;
if(convertView==null){
try{
{
System.gc();
// dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl=imageUrl+stringOnTextView[position];
System.out.println(imageUrl);
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText("Profile Image "+(position+1));
/* URL myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, 80, 80, true);*/
// new ImageView(mContext);
iv= (ImageView)v.findViewById(R.id.image);
new BackgroundAsyncTask().execute(imageUrl);
//iv.setImageBitmap(bitmap);
//dialog.cancel();
// System.out.println(bitmap.getHeight());
System.out.println("++++++++"+R.id.image);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
else
{
try{
v = convertView;}
catch(Exception e){
System.out.println(e);
}
}
return v;
}
}
Can anyone help me over this?
Try AsyncTask,
private class myAsyncTask extends AsyncTask<String, Void, Void>
{
ProgressDialog mProgressDialog;
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(Activity_name.this, "Loading...", "Please wait...");
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// you can do download from internet here
return null;
}
#Override
protected void onPostExecute(Void result) {
mProgressDialog.dismiss();
}
}
Android AsyncTask its answer for what you needed. Look here Android - AsyncTask
The trick is to
setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
for your progressDialog.
Related
I have a Baseadapter for a listview, when 1 of the elements inside gets clicked it is supposed to execute an AsyncTask. The onClick is inside Baseadapter and that works however the async execute is not working here is my baseAdapter
public class LocalFeed_CustomView extends BaseAdapter {
JSONObject names;
Context ctx;
LayoutInflater myiflater;
public LocalFeed_CustomView(){}
public LocalFeed_CustomView(JSONObject arr,Context c) {
ctx = c;
names = arr;
// myiflater = (LayoutInflater)c.getSystemService(c.LAYOUT_INFLATER_SERVICE);
// System.err.println("vv:" + arr);
}
#Override
public int getCount() {
try {
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
return jaLocalstreams.length();
} catch (Exception e) {
Toast.makeText(ctx,"Error: Please try again",Toast.LENGTH_LONG).show();
return names.length();
}
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position,View convertView, ViewGroup parent) {
try {
if(convertView==null) {
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = li.inflate(R.layout.customadapter, null);
}
TextView votes= (TextView)convertView.findViewById(R.id.votes);
JSONArray jaLocalstreams = names.getJSONArray("localstreams");
final JSONObject jsonObject = jaLocalstreams.getJSONObject(position);
jsonObject.getInt("id");
// the click works because the toast message fires
votes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
int Stream_ID= jsonObject.getInt("id");
SharedPreferences myaccount = ctx.getSharedPreferences("userInfo", ctx.MODE_PRIVATE);
int Profile_id=myaccount.getInt("id", 0);
Toast.makeText(ctx, "click worked", Toast.LENGTH_SHORT).show();
// the execute below is not firing off
new Add_Votes(Stream_ID,Profile_id).execute();
}
catch (Exception e)
{
e.getCause();
}
}
});
return convertView;
} catch (Exception e) {
e.printStackTrace();
}
return convertView;
}
}
As you can see the execute is not working and both of the int values have numbers in them. This is my AsyncTask
public class Add_Votes extends AsyncTask<String,String,String> {
HttpURLConnection conn;
URL url;
String result="";
DataOutputStream wr;
String Stream_URL;
Activity m;
int stream_id,profile_id;
public Add_Votes(int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Stream_URL= m.getResources().getString(R.string.PathUrl)+"/api/addvote";
//this Toast never fires off
Toast.makeText(m.getApplicationContext(),"clicked",Toast.LENGTH_SHORT);
}
#Override
protected String doInBackground(String... params) {
BufferedReader reader=null;
try{
url = new URL(Stream_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.connect();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
String cert="id="+profile_id+"&stream_id="+stream_id;
wr = new DataOutputStream(conn.getOutputStream());
wr.writeBytes(cert);
wr.flush();
wr.close();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sBuilder = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
sBuilder.append(line + "\n");
}
result = sBuilder.toString();
reader.close();
conn.disconnect();
return result;
}
catch (Exception e)
{
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
Toast.makeText(m.getApplicationContext(),"Voted",Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(m.getApplicationContext(),"Inconclusive",Toast.LENGTH_SHORT).show();
}
}
}
Add_Votes is only an AsyncTask there is no activity associated with it. Any suggestions on how I can call an AsyncTask from a baseadapter would be great. It needs to be from a baseadapter because each row has different values depending on the item clicked which then I pass on to the Async Task.
One thing I notice is you are using a variable Activity m and you have not initialised it in your AsyncTask. try passing a context from your BaseAdapter to AsyncTask.
In Add_Votes :
private Context context;
public Add_Votes(Context context ,int stream_id,int profile_id)
{
this.stream_id=stream_id;
this.profile_id=profile_id;
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Toast.makeText(context,"clicked",Toast.LENGTH_SHORT).show();
}
In your BaseAdapter:
Add_Votes add_Votes = new Add_Votes(ctx,Stream_ID,Profile_id);
add_Votes.execute();
I have an Async running to get data from a page I've created. It get's the text just fine, but when I try and get the image from the image src via another class the app force closes. Here is the code that it force closes on:
public class FullReportActivity extends NavigationActivity {
private TextView textView;
private String url = "http://www.backcountryskiers.com/sac/sac-full.html";
private ImageView ivDangerRose;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// tell which region this covers
getSupportActionBar().setSubtitle("...from Sierra Avalanche Center");
setContentView(R.layout.activity_fullreport);
textView = (TextView) findViewById(R.id.todaysReport);
ivDangerRose = (ImageView) findViewById(R.id.dangerRose);
fetcher task = new fetcher();
task.execute();
}
// GET THE IMAGE and RETURN IT
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);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
class fetcher extends AsyncTask<String, Void, String> {
private ProgressDialog dialog = new ProgressDialog(
FullReportActivity.this);
private Document doc = null;
private Document parse = null;
private String results = null;
private String reportDate = null;
private Bitmap bimage = null;
#Override
protected String doInBackground(String... params) {
try {
doc = Jsoup.connect(url).get();
Log.e("Jsoup", "...is working...");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.e("Exception", e.getMessage());
}
parse = Jsoup.parse(doc.html());
results = doc.select("#fullReport").outerHtml();
Element dangerRoseImg = doc.getElementById("reportRose")
.select("img").first();
String dangerRoseSrc = dangerRoseImg.absUrl("src");
Log.i("Report Rose IMG", dangerRoseSrc);
bimage = getBitmapFromURL(dangerRoseSrc);
ivDangerRose.setImageBitmap(bimage);
return results;
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
// smooth out the long scrolling...
textView.setMovementMethod(ScrollingMovementMethod.getInstance());
reportDate = parse.select("#reportDate").outerHtml();
textView.setText(Html.fromHtml(reportDate + results));
textView.setPadding(30, 20, 20, 10);
}
#Override
protected void onPreExecute() {
dialog.setMessage("Loading Full Report from the Sierra Avalanche Center...");
dialog.show();
}
}
}
I have run this Async alone to get the image like so without a force close and I don't understand what i am doing different besides calling the method:
public class MainActivity extends Activity {
public String durl = "http://www.sierraavalanchecenter.org/dangerrose.png?a=2955";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new DownloadImageTask((ImageView) findViewById(R.id.dangerrose))
.execute(durl);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap drose = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
drose = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return drose;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
This class gets the image src and creates a bitmap and puts it into an ImageView, what is different here than on my first class???
Frustrated.
You can not modify UI from background thread.
move ivDangerRose.setImageBitmap(bimage); in onPostExecute
In the method doInBackground
remove --> ivDangerRose.setImageBitmap(bimage);
as you can't modify UI in background process.
If you still want you can try runOnUiThread Method
In doInBackground() we should not access the content of activity.
im fetching an image from internet using the below code using an Async task,But the bitmp returns from the function is always null.
private Bitmap asyncTaskFetchImage(final String imgeurl) {
// TODO Auto-generated method stub
new AsyncTask<Object, Object, Object>() {
#Override
protected void onPreExecute() {
progress_Dialog = ProgressDialog.show(this, "", "Loading");
}
#Override
protected Object doInBackground(Object... params) {
// TODO Auto-generated method stub
try
{
toSendBg=LoadImageFromURL(imgeurl);
System.gc();
return 0;
}
catch (Exception e) {
e.printStackTrace();
}
return 0;
}
#Override
protected void onPostExecute(Object result) {
if (progress_Dialog != null) {
progress_Dialog.dismiss();
}
}
}.execute();
return toSendBg;
}
Is this the exact way to return value from an Asyntask?
Try below code to download image from web using AsyncTask and display in imageview.
public class MainActivity extends Activity {
ImageView mImgView1;
static Bitmap bm;
ProgressDialog pd;
String imageUrl = "https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg";
BitmapFactory.Options bmOptions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mImgView1 = (ImageView) findViewById(R.id.mImgView1);
pd = ProgressDialog.show(MainActivity.this, "Aguarde...",
"Carregando...");
new ImageDownload().execute("");
}
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(imageUrl, bmOptions);
return imageUrl;
}
protected void onPostExecute(String imageUrl) {
pd.dismiss();
if (!imageUrl.equals("")) {
mImgView1.setImageBitmap(bm);
} else {
Toast.makeText(MainActivity.this,
"Não foi possível obter resultados", Toast.LENGTH_LONG)
.show();
}
}
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
}
private Bitmap asyncTaskFetchImage(final String imgeurl) {
Bitmap bmp=null;
new AsyncTask<Object, Object, Object>() {
...
and in your doInBackground method change return to
return toSendBg;
and
#Override
protected void onPostExecute(Object result) {
if (progress_Dialog != null) {
progress_Dialog.dismiss();
bmp=(Bitmap)result;
}
}
}.execute();
return bmp;
Try this..,.
i am making an app in which i have to get response from xml and i get image urls .Now i want to put images from urls into gridview but i dnt know how to extract images from urls and put in gridview.Any help will be appreciated.My code is as follows:
public class GalleryNewActivity extends Activity {
private ProgressDialog dialog;
GridView ga;
Element e;
Node elem;
public List<Drawable> pictures;
ImageView imageView;
static final String PREFS_NAME = "MyPrefs";
static final String USER_KEY = "user";
static final String Name = "name";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if(isNetworkconn()){
new GetSPCAsyncTask().execute("");
}else{
showDialogOnNoInternet();
}
ga = (GridView)findViewById(R.id.Gallery01);
ga.setAdapter(new ImageAdapter(this));
imageView = (ImageView)findViewById(R.id.ImageView01);
}
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return pictures.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.galleryitem, null);
imageView = (ImageView)v.findViewById(R.id.thumbImage);
imageView.setLayoutParams(new GridView.LayoutParams(200, 250));
// imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(2, 5, 2, 5);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageDrawable(pictures.get(position));
imageView.setTag(pics[position]);
return imageView;
}
private class GetPicsToNextPage extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
String str = null;
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
Intent intent = new Intent(getApplicationContext(), Flip3d.class);
startActivity(intent);
}
}
private boolean isNetworkconn(){
ConnectivityManager conMgr = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null && conMgr.getActiveNetworkInfo().isAvailable() && conMgr.getActiveNetworkInfo().isConnected()) {
return true;
}else{
return false;
}
}
private void showDialogOnNoInternet(){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(GalleryNewActivity.this);
alt_bld.setTitle("Error.");
alt_bld.setMessage("Your phone is not connected to internet.");
alt_bld.setCancelable(false);
alt_bld.setNeutralButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
alt_bld.show();
}
//loader for dynamic starts
private class GetSPCAsyncTask extends AsyncTask<String, String, String>{
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
dialog = ProgressDialog.show(GalleryNewActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
NodeList nodes = doc.getElementsByTagName("Image");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
e = (Element)nodes.item(i);
//map.put("Image", XMLfunctions.getValue(e, "Image"));
map.put("ImagePath", "Naam:" + XMLfunctions.getValue(e, "ImagePath"));
map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline"));
System.out.println(map.put("ImageHeadline", "Headline: " + XMLfunctions.getValue(e, "ImageHeadline")));
map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc"));
System.out.println(map.put("ImageDesc", "Desc: " + XMLfunctions.getValue(e, "ImageDesc")));
mylist.add(map);
Drawable d=LoadImageFromWebOperations();
pictures.add(d);
}
return xml;}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
}
private Drawable LoadImageFromWebOperations()
{
String path=XMLfunctions.getValue(e, "ImagePath");
try{
InputStream is = (InputStream) new URL(path).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
Log.w("CREADO","CREADO");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
}
}
I would suggest you to check below solutions for loading images from URL:
Android - Universal Image loader by Nostra
Lazy load of images in ListView
Result you can get if you use Universal image loader:
call this function with url you will get Drawable , and then store this drawables into custom class and then place in grid view.
call function like this
ImageOperations(this, imageurl)
public Object fetch(String address) throws MalformedURLException, IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
private Drawable ImageOperations(Context ctx, String url) {
try {
InputStream is = (InputStream) this.fetch(url);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
https://github.com/koush/UrlImageViewHelper
UrlImageViewHelper will fill an ImageView with an image that is found at a URL.
The sample will do a Google Image Search and load/show the results asynchronously.
UrlImageViewHelper will automatically download, save, and cache all the image urls the BitmapDrawables. Duplicate urls will not be loaded into memory twice. Bitmap memory is managed by using a weak reference hash table, so as soon as the image is no longer used by you, it will be garbage collected automatically.
else use this,
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I am making an android application that gets updated. For this I need a simple function that can download a file and show the current progress in a ProgressDialog. I know how to do the download the file, but I'm not sure how to display the current progress.I am using the following method for downloading images.
public Bitmap DownloadFile(String url){
URL myFileUrl;
Bitmap bitmap=null;
try {
myFileUrl = new URL(imageUrl);
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bitmap = BitmapFactory.decodeStream((InputStream) new URL(
imageUrl).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap,80 , 80, true);
System.out.println("name of butmap"+bitmap.toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bitmap;
}
And following is my async task class :
public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> {
int myProgress;
#Override
protected void onPostExecute(Bitmap result) {
dialog.dismiss();
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(result);
System.out.println("bbbbbbbbb");
System.out.println("post execute");
}
#Override
protected void onPreExecute() {
System.out.println("pre execute");
dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
}
#Override
protected Bitmap doInBackground(String...paths) {
System.out.println(imageUrl+" imageurl");
return DownloadFile(imageUrl);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
and i am calling the method in the following adapter class :
public class ImageAdapter extends BaseAdapter {
Context mContext;
public String[] stringOnTextView;
public ImageAdapter(Context c) {
mContext = c;
}
public ImageAdapter(Context Context,
String[] stringOnTextView) {
this.mContext=Context;
this.stringOnTextView=stringOnTextView;
}
public int getCount() {
return stringOnTextView.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = null;
if(convertView==null){
try{
{
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
TextView tv = (TextView)v.findViewById(R.id.text);
tv.setText("Profile Image "+(position+1));
iv= (ImageView)v.findViewById(R.id.image);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl=imageUrl+stringOnTextView[position];
new BackgroundAsyncTask().execute(imageUrl);
}
}catch (Exception e) {
e.printStackTrace();
System.out.println(e);
}
}
else
{
try{
v = convertView;}
catch(Exception e){
System.out.println(e);
}
}
return v;
}
}
I need to download 9 images but the problem i am facing is that it only shows the last image and progress dialog goes into infinite loop.
Can anyone tell me over how to resolve thios issue.
Thanks
I have already suggested you to use AsyncTask previously for your problems if you remember.
onPreExecute() - show proress dialog
doInBackground() - call your DownloadFile() method inside the doInBackground()
dismiss the progress dialog.
Go through this example and understand it and implement it in your way: AsyncTask with Progress Dialog
I got the solution by working on it and the following should be the solution for this:
class DownloadFileAsync extends AsyncTask<String, String, String>
{
int count;
URL myFileUrl;
ImageView imageview;
Bitmap bp;
public DownloadFileAsync(ImageView iv, URL uu)
{
this.imageview = iv;
this.myFileUrl = uu;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
showDialog(DIALOG_DOWNLOAD_PROGRESS);
}
#Override
protected String doInBackground(String... aurl)
{
for (int i = 0; i < aurl.length; i++)
System.out.println("----------" + i + "------" + aurl[i]);
try
{
HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
bp = BitmapFactory.decodeStream((InputStream) (myFileUrl).getContent());
bp = Bitmap.createScaledBitmap(bp, 70, 70, true);
}
catch (Exception e)
{
System.out.println(e);
e.printstacktrace();
}
return null;
}
protected void onProgressUpdate(String... progress)
{
dialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String unused)
{
try
{
imageview.setImageBitmap(bp);
System.out.println("this is" + this);
// dialog.dismiss();
dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
}
catch (Exception e)
{
System.out.println(e);
}
}
}
You have to use an AssyncTask to be able to easily communicate progress to the UI thread.
For the dialog, use ProgressDialog:
private void downloadFile(URL fileUrl) {
if (myProgressDialog == null) {
new DownloadFilesTask().execute(fileUrl);
myProgressDialog = ProgressDialog.show(this, "Downloading file " + fileUrl.toString(), "Wait patiently, your download is in progress.", true /*You wont have a time estimate*/, false /*Download cannot be canceled*/);
} else {
Log.e(LOG_TAG, "A download is already in progress");
}
}
private void hideDialog() {
if (myProgressDialog != null) {
myProgressDialog.cancel();
}
}
And for the AssycTask, use an inner class in your Activity:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Boolean> {
protected Long doInBackground(URL... urls) {
// TODO Download file here
return true;
}
protected void onProgressUpdate(Integer... progress) {
// TODO nothing to do here, you don't have download details
}
protected void onPostExecute(Boolean result) {
MyActivity.this.hideProgressDialog();
}
}
ok, i see 2 potential problems here ..
you have to use holder kind of structure for your adapter.
in asyncTask, the imageView, should be different for each item in the listView. basically, you have to pass imageView as an argument to asyncTask.
I changed your adapter, have a look at it.
static class ViewHolder {
TextView tv;
ImageView iv;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
View v = null;
if(convertView==null){
vh = new ViewHolder();
LayoutInflater li = getLayoutInflater();
v = li.inflate(R.layout.icon, null);
vh.tv = (TextView)v.findViewById(R.id.text);
vh.iv= (ImageView)v.findViewById(R.id.image);
v.setTag(vh);
}
else
{
vh = (ViewHolder) convertView.getTag();
v = convertView;
}
vh.tv.setText("Profile Image "+(position+1));
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl=imageUrl+stringOnTextView[position];
new BackgroundAsyncTask(vh.iv).execute(imageUrl);
return v;
}
And also the asyncTask here. I made a constructor and passed imageView as argument.
public class BackgroundAsyncTask extends AsyncTask<String, Integer, Bitmap> {
int myProgress;
ImageView iv;
public BackgroundAsyncTask (ImageView imageView) {
iv = imageView;
}
#Override
protected void onPostExecute(Bitmap result) {
dialog.dismiss();
iv.setVisibility(View.VISIBLE);
iv.setImageBitmap(result);
System.out.println("bbbbbbbbb");
System.out.println("post execute");
}
#Override
protected void onPreExecute() {
System.out.println("pre execute");
dialog = ProgressDialog.show(ProfileNormalUserPhotos.this, "Loading...", "Please wait...");
}
#Override
protected Bitmap doInBackground(String...paths) {
System.out.println(imageUrl+" imageurl");
return DownloadFile(imageUrl);
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
progressBar.setProgress(values[0]);
}
}
but i still can't guarantee the solution to infinite loop, but it is always good to fix some other problems :)
HTH.