Android - Listview adapter with asynctask to load images - android

I'm trying to handle an image loading at the background.
Now, I've look at the next link - here
And I've got few things I don't understand -
1) I've made the next CursorAdapter for the listview items-
public class ChatCursorAdapter extends CursorAdapter implements OnClickListener {
public ChatCursorAdapter(Context context, Cursor c) {
super(context, c, 0);
}
#Override
public int getCount() {
return getCursor() == null ? 0 : super.getCount();
}
#Override
public int getViewTypeCount() {
return 2;
}
#Override
public int getItemViewType(int _position) {
Cursor cursor = (Cursor) getItem(_position);
return getItemViewType(cursor);
}
private int getItemViewType(Cursor cursor) {
String sender = cursor.getString(2);
SharedPreferences userPref = PreferenceManager
.getDefaultSharedPreferences(MainChat.this);
String saveUser = userPref.getString("user", "");
if (saveUser.equalsIgnoreCase(sender)){
return 0;
}else{
return 1;
}
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
holder = (ViewHolder) view.getTag();
holder.mesg.setText(getSmiledText(MainChat.this,msg));
holder.mesg2.setText(getSmiledText(MainChat.this,msg2));
holder.myImage.setTag(picPath);
holder.myImage.setImageBitmap(setImageToImageView(picPath));
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
View itemLayout = null;
switch(getItemViewType(cursor)){
case 0:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item1,parent, false);
break;
case 1:
itemLayout = getLayoutInflater().inflate(R.layout.msg_item13, parent,false);
break;
}
itemLayout.setTag(holder);
holder.mesg = (TextView) itemLayout.findViewById(R.id.text_start);
holder.mesg2 = (TextView) itemLayout.findViewById(R.id.text_end);
holder.myImage = (ImageView) itemLayout.findViewById(R.id.imageView_msgpic);
return itemLayout;
}
Now i wnat to use the info from the link.
But i don't understand - What i need to pass into the and what to AsyncTask leave at CursorAdapter?
Also the sample code uses -
.execute(holder);
Can't I call to the AsyncTask like this -
new AsyncTask().execute();
And how and where should i call the AsyncTask, I don't understand it?
Thanks for any kind of help

You could always use an external lib like Universal-Image-Loader or Picasso to achieve what you are trying to do =)

Take a look at AsyncTask. You must Override doInBackground method. You may define a constructor to supply view in which you want to put downloaded image.
public class ImageDownloader extends AsyncTask<String, Void, List<Bitmap>> {
private ImageView ivImageHolder;
private Context context;
public ImageDownloader(Context context, ImageView imageHolder) {
this.ivImageHolder = imageHolder;
this.context = context;
}
...
#Override
protected List<Bitmap> doInBackground(String... params) {
//This happens in background
List<Bitmap> bitmaps = new ArrayList<Bitmap>();
for (String url : params) {
Bitmap bitmap = DownloadImage(url);
bitmaps.add(bitmap);
}
return bitmaps;
}
....
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
...
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
#Override
protected void onPostExecute(List<Bitmap> bitmaps) {
super.onPostExecute(bitmaps);
for (int i = 0; i < bitmaps.size(); i++) {
final Bitmap bitmap = bitmaps.get(i);
ivImageHolder.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new ImageViewActivity(context, bitmap).show();
}
});
// iv.setImageBitmap(bitmap);
ivImageHolder.setImageBitmap(bitmap);
ivImageHolder.setVisibility(ImageView.VISIBLE);
}
}

if you write your asyntask method I can say how can you use it, If it need to string value
you can use like this:
new your_async(context).execute(url) ;
But in my advice : you should use lazyadapter to use bitmaps on listview because there is a mermory issue if you do not pay attention properties of images.
here is link : stackoverfow

Related

android asynctask is not executing inside baseadapter

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();

Why my application crashes when I scroll quickly (or a lot) my GridView?

