Image Bitmap from URL - java

I am trying to get images from URLs in a string array and my app is crashing. It is crashing on line 110: InputStream input = connection.getInputStream(); What am I doing wrong?
Here is my class:
package kyfb.android.kyfb.com.kyfb;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.media.Image;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by KFB on 8/12/14.
*/
class ActionAlertsAdapter extends BaseAdapter {
private LayoutInflater inflater;
public ActionAlertsAdapter(Context context) {
inflater = LayoutInflater.from(context);
}
public int getCount() {
// TODO Auto-generated method stub
return ActionAlertsFragment.title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if(convertView == null){
convertView = inflater.inflate(R.layout.item_feed, null);
holder = new ViewHolder();
holder.lytItemFeed = (RelativeLayout) convertView.findViewById(R.id.lytItemFeed);
holder.txtTitle= (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtPubDate = (TextView) convertView.findViewById(R.id.txtPubDate);
holder.thumbnail = (ImageView) convertView.findViewById(R.id.thumbnail);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
if((position%2)!=0){
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}else{
holder.lytItemFeed.setBackgroundColor(Color.TRANSPARENT);
}
holder.txtTitle.setText(ActionAlertsFragment.title[position]);
holder.txtPubDate.setText(ActionAlertsFragment.pubDate[position]);
Bitmap bitmap = getBitmapFromURL(ActionAlertsFragment.thumb[position]);
if(bitmap == null) {
holder.thumbnail.setImageResource(R.drawable.kyfb);
}
else {
holder.thumbnail.setImageBitmap(bitmap);
}
holder.txtTitle.setTextColor(Color.WHITE);
holder.txtPubDate.setTextColor(Color.WHITE);
return convertView;
}
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
static class ViewHolder {
TextView txtTitle, txtPubDate;
ImageView thumbnail;
RelativeLayout lytItemFeed;
}
}

This doesn't directly answer your question, but you might want to consider using an image loading library such as Picasso or Volley. There is a lot of complexity--some subtle, some not so much--in loading images from network, even more so when you're trying to do it in a ListView. Both of those libraries (and several others out there) take care of all or most of the complexity for you.

You should move your method in an AsyncTask. You are downloading stuff on your main thread.

Related

caching images from json in listview?

I followed this lesson here which talk about json parsing and image loading in list view the example works good but it has a problem in imageview when scrolling up & down all images reloading so can anyone solve this problem?
this the adapter of listview
package com.wingnity.jsonparsingtutorial;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ActorAdapter extends ArrayAdapter<Actors> {
ArrayList<Actors> actorList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
actorList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
holder.tvName = (TextView) v.findViewById(R.id.tvName);
holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
holder.tvSpouse = (TextView) v.findViewById(R.id.tvSpouse);
holder.tvChildren = (TextView) v.findViewById(R.id.tvChildren);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imageview.setImageResource(R.drawable.ic_launcher);
new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
holder.tvName.setText(actorList.get(position).getName());
holder.tvDescription.setText(actorList.get(position).getDescription());
holder.tvDOB.setText("B'day: " + actorList.get(position).getDob());
holder.tvCountry.setText(actorList.get(position).getCountry());
holder.tvHeight.setText("Height: " + actorList.get(position).getHeight());
holder.tvSpouse.setText("Spouse: " + actorList.get(position).getSpouse());
holder.tvChildren.setText("Children: " + actorList.get(position).getChildren());
return v;
}
static class ViewHolder {
public ImageView imageview;
public TextView tvName;
public TextView tvDescription;
public TextView tvDOB;
public TextView tvCountry;
public TextView tvHeight;
public TextView tvSpouse;
public TextView tvChildren;
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Used the Android Universal Image-Loader This is best
Declare
private ImageLoader imageLoader1;
On Create
imageLoader1 = ImageLoader.getInstance();
imageLoader1.init(ImageLoaderConfiguration.createDefault(getActivity()));
no_image here a drawable image without any image load in Cache
DisplayImageOptions
options = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.cacheOnDisk(true)
.showImageOnLoading(R.drawable.no_image) // resource or drawable
.showImageForEmptyUri(R.drawable.no_image) // resource or drawable
.showImageOnFail(R.drawable.no_image)
.considerExifParams(true)
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
imageLoader1.displayImage(yourpath.replace(" ", "%20"), ivprofile, options);
You Can Use Piccaso Also and Glide also
here is the code after editing it works like a charm
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;
public class ActorAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Actors> movieItems;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
public ActorAdapter(Activity activity, List<Actors> movieItems) {
this.activity = activity;
this.movieItems = movieItems;
}
#Override
public int getCount() {
return movieItems.size();
}
#Override
public Object getItem(int location) {
return movieItems.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_item, null);
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
NetworkImageView thumbNail = (NetworkImageView) convertView
.findViewById(R.id.flag);
TextView title = (TextView) convertView.findViewById(R.id.rank);
// getting movie data for the row
Actors m = movieItems.get(position);
// thumbnail image
thumbNail.setImageUrl(m.getImage(), imageLoader);
// title
title.setText(m.getName());
return convertView;
}
}

Implement Custom Gridview in Android [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Hi i am new to android development. I have made an app where picture are now shown in a gridview. But i want to make it more user friendly. I have found an example but i need some help to implement my code as the example. I want to write my UserList.java as ImageAdapter.java. I want to use imageview instead of holder. How can i do that??
Example i am trying to follow:
ImageAdapter.java
package com.step2rock.www.photographynowroadtopro;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Created by Sushimz on 5/7/2016.
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5, R.drawable.pic_6,
// R.drawable.pic_7, R.drawable.pic_8,
// R.drawable.pic_9, R.drawable.pic_10,
// R.drawable.pic_11, R.drawable.pic_12,
// R.drawable.pic_13, R.drawable.pic_14,
// R.drawable.pic_15
};
// Constructor
public ImageAdapter(Context c){
mContext = c;
}
#Override
public int getCount() {
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(mThumbIds[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
return imageView;
}
}
Now Here is my code.
UserList.java
package com.step2rock.www.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.step2rock.www.crudproject.R;
import com.step2rock.www.crudproject.UserlistActivity;
import com.step2rock.www.model.User;
public class UserList extends BaseAdapter {
private Context mContext;
LayoutInflater inflater;
UserlistActivity activity;
ArrayList<User> users;
public UserList(Context context, ArrayList<User> users) {
mContext = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.users = users;
}
#Override
public int getCount() {
return users.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
static class ViewHolder {
public ImageView ivUserImage;
public TextView tvUserName;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
activity = new UserlistActivity();
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.userrow_activity, null);
holder.ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserImage);
holder.tvUserName = (TextView) convertView.findViewById(R.id.tvHeader);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
User user = new User();
user = users.get(position);
holder.ivUserImage.setImageBitmap(convertToBitmap(user.get_user_pic()));
holder.tvUserName.setText(user.get_first_name());
return convertView;
}
public Bitmap convertToBitmap(String base64String) {
byte[] decodedString = Base64.decode(base64String, Base64.DEFAULT);
Bitmap bitmapResult = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
return bitmapResult;
}
}
You are new to android and want to create a grid of showing pictures.
You can develop the grid like below Follow this tutorial.

Getting Images from url in ListView

I am trying to get images from url and set it in a listview through my listviewadapter class. I am getting NULLPOINTEREXCEPTION at openConnection()
in getBitmapFromUrl method at the end.
Here is my code:
ListViewAdapter.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
Bitmap[] myBitmap = new Bitmap[8];
public Activity context;
int positionX;
URL urlX;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return msgData.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
URL url = null;
try {
url = new URL(msgData[position]);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
urlX=url;
positionX=position;
try {
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
holder.imgView.setImageBitmap(myBitmap[position]);
}
return convertView;
}
public Bitmap getBitmapFromUrl(URL url1) {
Bitmap Bitmap = null;
try {
HttpURLConnection connection = (HttpURLConnection) url1
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
}
return Bitmap;
}
}
EDIT:
Thread t = new Thread(new Runnable() {
public void run(){
myBitmap[positionX] = getBitmapFromUrl(urlX);
}
});
t.start();
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LOGCAT(after edit):
04-03 12:01:26.860: E/AndroidRuntime(11944): FATAL EXCEPTION: Thread-1155
04-03 12:01:26.860: E/AndroidRuntime(11944): java.lang.NullPointerException
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter.getBitmapFromUrl(ListViewAdapter.java:127)
04-03 12:01:26.860: E/AndroidRuntime(11944): at com.appquest.flatcassign.ListViewAdapter$1.run(ListViewAdapter.java:107)
04-03 12:01:26.860: E/AndroidRuntime(11944): at java.lang.Thread.run(Thread.java:856)
Hi I update your base adpter class see blow with implement of the picasso library, you just have to copy and replace the code, sure help you. do not forget to add the jar file.
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class ListViewAdapter extends BaseAdapter {
public String msgType[] = new String[8];
public String msgData[] = new String[8];
public String msgTimeStamp[] = new String[8];
public Activity context;
public LayoutInflater inflater;
public ListViewAdapter(Activity context, String[] type, String[] data,
String[] timestamp) {
super();
this.context = context;
this.msgType = type;
this.msgData = data;
this.msgTimeStamp = timestamp;
this.inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return msgData.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
ImageView imgView;
TextView txtType;
TextView txtData;
TextView txtTimestamp;
Bitmap myBitmap;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.list_item, null);
holder.imgView = (ImageView) convertView.findViewById(R.id.image);
holder.txtType = (TextView) convertView.findViewById(R.id.type);
holder.txtData = (TextView) convertView.findViewById(R.id.data);
holder.txtTimestamp = (TextView) convertView
.findViewById(R.id.timestamp);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// holder.imgView.setImageBitmap(myBitmap[position]);
holder.txtType.setText(msgType[position]);
holder.txtTimestamp.setText(msgTimeStamp[position]);
if (msgType[position].equals("0"))
holder.txtData.setText(msgData[position]);
else {
holder.txtData.setText("");
Picasso.with(context).load(msgData[position]).into(holder.imgView);
}
return convertView;
}
}
Thank you.

