How to set image from Url using AsyncTask? - android

I'm a newbie programmer an I'm making an android program that displays an image on ImageView from a given url. My problem is how do you use this on the AsyncTask?
These codes work on min SDK 2.2 but I switched to min SDK 3.0 so it needs to run on the AsyncTask. Thank you for your help! :)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
satellite(); //satellite's image from main menu
}
//******satellite url
private void satellite() {
// TODO Auto-generated method stub
ImageView imgView =(ImageView)findViewById(R.id.satellite);
Drawable drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
imgView.setImageDrawable(drawable);
}
private Drawable LoadImageFromWeb(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
return d;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}

well, I dont know why android SDK does not provide support for it (yet) I extended the ImageView class by UrlImageView class with asynchronous loading and caching support. I put the code of my class below, which is plug and play. The class body is at the end of my post, now I write two lines how to use it the convenient way.
Two more methods now are supported:
setImageUrl(URL url) // sets the bitmap by its URL
cancelLoading(); // tell this view to cancel pending load
How to use your java-code:
// [somewhere in your activity]
UrlImageView urlImg = new UrlImageView(this).setImageUrl("http://abc.png");
...
urlImg.setImageUrl("http://abc2.png"); // works like expected
How to bind in your layouts:
<!-- thumbnail -->
<com.gplushub.android.view.UrlImageView
android:id="#+id/thumbnail"
android:layout_width="64dp"
android:layout_height="64dp"
android:layout_gravity="center_vertical"
android:layout_marginRight="2dp"
android:scaleType="fitXY" />
..and again in your activity java code:
((UrlImageView)findViewById(R.id.thumbnail)).setImageUrl("http://foo.bar.png");
I use it in lists with more than 100 entries - flinging very well. Here the class body, you can use it, modify it, extend it, whatever you like:
package com.gplushub.android.view;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.ImageView;
/**
* an {#link ImageView} supporting asynchronous loading from URL. Additional
* APIs: {#link #setImageURL(URL)}, {#link #cancelLoading()}.
*
* #author ep#gplushub.com / Eugen Plischke
*
*/
public class UrlImageView extends ImageView {
private static class UrlLoadingTask extends AsyncTask<URL, Void, Bitmap> {
private final ImageView updateView;
private boolean isCancelled = false;
private InputStream urlInputStream;
private UrlLoadingTask(ImageView updateView) {
this.updateView = updateView;
}
#Override
protected Bitmap doInBackground(URL... params) {
try {
URLConnection con = params[0].openConnection();
// can use some more params, i.e. caching directory etc
con.setUseCaches(true);
this.urlInputStream = con.getInputStream();
return BitmapFactory.decodeStream(urlInputStream);
} catch (IOException e) {
Log.w(UrlImageView.class.getName(), "failed to load image from " + params[0], e);
return null;
} finally {
if (this.urlInputStream != null) {
try {
this.urlInputStream.close();
} catch (IOException e) {
; // swallow
} finally {
this.urlInputStream = null;
}
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (!this.isCancelled) {
// hope that call is thread-safe
this.updateView.setImageBitmap(result);
}
}
/*
* just remember that we were cancelled, no synchronization necessary
*/
#Override
protected void onCancelled() {
this.isCancelled = true;
try {
if (this.urlInputStream != null) {
try {
this.urlInputStream.close();
} catch (IOException e) {
;// swallow
} finally {
this.urlInputStream = null;
}
}
} finally {
super.onCancelled();
}
}
}
/*
* track loading task to cancel it
*/
private AsyncTask<URL, Void, Bitmap> currentLoadingTask;
/*
* just for sync
*/
private Object loadingMonitor = new Object();
public UrlImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public UrlImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public UrlImageView(Context context) {
super(context);
}
#Override
public void setImageBitmap(Bitmap bm) {
cancelLoading();
super.setImageBitmap(bm);
}
#Override
public void setImageDrawable(Drawable drawable) {
cancelLoading();
super.setImageDrawable(drawable);
}
#Override
public void setImageResource(int resId) {
cancelLoading();
super.setImageResource(resId);
}
#Override
public void setImageURI(Uri uri) {
cancelLoading();
super.setImageURI(uri);
}
/**
* loads image from given url
*
* #param url
*/
public void setImageURL(URL url) {
synchronized (loadingMonitor) {
cancelLoading();
this.currentLoadingTask = new UrlLoadingTask(this).execute(url);
}
}
/**
* cancels pending image loading
*/
public void cancelLoading() {
synchronized (loadingMonitor) {
if (this.currentLoadingTask != null) {
this.currentLoadingTask.cancel(true);
this.currentLoadingTask = null;
}
}
}
}

If the image is not that big you can just use an anonymous class for the async task. This would like this:
ImageView mChart = (ImageView) findViewById(R.id.imageview);
String URL = "http://www...anything ...";
mChart.setTag(URL);
new DownloadImageTask.execute(mChart);
and the task class is
public class DownloadImagesTask extends AsyncTask<ImageView, Void, Bitmap> {
ImageView imageView = null;
#Override
protected Bitmap doInBackground(ImageView... imageViews) {
this.imageView = imageViews[0];
return download_Image((String)imageView.getTag());
}
#Override
protected void onPostExecute(Bitmap result) {
imageView.setImageBitmap(result);
}
private Bitmap download_Image(String url) {
...
}

Try this code, make your drawable variable global and change your satellite function like this:
private void satellite() {
// TODO Auto-generated method stub
ImageView imgView =(ImageView)findViewById(R.id.satellite);
new yourTask().execute();
}
then create asyncTask class like this:
private class yourTask extends AsyncTask<Integer, Void, Integer> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//show a progress bar
}
#Override
protected String doInBackground(Integer... params) {
drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
return 0;
}
#Override
protected void onPostExecute(Integer result) {
super.onPostExecute(result);
imgView.setImageDrawable(drawable);
}
}

Here is the code for the Aynctask implementation
Make your drawable object as global in Aynctask class.
Class MyDownloader extends AsyncTask<Void,Void,String>{
Drawable drawable;
#Override
public String doInBackground(Void... args){
drawable = LoadImageFromWeb("http://www.pagasa.dost.gov.ph/wb/sat_images/satellite.gif");
return null; // here you can pass any string on response as on error or on success
}
public void onPostExecute(String result){
if(drawable!=null){
imgView.setImageDrawable(drawable);
}
}
}
now create object of this class and execute it
private void satellite() {
// TODO Auto-generated method stub
ImageView imgView =(ImageView)findViewById(R.id.satellite);
new MyDownloader.execute();
}
Here is good example link for caching the image check out this link and example
https://github.com/novoda/ImageLoader

You are right when u do any network operation later Android 2.2(Froyo) Must use Asynctask
This is the best example to understand AsyncTask

based on the answer from comeGetSome i created my own implementation which works with normal ImageView class instead of creating a new class UrlImageView, also new options are provided like - what to do when the loading completes or cancels
Now load image as you want, like this from any of the three loadImage methods
UrlImageLoader urlImageLoader=new UrlImageLoader();
ImageView imageView=new ImageView(context);
//load and set the image to ImageView
urlImageLoader.loadImage(imageView, "http://www......com/.....jpg");
//for loading a image only - load image and do any thing with the bitmap
urlImageLoader.loadImage("http://www......com/.....jpg", new UrlImageLoader.OnLoadingCompleteListener() {
#Override
public void onComplete(ImageView imageView, Bitmap bmp) {
// do anything with the Bitmap
// here imageView will be null
}
#Override
public void onCancel(ImageView imageView) {
}
});
urlImageLoader.loadImage(imageView, "http://www......com/.....jpg", new UrlImageLoader.OnLoadingCompleteListener() {
#Override
public void onComplete(ImageView imageView, Bitmap bmp) {
// do anything with the Bitmap
// here imageView is not null
imageView.setImageBitmap(bmp);
}
#Override
public void onCancel(ImageView imageView) {
}
});
create this class for loading UrlImageLoader
/*special thanks to stackoverflow.com user comeGetSome for UrlImageLoadingTask code
* question - http://stackoverflow.com/questions/14332296/how-to-set-image-from-url-using-asynctask/15797963
* comeGetSome - http://stackoverflow.com/users/1005652/comegetsome
*/
package com.GameG.SealTheBox;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.ImageView;
public class UrlImageLoader {
public static interface OnLoadingCompleteListener {
public void onComplete(ImageView imageView, Bitmap bmp);
public void onCancel(ImageView imageView);
}
ArrayList<UrlImageLoadingTask> loadingList=new ArrayList<UrlImageLoadingTask>();
/**
* Loads a image from url and calls onComplete() when finished<br>
* #Note you should manually set the loaded image to ImageView in the onComplete()
* #param imageView
* #param url
* #param onComplete
*/
public void loadImage(ImageView imageView, String url, OnLoadingCompleteListener onComplete){
try {
URL url2=new URL(url);
if(imageView!=null){
for(int i=0;i<loadingList.size();i++){
UrlImageLoadingTask tmptask=loadingList.get(i);
if(tmptask.updateView!=null && tmptask.updateView.equals(imageView)){
tmptask.cancel(true);
break;
}
}
}
UrlImageLoadingTask loadtask=new UrlImageLoadingTask(imageView,onComplete,url);
loadtask.execute(url2);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
/**
* Loads a image from url and calls onComplete() when finished
* #param url
* #param onComplete
*/
public void loadImage(String url, OnLoadingCompleteListener onComplete){
loadImage(null,url,onComplete);
}
/**
* Loads a image from url and sets the loaded image to ImageView
* #param imageView
* #param url
*/
public void loadImage(ImageView imageView, String url){
loadImage(imageView,url,null);
}
/**
* Cancel loading of a ImageView
*/
public void cancel(ImageView imageView){
for(int i=0;i<loadingList.size();i++){
UrlImageLoadingTask tmptask=loadingList.get(i);
if(tmptask.updateView.equals(imageView)){
loadingList.remove(i);
tmptask.cancel(true);
break;
}
}
}
/**
* Cancel loading of a Url
*/
public void cancel(String url){
for(int i=0;i<loadingList.size();i++){
UrlImageLoadingTask tmptask=loadingList.get(i);
if(tmptask.url.equals(url)){
loadingList.remove(i);
tmptask.cancel(true);
break;
}
}
}
/**
* Cancel all loading tasks
*/
public void cancelAll(){
while(loadingList.size()>0){
UrlImageLoadingTask tmptask=loadingList.get(0);
loadingList.remove(tmptask);
tmptask.cancel(true);
}
}
private class UrlImageLoadingTask extends AsyncTask<URL, Void, Bitmap> {
public ImageView updateView=null;
public String url;
private boolean isCancelled = false;
private InputStream urlInputStream;
private OnLoadingCompleteListener onComplete=null;
private UrlImageLoadingTask(ImageView updateView, OnLoadingCompleteListener onComplete, String url) {
this.updateView=updateView;
this.onComplete=onComplete;
this.url=url;
}
#Override
protected Bitmap doInBackground(URL... params) {
try {
URLConnection con = params[0].openConnection();
// can use some more params, i.e. caching directory etc
con.setUseCaches(true);
this.urlInputStream = con.getInputStream();
return BitmapFactory.decodeStream(urlInputStream);
} catch (IOException e) {
Log.w(UrlImageView.class.getName(), "failed to load image from " + params[0], e);
return null;
} finally {
if (this.urlInputStream != null) {
try {
this.urlInputStream.close();
} catch (IOException e) {
; // swallow
} finally {
this.urlInputStream = null;
}
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (!this.isCancelled) {
// hope that call is thread-safe
if(onComplete==null){
if(updateView!=null)
this.updateView.setImageBitmap(result);
}else{
onComplete.onComplete(updateView, result);
}
}
loadingList.remove(this);
}
/*
* just remember that we were cancelled, no synchronization necessary
*/
#Override
protected void onCancelled() {
this.isCancelled = true;
try {
if (this.urlInputStream != null) {
try {
this.urlInputStream.close();
} catch (IOException e) {
;// swallow
} finally {
this.urlInputStream = null;
}
}
} finally {
super.onCancelled();
if(onComplete!=null)
onComplete.onCancel(updateView);
loadingList.remove(this);
}
}
}
}

Just create a new class "DownloadImageTask" like following one and put it at the same folder where you have your Activity.
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.os.AsyncTask;
import java.io.*;
public 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 myImage = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
myImage = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return myImage;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
After this add line to crate that class in your Activity.
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.util.Log;
import android.widget.ImageView;
public class HomeScreen extends ActionBarActivity {
private final String TAG = "test1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate");
setContentView(R.layout.activity_home_screen);
InitHomeScreen();
}
protected void InitHomeScreen()
{
String imageUrl = "http://s20.postimg.org/4t9w2pdct/logo_android_png.png";
Log.d(TAG, "Get an Image");
// Get an Image
try{
AsyncTask<String, Void, Bitmap> execute = new DownloadImageTask((ImageView) findViewById(R.id.imageView))
.execute(imageUrl);
// R.id.imageView -> Here imageView is id of your ImageView
}
catch(Exception ex)
{
}
}
// Other code...
Don't forget to allow access to INTERNET to your Android app.
Check your manifest file.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.dmitry.myapplication1" >
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".HomeScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Related

How to retrieve data from Azure Mobile Service and bind to Android ListView

I am currently trying to retrieve the data I have inserted into Azure Mobile Services into a ListView in my Android application. I tried to follow the tutorial Microsoft provided but my items are not showing up in the ListView. The example they provided had a checkbox in it, which I do not need. I just wanna display my Entry Name and the Date + Time I have inserted into the database table into the ListView. This is my list view layout:
entry_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<TextView
android:id="#+id/tvEntryName"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Entry name"/>
<TextView
android:id="#+id/tvEntryDateTime"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="date/time"/>
</LinearLayout>
and then this is my adapter
Entry Item Adapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import java.security.KeyStore;
public class EntryItemAdapter extends ArrayAdapter<EntryItem> {
Context mContext;
int mLayoutResourceId;
public EntryItemAdapter(Context context, int layoutResourceId) {
super(context, layoutResourceId);
mContext = context;
mLayoutResourceId = layoutResourceId;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
final EntryItem currentItem = getItem(position);
if (row == null) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
row = inflater.inflate(mLayoutResourceId, parent, false);
}
row.setTag(currentItem);
return row;
}
}
last but not least, the activity where I wanna display the ListView
AllEntriesActivity.java
import android.content.Intent;
import android.content.res.TypedArray;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.net.MalformedURLException;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.table.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.ColumnDataType;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.MobileServiceLocalStoreException;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.SQLiteLocalStore;
import com.microsoft.windowsazure.mobileservices.table.sync.synchandler.SimpleSyncHandler;
import static com.microsoft.windowsazure.mobileservices.table.query.QueryOperations.val;
import android.os.AsyncTask;
public class AllEntriesActivity extends BaseActivity {
private MobileServiceClient mClient;
private MobileServiceTable<EntryItem> mEntryTable;
private EntryItemAdapter mAdapter;
private String[] navMenuTitles;
private TypedArray navMenuIcons;
Button btnAddEntry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_entries);
try {
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(
"https://skerydiary.azure-mobile.net/",
"farvbebCTbuqVueYGNugUivXktrljJ72",
this);
mEntryTable = mClient.getTable(EntryItem.class);
//initLocalStore().get();
// Create an adapter to bind the items with the view
mAdapter = new EntryItemAdapter(this, R.layout.entry_listview);
ListView listViewEntryItems = (ListView) findViewById(R.id.listViewEntries);
listViewEntryItems.setAdapter(mAdapter);
// Load the items from the Mobile Service
refreshItemsFromTable();
} catch (MalformedURLException e) {
e.printStackTrace();
}
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items); // load
// titles
// from
// strings.xml
navMenuIcons = getResources()
.obtainTypedArray(R.array.nav_drawer_icons);// load icons from
// strings.xml
set(navMenuTitles, navMenuIcons);
btnAddEntry = (Button) findViewById(R.id.btnAddNewEntry);
btnAddEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent addEntryIntent = new Intent(AllEntriesActivity.this, AddNewEntry.class);
addEntryIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
overridePendingTransition(0, 0);
startActivity(addEntryIntent);
}
});
}
// public void loadItem(final EntryItem item) {
// if (mClient == null) {
// return;
// }
//
// // Set the item as completed and update it in the table
// //item.setComplete(true);
//
// AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
// #Override
// protected Void doInBackground(Void... params) {
// try {
//
// //checkItemInTable(item);
// runOnUiThread(new Runnable() {
//// #Override
//// public void run() {
//// if (item.isComplete()) {
//// mAdapter.remove(item);
//// }
//// }
// });
// } catch (final Exception e) {
// createAndShowDialogFromTask(e, "Error");
// }
//
// return null;
// }
// };
//
// runAsyncTask(task);
// }
private void refreshItemsFromTable() {
// Get the items that weren't marked as completed and add them in the
// adapter
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>(){
#Override
protected Void doInBackground(Void... params) {
try {
final List<EntryItem> results = refreshItemsFromMobileServiceTable();
//Offline Sync
//final List<ToDoItem> results = refreshItemsFromMobileServiceTableSyncTable();
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.clear();
for (EntryItem item : results) {
mAdapter.add(item);
}
}
});
} catch (final Exception e){
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
private List<EntryItem> refreshItemsFromMobileServiceTable() throws ExecutionException, InterruptedException {
return mEntryTable.where().field("active").
eq(val(true)).execute().get();
}
private AsyncTask<Void, Void, Void> initLocalStore() throws MobileServiceLocalStoreException, ExecutionException, InterruptedException {
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
try {
MobileServiceSyncContext syncContext = mClient.getSyncContext();
if (syncContext.isInitialized())
return null;
SQLiteLocalStore localStore = new SQLiteLocalStore(mClient.getContext(), "OfflineStore", null, 1);
Map<String, ColumnDataType> tableDefinition = new HashMap<String, ColumnDataType>();
tableDefinition.put("id", ColumnDataType.String);
tableDefinition.put("date", ColumnDataType.String);
tableDefinition.put("time", ColumnDataType.String);
tableDefinition.put("newentry", ColumnDataType.String);
tableDefinition.put("description", ColumnDataType.String);
tableDefinition.put("location", ColumnDataType.String);
tableDefinition.put("image", ColumnDataType.String);
localStore.defineTable("EntryItem", tableDefinition);
SimpleSyncHandler handler = new SimpleSyncHandler();
syncContext.initialize(localStore, handler).get();
} catch (final Exception e) {
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
return runAsyncTask(task);
}
private void createAndShowDialogFromTask(final Exception exception, String title) {
runOnUiThread(new Runnable() {
#Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
private void createAndShowDialog(Exception exception, String title) {
Throwable ex = exception;
if (exception.getCause() != null) {
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
private void createAndShowDialog(final String message, final String title) {
final android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
}
I have no idea what's wrong, no error is thrown and my activity doesn't show anything in the list view.
Verify that the mobile service is returning data. Set a breakpoint on the following line:
final List results = refreshItemsFromMobileServiceTable()
Then, view the results of the results List.
->If results is empty, you either have no data or there is a problem with your mobile service or there is a problem with the call to your mobile service.
->If results contains the expected data, you have a problem with the code displaying this data to your form.

No Progress Bar update...Async

I'm simply loading an image on button click via url , i want progress bar to show downloadin done,0-100 now i had changed the code not showing the progress updation but only progress bar
kindly help. XML has a button [downloadbtn], and a progressbar, imageview and a quit button
mainfest.xml has acsess permission internet
code:
*
package com.example.t4;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
ProgressBar prgs;
ProgressTask task = new ProgressTask();
Button showProgressBtn;
Button stopProgressBtn;
ImageView img;
Bitmap bmp ;
TextView tv1;
int filesize,filedyn;
public void startdownload(){
try { URL url;
url = new URL("http://whywedoit.files.wordpress.com/2009/04/smile.jpg");
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
filesize = urlConnection.getContentLength();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv1=(TextView)findViewById(R.id.tv1);
img = (ImageView) findViewById(R.id.imageView1) ;
stopProgressBtn = (Button) findViewById(R.id.btnCancel);
prgs = (ProgressBar) findViewById(R.id.progress);
showProgressBtn = (Button) findViewById(R.id.btn);
prgs.setVisibility(View.INVISIBLE);
img.setVisibility(View.INVISIBLE);
tv1.setVisibility(View.INVISIBLE);
final ProgressTask pgt = new ProgressTask();
showProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(pgt.getStatus()==Status.RUNNING){Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();}
if(pgt.getStatus()==Status.FINISHED||pgt.getStatus()==Status.PENDING){
Toast.makeText(getApplicationContext(), "Status"+pgt.getStatus(), Toast.LENGTH_SHORT).show();
prgs.setVisibility(View.VISIBLE);
task.execute(10);
tv1.setVisibility(View.VISIBLE);
}}
});
stopProgressBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
stopProgress();
}
});
}
private class ProgressTask extends AsyncTask<Integer,Integer,Void>{
protected void onPreExecute() {
super.onPreExecute();
prgs.setMax(100); // set maximum progress to 100.
}
protected void onCancelled() {
prgs.setMax(0); // stop the progress
Log.v("Progress","Cancelled");
finish();
}
protected Void doInBackground(Integer... params) {
startdownload();
//for(int j=0;j<=filesize;j++){
publishProgress((int) ((filedyn / (float) filesize) * 100));
//}
Log.v("Progress","Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(0);
Log.v("Progress","Updating");
}
protected void onPostExecute(Void result) {
img.setVisibility(View.VISIBLE);
tv1.setVisibility(View.INVISIBLE);
img.setImageBitmap(bmp);
prgs.setVisibility(View.INVISIBLE);
Log.v("Progress", "Finished");
}
}
public void stopProgress() {
task.cancel(true);
}
}
*
Sorry, I don't think you only have progress bar update problems. There are too many points needs to be repaired.
1st inside your OnClickListener, you are doing task.execute(10);showProgress(); AsnycTask is asynchronous task, you cannot put your showProgress() there. Do something with your code.
private boolean init = true;
private Void doInBackground(Integer... params) {
init = true;
startdownload();
Log.v("Progress", "Downloading");
return null;
}
protected void onProgressUpdate(Integer... values) {
if (init){
showProgress();
init = false;
}else{
prgs.setProgress(5);
Log.v("Progress", "Once");
}
}
2nd startdownload method, are you sure your startdownload method doing downloading? or just getting the length of filesize. Make it clear else you will get yourself confuse.
3nd To invoke onProgressUpdate, you need to call publishProgress(progressValue); Here's the sample.
private Void doInBackground(Integer... params) {
init = true;
startdownload();
publishProgress(5); // onProgressUpdate invoked
//
// doing download
//
Log.v("Progress", "Downloading");
return null;
}
use this code and use progressdialog instead of progressbar
#Override
protected void onProgressUpdate(Integer... progress) {
//Set the pertange done in the progress dialog
pd.setProgress((int) (progress[0]));
}
You need set the ProgressBar max value and you need to update the progress in onProgressUpdate
protected void onProgressUpdate(Integer... values) {
prgs.setProgress(values[0]);
Log.v("Progress","Once");
}
and call
publishProgress(progress)
in the doInBackground of ProgressTask to update the progress
Check for more ref

showing images in android grid

I am new to android so please be patient with me , I am creating this code to draw a gridview of images , and I am using asynctask , however my problem is the asynctask is running so binding the image becomes late and the image isnt shown , when i debug it's shown because i delay it so i know the problem but i hope someone fixes the syntax for me , thanks alot .
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImagesAdapter extends BaseAdapter implements ListAdapter {
private Context mContext;
ImageView currentImageView;
Bitmap bmImg;
// Constructor
public ImagesAdapter(Context c) {
super();
mContext = c;
GridViewConfig.addImageUrls();
}
#Override
public int getCount() {
return GridViewConfig.getResim_list().size();
}
#Override
public Object getItem(int position) {
return GridViewConfig.getResim_list().get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null)
{
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(5, 5, 5, 5);
} else {
imageView = (ImageView) convertView;
}
downloadFile(GridViewConfig.getResim_list().get(position));
imageView.setImageBitmap(bmImg);
// imageView.setImageDrawable(LoadImageFromURL(GridViewConfig
// .getResim_list().get(position)));
return imageView;
}
void downloadFile(String fileUrl) {
AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
#Override
protected String doInBackground(String... params) {
URL myFileUrl = null;
try {
myFileUrl = new URL(params[0]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String unused) {
/* if (currentImageView == null) {
currentImageView = new ImageView(mContext);
}
currentImageView.setImageBitmap(bmImg); */
}
};
task.execute(fileUrl);
}
gridviewconfig class returns the needed images.
Take a look at http://developer.android.com/training/displaying-bitmaps/index.html There is a BitmapFun sample project/app with the grid and many useful stuff. I recommend you not to reinvent the wheel but to use google's code who are the creators of Android
also I suggest you to study some LazyList implementation

call onListItemClick() after execution of onPostExecute(Void result) android

I am having problem to call onListItemClick() function after execution of onPostExecute(Void result)
Below is my code snippet .
package com.myapp.checkoutnhangout;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class CheckoutNearestPlaces extends ListActivity {
private String[] placeName;
private String[] imageUrl;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new GetPlaces(this,getListView()).execute();
}
class GetPlaces extends AsyncTask<Void, Void, Void> {
Context context;
private ListView listView;
private ProgressDialog progressDialog;
public GetPlaces(Context context , ListView listView) {
this.context = context;
this.listView = listView;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setIndeterminate(true);
progressDialog.setTitle("Loading");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
findNearLocation();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (UnrecoverableKeyException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
progressDialog.dismiss();
setListAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
// this.listView.setAdapter(new ArrayAdapter<String>(context,android.R.layout.simple_list_item_1,placeName));
}
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
public void findNearLocation() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
PlacesService placesService = new PlacesService("AIzaSyC3y3fOMTqTkCjNNETQTCKustG7BRk_eVc");
List<Place> findPlaces = placesService.findPlaces(28.6752, 77.4362, "");
int findPlacesSize = findPlaces.size();
placeName = new String[findPlacesSize];
imageUrl = new String[findPlacesSize];
for(int index = 0 ; index < findPlacesSize ; index ++) {
Place placeDetail = findPlaces.get(index);
// System.out.println("name of place : "+placeDetail.getName());
placeName[index] = placeDetail.getName();
// System.out.println("url of place : "+placeDetail.getIcon());
imageUrl[index] = placeDetail.getIcon();
}
}
}
}
Above code use google palce api and display list of locations on the basis of user's interest .
After that , I want to call onListItemClick() function , so that I can call another activity on each item click.
Any help will be appreciable.
remove
public void onListItemClick(ListView listView , View v , int position , long id){
System.out.println("position------------"+placeName[position]);
}
from class GetPlaces
and put in CheckoutNearestPlaces

confusion to pass argument in asyncTask

In my application i get image from server and those image build animation.this all things are gone be right way and i create method for it.this is the method::
package com.animation;
import java.io.InputStream;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Button;
import android.widget.ImageView;
public class animation extends Activity {
Button Buttona;
AnimationDrawable animation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.simple_anim);
animation = new AnimationDrawable();
try {
for(int i=0;i<54;i++)
{
xyz("girl000",i);
}
animation.setOneShot(false);
} catch (Exception e) {
}
img.setBackgroundDrawable(animation);
img.post(new Starter());
}
public void xyz(String str,int x)
{
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
"http://201.109.115.111/MRESC/images/test/girl/"+"girl000"+x+".png")
.getContent());
Drawable frame =new BitmapDrawable(bitmap);
animation.addFrame(frame, 50);
} catch (Exception e) {
}
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
}
now my problem is it is take much time to load image from server so simply i plan to use asyncTask. but problem is i cant get judgment that how can i do this?
can you give me example(Note : i know asyncTask and use already but problem is passing argument as per my xyz() method declare)
Thanks
nik
Here is the code:
Note that the loop now is in the background thread
After each loop, you publish the progress to setup the animation frame
At the very end, you run onPostExecute to run the remaining code
Note, that this is just a skeleton and rough sketches, you need to understand and debug it if there is any problem. I haven't run the code yet
public class Animation extends Activity {
Button Buttona;
AnimationDrawable animation;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
animation = new AnimationDrawable();
AsyncTask asyncTask =
new AsyncTask() {
#Override
protected Void doInBackground(Void... params) {
try {
// Execute this whole loop in background, so it doesn't
// block your UI Thread
for(int i=0;i<54;i++) {
xyz("girl000",i);
}
} catch (Exception e) {
return null;
}
}
public void xyz(String str,int x) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
"http://201.109.115.111/MRESC/images/test/girl/"+"girl000"+x+".png")
.getContent());
// publish progress so that the bitmap is set on the UI Thread
publishProgress(bitmap);
} catch (Exception e) {
// handle error
}
}
#Override
protected void onProgressUpdate(Bitmap... result) {
// handle the progress update to add the animation frame
Bitmap bitmap = result[0];
Drawable frame =new BitmapDrawable(bitmap);
animation.addFrame(frame, 50);
}
#Override
protected void onPostExecute(Void result) {
if(result != null) {
// execute the rest of your instruction after the loop is over here
animation.setOneShot(false);
ImageView img = (ImageView) findViewById(R.id.simple_anim);
img.setBackgroundDrawable(animation);
img.post(new Starter());
} else {
// handle error
}
}
};
asyncTask.execute();
}
class Starter implements Runnable {
public void run() {
animation.start();
}
}
}

Categories

Resources