I am filling a GridView with my facebook friends' photo.
When I use my account of tester with few friends my application works good. But when I use my main account and I scroll quickly my application I get This error:
AndroidRuntime(6131): java.util.concurrent.RejectedExecutionException: Task android.os.AsyncTask$3#42230f20 rejected from java.util.concurrent.ThreadPoolExecutor#4206af70[Running, pool size = 128, active threads = 128, queued tasks = 10, completed tasks = 61]
otherwise
If i scroll a lot i get this error:
java.lang.RuntimeException: An error occured while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:299)
Caused by: java.lang.NullPointerException at it.alfonso.utils.GetImageFromUrlAsyncTask.downloadImage(GetImageFromUrlAsyncTask.java:62)
if (facebookAdapter == null) {
facebookAdapter = new ImageAdapterFacebook(this, facebookResponses);
gridview.setAdapter(facebookAdapter);
}
else {
gridview.setAdapter(facebookAdapter);
}
My adapeter for my GridView
public class ImageAdapterFacebook extends BaseAdapter {
private Context mContext;
private FacebookResponses facebookFrinds;
public ImageAdapterFacebook(Context c, FacebookResponses facebookFrinds) {
mContext = c;
this.facebookFrinds = facebookFrinds;
}
public int getCount() {
return facebookFrinds == null ? 0 : facebookFrinds.getData().length;
}
public Object getItem(int position) {
return facebookFrinds == null ? null
: facebookFrinds.getData()[position];
}
public long getItemId(int position) {
return position;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View amico, ViewGroup parent) {
final ImmageViewHolder viewHolder;
if (amico == null) { // if it's not recycled, initialize some attributes
LayoutInflater li = (LayoutInflater) parent.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
amico = li.inflate(R.layout.details_img_facebook_user, parent,
false);
viewHolder = new ImmageViewHolder();
viewHolder.userImage = (ImageView) amico
.findViewById(R.id.userLikesimg);
amico.setTag(viewHolder);
} else {
viewHolder = (ImmageViewHolder) amico.getTag();
}
if (facebookFrinds != null) {
viewHolder.userImage.setImageResource(R.drawable.image_loader);
String imgUserurl = facebookFrinds.getData()[position]
.getPic_square();
// Create an object for subclass of AsyncTask
GetImageFromUrlAsyncTask task = new GetImageFromUrlAsyncTask(
mContext, new DownloadImageLister() {
#Override
public void onDownloadImageSucces(Bitmap immagine) {
viewHolder.userImage.setImageBitmap(immagine);
}
#Override
public void onDownloadImageFail() {
System.out.print("errore");
}
});
task.execute(imgUserurl);
}
return amico;
}
public class ImmageViewHolder {
ImageView userImage;
}
}
My AsyncTask
public class GetImageFromUrlAsyncTask extends AsyncTask<String, Void, Bitmap> {
private Context contesto;
private DownloadImageLister listenerImage;
public GetImageFromUrlAsyncTask(Context context,
DownloadImageLister listener) {
contesto = context;
listenerImage = listener;
}
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null ) {
listenerImage.onDownloadImageSucces(result);
}
if (result == null ) {
listenerImage.onDownloadImageFail();
}
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
Since you are performing so many requests for each image load your app is crashing. You could use the Volley Android library and its NetworkImageView. This is what several Google apps are using for async image loading and http requests. There is a good tutorial explaining how to use it here: http://www.captechconsulting.com/blog/clinton-teegarden/android-volley-library-tutorial.
Hope that helps!

Display Image in a Listview (In Adapter) using Json

