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.
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 am getting friends names,birthdays and profile pictures from Facebook.and I am displaying in listview but profile pictures is not matching with there names.
I tried below code:
public void onComplete(String response, Object state) {
Log.v("", "FriendListRequestONComplete");
friendData = response;
Log.v("friendData--", ""+friendData);
//Create method to run on UI thread
MainActivity.this.runOnUiThread(new Runnable() {
#SuppressLint("NewApi")
public void run() {
try {
//Parse JSON Data
// pick(userID);
JSONObject json;
//json = Util.parseJson(friendData);
json = new JSONObject(friendData);
//Get the JSONArry from our response JSONObject
friendArray = json.getJSONArray("data");
Log.v("friendArray--", ""+friendArray);
for(i = 0; i< friendArray.length(); i++)
{
frnd_obj = friendArray.getJSONObject(i);
try{
friends.add("Name:"+frnd_obj.getString("name")+"\n"+"DOB:"+frnd_obj.getString("birthday"));
String userProfileID=frnd_obj.getString("id");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
new DownloadImageTask(img).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, "https://graph.facebook.com/"+userProfileID+"/picture?type=small");
} else{
new DownloadImageTask(img).execute("https://graph.facebook.com/"+userProfileID+"/picture?type=small");
}
}
catch(Exception e){
//friends.add("Name:"+frnd_obj.getString("name"));
}
}list1.setAdapter(new lsAdapter(MainActivity.this));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
For load profile Pictures Asyntask:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
private ProgressDialog mDialog;
private ImageView bmImage;
// Bitmap mIcon11 = null;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected void onPreExecute() {
mDialog = ProgressDialog.show(MainActivity.this,"Please wait...", "Retrieving data ...", true);
mDialog.show();
}
protected Bitmap doInBackground(String... urls) {
Log.d("image", "do in");
String urldisplay = urls[0];
try {
Log.d("image", "do 1");
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
Log.d("image", "do 2");
} catch (Exception e) {
Log.e("Error", "image download error");
Log.e("Error", e.getMessage());
// mIcon11=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
e.printStackTrace();
Log.d("image", "do catch");
}
Log.d("image", "do out");
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
//set image of your imageview
Log.d("image", "post");
// bmImage.setImageResource(R.drawable.ic_launcher);
bmImage.setImageBitmap(null);
bmImage.setVisibility(View.INVISIBLE);
bmImage.setImageBitmap(result);
if(result!=null){
//Toast.makeText(getApplicationContext(), "success", 5000).show();
mIcon11=result;
}else {
//Toast.makeText(getApplicationContext(), "Not success", 5000).show();
mIcon11=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
// bmImage.setImageBitmap(mIcon11);
bitmapArray.add(mIcon11);
mDialog.dismiss();
//close
//mDialog.dismiss();
}
}
This is BaseAdapter class:
class lsAdapter extends BaseAdapter{
Context context;
public lsAdapter(Context c){
context=c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return friends.size();
return bitmapArray.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View v, ViewGroup group) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
View vi=inflater.inflate(R.layout.customlist, null);
ImageView iv=(ImageView)vi.findViewById(R.id.iv);
ImageView next=(ImageView)vi.findViewById(R.id.nextimg);
TextView tv=(TextView)vi.findViewById(R.id.tv);
//iv.setImageURI(friendArray.getJSONObject(i).getString("id"));
tv.setText(friends.get(position));
iv.setImageBitmap(bitmapArray.get(position));
return vi;
}
}
Please help me.to get friends profile picture with there correct names.
It seems that you're just adding to the bitmapArray in onPostExecute. But since the ImageDownloadTasks are executed asynchronously, there's no guaranteed order to when onPostExecute will run (an image added later could finish loading earlier). This is probably why you're seeing the random ordering.
Instead of just a bitmapArray, try using a HashMap, with the key being the "id", and the value being the bitmap. Then you can do a lookup in your adapter based on the user id. Alternatively, when you create the ImageDownloadTask, assign it a position, and set the bitmap in the correct position in the array.
i want to display images from mysql server(testing in localhost) using imageurl,i have images in a filder on my server,in an android client app as gridview along with text.how do i use imageurl in my code?
mymainmenu.java
public class MainMenu extends Activity {
GridView gridView;
static final String[] MOBILE_OS = new String[] {
"Android", "iOS","Windows", "Blackberry" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu_list);
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(new ImageAdapter(this, MOBILE_OS));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.grid_item_label))
.getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
my imageadapter.java:
public class ImageAdapter extends BaseAdapter {
private Context context;
private final String[] mobileValues;
public ImageAdapter(Context context, String[] mobileValues) {
this.context = context;
this.mobileValues = mobileValues;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = new View(context);
// get layout from list.xml
gridView = inflater.inflate(R.layout.list, null);
// set value into textview
TextView textView = (TextView) gridView
.findViewById(R.id.grid_item_label);
textView.setText(mobileValues[position]);
// set image based on selected text
ImageView imageView = (ImageView) gridView
.findViewById(R.id.grid_item_image);
String mobile = mobileValues[position];
if (mobile.equals("Windows")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("iOS")) {
imageView.setImageResource(R.drawable.imggrid);
} else if (mobile.equals("Blackberry")) {
imageView.setImageResource(R.drawable.imggrid);
} else {
imageView.setImageResource(R.drawable.imggrid);
}
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return mobileValues.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
I dnt know how to use the following in my code:
try {
URL url = new URL(imageFileURL);
URLConnection conn = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection)conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream inputStream = httpConn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
img.setImageBitmap(bitmap);
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Put the image downloading code in a AsyncTask. Here is the explanation.
Execute one instance of asynctask in your getView method, i.e to fetch one image everytime.
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView mImageView;
public void setImageView(ImageView img) {
mImageView = img;
}
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
Call task.setImageView(yourImageViewinGrid) before executing your AsyncTask to let it know where to set the image after downloading.
To get the image, you have to do something like :
URL new_url = new URL("your url");
Bitmap image_bitmap = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream()); ImageView image_view = new ImageView(this);
image_view.setImageBitmap(image_bitmap);
Anyway, it's better to download the image as background task. What I actually do is to create a custom view with one private inner class that extend AsyncTask to download the image for you.
I dnt know how to use the following in my code:
that code will download the image for you, you can place in separate thread either AsyncTask or Thread and set the downloaded image in the imageview... simple as that. There are so many example on the web you can google it out
EIDTED
code to download the image
public class AsyncFetchImage extends AsyncTask<String, Void, Bitmap>{
private WeakReference<ImageView> imageReference;
// private WeakReference<Dialog> dialogReferance;
public AsyncFetchImage(ImageView imageview) {
imageReference = new WeakReference<ImageView>(imageview);
// dialogReferance = new WeakReference<Dialog>(dialog);
}
#Override
protected Bitmap doInBackground(String... s) {
return downloadImage(s[0]);
}
private Bitmap downloadImage(String url) {
final AndroidHttpClient client = AndroidHttpClient.newInstance("Nixit");
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
Log.w("ImageDownloader", "Error " + statusCode + " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if(entity != null){
InputStream is = null;
try{
is = entity.getContent();
final Bitmap bit = BitmapFactory.decodeStream(is);
return bit;
}finally{
if(is != null)
is.close();
entity.consumeContent();
}
}
} catch (IOException e) {
e.printStackTrace();
return null;
} finally{
if(client != null){
client.close();
}
}
Log.i("Image Fetch","Image Fetch Complete");
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
if(isCancelled()){
result = null;
}
if(imageReference != null){
ImageView imageView = imageReference.get();
// Dialog di = dialogReferance.get();
if (imageView != null) {
imageView.setImageBitmap(result);
// di.show();
}
}
}
}
How to use:-
imageView = (ImageView)dialog.findViewById(R.id.imageView1);
AsyncFetchImage fetchImage = new AsyncFetchImage(imageView);
fetchImage.execute(url);
You can use this in getview method of adapter
Hope that help
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 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.