Can not reference async task in custom adapter

The problem is , when I set the async download task at custom adapter getView function, it return
ImageLoader cannot be resolved to a type
error. The class is in different package of same project, it normally can import but in this case it only show error. How to fix the problem? Thanks for helping
LeadersAdapter.java
public class LeadersAdapter extends ArrayAdapter<Record> {
public LeadersAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public LeadersAdapter(Context context, int resource, List<Record> items) {
super(context, resource, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.leader_record_row, null);
}
Record p = getItem(position);
if (p != null) {
ImageView pic = (ImageView) v.findViewById(R.id.profile_pic);
TextView name = (TextView) v.findViewById(R.id.name);
TextView pts = (TextView) v.findViewById(R.id.pts);
new ImageLoader().execute(pic,p.url);
name.setText(p.name);
pts.setText(p.pts);
}
return v;
}
}
ImageLoader.java
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.widget.ImageView;
class ImageLoader extends AsyncTask<Object, Void, Bitmap> {
private static String TAG = "ImageLoader";
public InputStream input;
public ImageView view;
public String imageURL;
public ImageLoader(String text){
}
#Override
protected Bitmap doInBackground(Object... params) {
try {
view = (ImageView) params[0];
imageURL = (String) params[1];
URL url = new URL(imageURL);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
protected void onPostExecute(Bitmap result) {
if (result != null && view != null) {
view.setImageBitmap(result);
}
}
}
Your ImageLoader class (which is not defined as public) is using the default access modifier, package-private, so it is only visible in it's own package.
Changing...
class ImageLoader [...]
to...
public class ImageLoader [...]
should fix your accessibility problem.
Also, I would highly recommend looking into an existing image loading library (like Universal Image Loader) instead of baking your own.
I'd recommend Square's Picasso lib, which is easy to use.
Simple one line to load image from web into ImageView.
Ex:
Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);

Error while accessing the array

Noob android developer trying to create a gallery with thumbnails saved on my server:
I am trying to use my ArrayList in my ImageAdapter so that I can reference my array values when creating my thumbnail list loop. My eclipse package is available for download here since I may not explain this correctly. When I do trying and reference my "thumb" values in my array I am getting an undefined error along with a syntax error when trying to create my "mThumbIds"
I am not sure why I am having such a hard time understanding this.
showThumb.java:
package com.flash_tattoo;
import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class showThumb extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gridlayout);
Bundle bundle = getIntent().getExtras();
String jsonData = bundle.getString("jsonData");
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(jsonData);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<image_data> myJSONArray = new ArrayList<image_data>();
for(int i=0;i<jsonArray.length();i++)
{
JSONObject json_data = null;
try {
json_data = jsonArray.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.id = json_data.getInt("id");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.name = json_data.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.thumb = json_data.getString("thumb");
} catch (JSONException e) {
e.printStackTrace();
}
try {
image_data.path = json_data.getString("path");
} catch (JSONException e) {
e.printStackTrace();
}
myJSONArray.add(new image_data());
}
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this,myJSONArray));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(showThumb.this, "" + position, Toast.LENGTH_SHORT).show();
}
});
}
}
ImageAdapter:
package com.flash_tattoo;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
public class ImageAdapter extends ArrayAdapter<image_data>
{
//This code below was put in when I change from BaseAdapter to ArrayAdapter
public ImageAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
// TODO Auto-generated constructor stub
}
private Context mContext;
public int getCount() {
return mThumbIds.length;
}
public image_data 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) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
for(int i=0;i<myJSONArray.lenght();i++){
Object[] myJSONArray;
setImageDrawable(Drawable.createFromPath(myJSONArray[i].thumb)
};
};
}
You have there a private field mThumbIds of type Integer[] and you're trying to initialize it inline, but you fail to do so because you have an static block {} with statements.
I would say you need to just declare:
private Integer[] mThumbIds;
then, in the constructor you can populate the array.

Categories