Please bear with me before downvoting this.I am a beginner to Android. After trying multiple solutions on here I have failed to resolve this.
I am trying to set the Image in the listview with the following items in place.I want to be able to insert the image code somewhere on the Schedule adapter class.
The following code is my Schedule Adapter
public class Schedule_ArrayAdapter extends ArrayAdapter<String> {
private final Activity activity;
private final String[] name, category, image;
Typeface colab, colab_bold, Bebas;
int selected = -1;
public Schedule_ArrayAdapter(Activity activity, String[] name, String[] category, String[] image) {
super(activity, R.layout.schedule_item, category);
this.activity = activity;
this.name = name;
this.category = category;
this.image = image;
this.colab = Typeface.createFromAsset(activity.getAssets(), "ColabThi.otf");
this.colab_bold = Typeface.createFromAsset(activity.getAssets(), "ColabMed.otf");
this.colab_bold = Typeface.createFromAsset(activity.getAssets(), "BebasNeue.otf");
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//get view and textview from xml
View rowView = inflater.inflate(R.layout.schedule_item, parent, false);
rowView.setBackgroundColor(0xffffffff);
LinearLayout background = (LinearLayout) rowView.findViewById(R.id.back);
if (selected != -1) {
if (selected == position) {
background.setBackgroundColor(0xffeaac4b);
} else {
background.setBackgroundColor(0xffffffff);
}
}else{
background.setBackgroundColor(0xffffffff);
}
TextView TimeView = (TextView) rowView.findViewById(R.id.category);
TextView TitleView = (TextView) rowView.findViewById(R.id.title);
ImageView vi = (ImageView) rowView.findViewById(R.id.imgPreview);
GetImage getimage = new GetImage();
getimage.execute(image);
//change names
TitleView.setText(category[position]);
TitleView.setTextSize(fontpercent_screenheight(3.5));
TitleView.setPadding(dp(10), dp(5), dp(5), dp(0));
TitleView.setTypeface(Bebas);
TimeView.setText(name[position]);
TimeView.setTextSize(fontpercent_screenheight(3.5));
TimeView.setPadding(dp(10), dp(2), dp(5), dp(5));
TimeView.setTypeface(colab);
return rowView;
}
The following is my ImageDownloader class
public class ImageDownloader {
private InputStream OpenHttpConnection(String image) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(image);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
conn.setUseCaches(true);
HttpURLConnection httpConn = (HttpURLConnection) conn;
try {
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting" + ex);
}
return in;
}
public Bitmap DownloadImage(String image) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(image);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
}
Parsing of JSON and fetching Data is working as normal. When looking in the debugger the "image" array is also been fetched. How do i set the images in the view ?
So in your getView of the adapter you should make a request to some url and use the
Bitmap bitmap=BitmapFactory.decodeStream(inputstream);
now set this in your imageview of your layout
ImageView i=(ImageView)findViewById(R.id.imageiew);
i.setImageResource(bitmap);
so that shows the image.
You can also try this code
ImageView iv=(ImageView) findViewById(R.id.imageview);
try {
iv.setImageDrawable(grabImageFromUrl(Global.a5));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
the function of fetching image from URL is
private Drawable grabImageFromUrl(String url) throws Exception {
return Drawable.createFromStream((InputStream)new URL(url).getContent(), "src"); }

image display as gridview

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

FATAL Exception main while displaying images in listview

I am at beginner level, i am populating listview with different remote images and text in an android app. I am using adapter to populate listview and AsynTask to load images. But i am facing two problems and tried most since many days but unfortunately can't success. First problem is that first image and text appears in first row of listview and disappears than second row being populated with second image and text and also disappears and similarly each rows appears with images and text and disappears. Second problem is that when final row appears than app crashes and stopped running giving below exception:
11-01 20:03:56.449: ERROR/AndroidRuntime(29665): FATAL EXCEPTION: main
11-01 20:03:56.449: ERROR/AndroidRuntime(29665): java.lang.NullPointerException
This is my main class:
public class ParseImagesActivity extends ListActivity {
String myURL;
String xml;
Document doc;
NodeList nodes;
//int i=5;
int j=0;
int equal;
int h;
String[] length = {"1","2","3","4","5","6","7","8","9",null};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
xml = XmlParser.getXML("http://url.com");
doc = XmlParser.XMLfromString(xml);
nodes = doc.getElementsByTagName("item");
Element g = (Element)nodes.item(j);
startParsing(XmlParser.getValue(g,"thumb"));
}
In main class i am calling startParsing method passing it a url..1 to access first image by function XmlParser.getValue(g,"thumb") which return url from XmlParser class. startParsing method is:
private void startParsing(String url) {
new backgroundLoadListView().execute(url);
}
public class backgroundLoadListView extends
AsyncTask<String, Void, String> {
#Override
protected void onPostExecute(String unused) {
// TODO Auto-generated method stub
if(j<nodes.getLength()){
setListAdapter(new MyCustomAdapter(ParseImagesActivity.this, R.layout.row, length));
Log.e("post Execute","post execute="+j);
equal=j;
j++;
Element h = (Element)nodes.item(j);
startParsing(XmlParser.getValue(h,"thumb"));
}
}
#Override
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
//Log.e("do in back","do in back="+j);
String url = params[0];
preLoadSrcBitmap(url);
return null;
}
}
Here i am calling MyCustomerAdapter constructor and in postExecute method i am calling startParsing method passing url2,3,4,...etc to access other images. MyCustomAdapter class and preloadSrcBitmap method are:
public class MyCustomAdapter extends ArrayAdapter<String> {
Bitmap bm;
public MyCustomAdapter(Context context, int textViewResourceId,
String[] objects) {
//
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
bm = srcBitmap;
Log.e("my customer adapter","my adapter"+j);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//return super.getView(position, convertView, parent);
View row = convertView;
if(row==null){
LayoutInflater inflater=getLayoutInflater();
row=inflater.inflate(R.layout.row, parent, false);
}
Log.e("getview",j+"calls");
TextView label=(TextView)row.findViewById(R.id.weekofday);
ImageView icon=(ImageView)row.findViewById(R.id.icon);
if(j<nodes.getLength())
{
if(equal==position)
{
Log.e("text view calls",""+equal);
Element f = (Element)nodes.item(equal);
label.setText(XmlParser.getValue(f, "title"));
icon.setImageBitmap(bm);
}
}
return row;
}
}
Bitmap srcBitmap;
private void preLoadSrcBitmap(String url){
//Log.e("preloadsrcbitmap","preloadsrcbitmap="+j);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
srcBitmap = LoadImage(url, bmOptions);
}
/** Called when the activity is first created. */
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
String selection = l.getItemAtPosition(position).toString();
Toast.makeText(this, selection, Toast.LENGTH_LONG).show();
}
private Bitmap LoadImage(String URL, BitmapFactory.Options options)
{
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bitmap;
}
private 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;
}
And thanks very much to the peoples helping me with mentioned problems. I can't figure them out.
Anything that updates the UI (interacts with the Activity) with an AsyncTask needs to have the following structure (outline because I haven't done this in awhile :P):
//AsyncTask starts here
//code that doesn't run on the UI thread
myASyncTask.runOnUiThread(new Runnable() {
//update your UI stuff here
};
//do more non-UI stuff here
It looks like you're trying to update ImageViews and TextViews synchronously within an AsyncTask method. This will cause Fatal Errors. Try the code above :)
Hope this helps! Let me know if you need more clarification.
Thanks

Categories

Resources