I have the queryAppIcon() method that queries and stores images in the array appIconDrawable. However, I'm only getting blank where images should pop up. Please let me know if I should post any other relevant code
This is the relevant code inside the ViewActivity:
// global vars
final Drawable[] appIconDrawable = null;
int i;
public Drawable[] queryAppIcon() throws ParseException, IOException {
ParseQuery<ParseObject> query = ParseQuery.getQuery("AndroidStoreContent");
query.whereExists("appIcon");
List<ParseObject> ParseResult = query.find();
// Drawable array
appIconDrawable = new Drawable[ParseResult.size()];
for (i = 0; i < ParseResult.size(); i++) {
ParseFile pf = (ParseFile) ParseResult.get(i).get("appIcon");
startDownload(pf);
}
return appIconDrawable;
}
public void startDownload(ParseFile pf) {
new DownloadImageTask(this).execute(pf);
}
public class DownloadImageTask extends AsyncTask<ParseFile, Void, Drawable> {
private AsyncResponse ar;
DownloadImageTask(AsyncResponse ar) {
this.ar = ar;
}
#Override
protected Drawable doInBackground(ParseFile... pf) {
return fetchDrawable(pf[0]);
}
protected void onPostExecute(Drawable result) {
ar.processFinish(result);
}
public Drawable fetchDrawable(ParseFile pf) {
InputStream is;
try {
is = (InputStream) new URL(pf.getUrl()).getContent();
return Drawable.createFromStream(is,null);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
#Override
public void processFinish(Drawable d) {
appIconDrawable[i] = d; // i also tried testing appIconDrawable[1] = d and the app loaded with all blank images and then crashes
}
This is the interface, AsyncResponse:
public interface AsyncResponse {
void processFinish(Drawable d);
}
It seems like you need a bit of refactor...
You are expecting Drawable[] from queryAppIcon() but you will always get an empty set because you start the download which takes place in a separate thread to then update the return value.
You should be setting the Drawable to the ImageView from within processFinish.
Signs of things done wrong: Async methods such as downloading images should never have a return value.
UPDATE
Here is a very simple download AsyncTask but there are many checks, optimizations, etc. missing, like CACHE! Also, ImageView inside DownloadImageTask should be held by a WeakReference (Google it) otherwise it WILL leak your activity.
public class DownloadImageTask extends AsyncTask<String, Void, Drawable> {
private static final String TAG = DownloadImageTask.class.getSimpleName();
private ImageView mImageView;
DownloadImageTask(ImageView imageView) {
mImageView = imageView;
}
#Override
protected Drawable doInBackground(String... url) {
return fetchDrawable(url[0]);
}
#Override
protected void onPostExecute(Drawable result) {
if (result != null) {
mImageView.setImageDrawable(result);
} else {
Log.w(TAG, "Could download image!");
}
}
public static Drawable fetchDrawable(String url) {
Log.v(TAG, "Downloading: " + url);
InputStream is;
try {
is = (InputStream) new URL(url).getContent();
return Drawable.createFromStream(is, null);
} catch (MalformedURLException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
return null;
}
}
Adapter:
public class ImageDownloadAdapter extends ArrayAdapter<String>{
public ImageDownloadAdapter(Context context, String[] objects) {
super(context, R.layout.item_image_download, R.id.txt_url, objects);
}
#SuppressLint("NewApi")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = super.getView(position, convertView, parent);
String url = getItem(position);
ImageView imageView = (ImageView) view.findViewById(R.id.img_download);
DownloadImageTask downloadImageTask = new DownloadImageTask(imageView);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
downloadImageTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url);
} else {
downloadImageTask.execute(url);
}
return view;
}
}
Activity:
ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(new ImageDownloadAdapter(this, new String[]{
"http://www.beautystat.com/site/wp-content/uploads/2011/02/happy-faces-small.jpg",
"http://www.ducthide.com/new_wallet_pics/happy_face.JPG"
}));
Related
I'm solving my problem about Image Loader and I have some problems..
What I want is to show many images (about 400) in GridView(or ListView).
I don't want to use the Library like Picasso, Glide like that.
and Here is the problem.
When I call the method which convert from url to bitmap?
3.1. before setAdapter, then pass the bitmap array.
3.2. while getView.
two things are working well. but too much slow... maybe cuz of the times to call URLConnection..
Could anyone help me about these problem? How can I speed up? or are there any other solution without Open Source.
Here is my Source.
Now, 3-1.
ShowImage
private void showImages(ArrayList<String> imgUrls) {
ArrayList<Bitmap> bitmaps = new ArrayList<>();
for (int i = 0; i < imgUrls.size(); i++) {
try {
String img_path = imgUrls.get(i);
Bitmap bitmap = new UriToBitmapAsyncTask().execute(img_path).get();
bitmaps.add(bitmap);
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
CustomAdapter adapter = new CustomAdapter(getApplicationContext(),R.layout.row,bitmaps);
gridView.setAdapter(adapter);
}
and This is the customAdapter's GetView
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = inflator.inflate(rowLayout, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.imageView.setImageBitmap(bitmaps.get(position));
return convertView;
}
You should really take Reinventing the wheel to heart but if you really want to toture yourself an Approach could be:
use a ThreadPoolExecutor to fetch more images at once, you should read up how to use them
implement a way to cancel threads who load a img for a griditem which isn't displayed anymore
use two sets of data a thumbnail which loads faster for the grid view and a real image which gets loaded when the user clicks on the grid
dont't forget to use a LRU caching method or your device will run out of memory depending on the images
Don't use ArrayList to store bitmaps. Bitmaps usually take consumes a lot of memory. Try using LRUCache like this way,
public class TCImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
public TCImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int maxKb = am.getMemoryClass() * 1024;
int limitKb = maxKb / 8; // 1/8th of total ram
cache = new TCLruCache(limitKb);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
#Override
protected int sizeOf(ImagePoolKey key, Bitmap value) {
int kbOfBitmap = value.getByteCount() / 1024;
return kbOfBitmap;
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
#Override
public void onLowMemory() {
}
#Override
public void onTrimMemory(int level) {
if (level >= TRIM_MEMORY_MODERATE) {
cache.evictAll();
}
else if (level >= TRIM_MEMORY_BACKGROUND) {
cache.trimToSize(cache.size() / 2);
}
}
}
get a instance of TCImageLoader and call display method appropriately.
i wish to display my data and image which download from an URL but after i download the image from URL, the order of the image go wrong. I displayed my data and images using card view and recycle view, but the first image in first card go to second, while the second image at third card and the third one will missing and the first one will empty. Anyone can help me on this?
Below is my code. Tq
SimpleCardViewAdapter.java
public class SimpleCardViewAdapter extends RecyclerView.Adapter<SimpleCardViewAdapter.ViewHolder> {
private List<CardViewData> mDataset;
Bitmap downloadedBitmap;
ImageView row_image;
public SimpleCardViewAdapter(List<CardViewData> dataset) {
mDataset = dataset;
}
#Override
public ViewHolder onCreateViewHolder(final ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row_layout, viewGroup, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final ViewHolder viewHolder, int i) {
final CardViewData cardViewData = mDataset.get(i);
viewHolder.mTitle.setText(cardViewData.getTitle());
viewHolder.mDescription.setText(cardViewData.getDescription());
String var = cardViewData.getImage();
new Thread(new getImageTask(var)).start();
viewHolder.mImage.setImageBitmap(downloadedBitmap);
viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Title: " + cardViewData.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
class getImageTask implements Runnable {
String imageUrl;
getImageTask(String imgUrl){
imageUrl = imgUrl;
}
#Override
public void run() {
try {
URL url = new URL(imageUrl);
downloadedBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message msg = new Message();
Bundle b = new Bundle();
b.putString("mfeApi", "1");
msg.setData(b);
handlerGroupedProductsImage.sendMessage(msg);
}
}
Handler handlerGroupedProductsImage = new Handler() {
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String done = b.getString("mfeApi");
};
};
#Override
public int getItemCount() {
return mDataset == null ? 0 : mDataset.size();
}
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public TextView mDescription;
public ImageView mImage;
public ViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.row_title);
mDescription = (TextView) itemView.findViewById(R.id.row_description);
mImage = (ImageView) itemView.findViewById(R.id.row_image);
}
}
Activity.java
private void getData() {
try {
final String toSend = "http://www.test.com.my/test/api/kipcard_helpAPI.php";
new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
String receivedString = null;
try {
url = new URL(toSend);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
InputStream in = new BufferedInputStream(conn.getInputStream());
receivedString = IOUtils.toString(in, "UTF-8");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message msg = new Message();
Bundle b = new Bundle();
b.putString("mfeApi", receivedString);
msg.setData(b);
hGet.sendMessage(msg);
}
}).start();
} catch (Exception e) {
e.printStackTrace();
}
}
Handler hGet = new Handler() {
public void handleMessage(Message msg) {
Bundle b = msg.getData();
String s = b.getString("mfeApi");
items = s.split("\\|\\|");
size = items.length;
List <CardViewData> list = new ArrayList<CardViewData>();
for(int i = 0 ; i <= size-3 ; i+=3){
Log.d("here",items[i] +"" );
//new Thread(new getImageTask(imahr)).start();
list.add(new CardViewData(items[i+2], items[i+3], items[i+1]));
}
mAdapter = new SimpleCardViewAdapter(list);
mRecyclerView.setAdapter(mAdapter);
};
};
The problem is here:
new Thread(new getImageTask(var)).start();
viewHolder.mImage.setImageBitmap(downloadedBitmap);
As the thread do it's job parallel not synchronously downloadedBitmap can hold another's thread "old" result.
Instead of
new Thread(new getImageTask(var)).start();
viewHolder.mImage.setImageBitmap(downloadedBitmap);
Try using
final int position = i;
viewHolder.position = i;
new AsyncTask<Object, Void, Bitmap>() {
private AlbumViewHolder v;
#Override
protected Bitmap doInBackground( Object[] params ) {
v = (AlbumViewHolder) params[ 0 ];
// download here your image
return b;
}
#Override
protected void onPostExecute( Bitmap result ) {
super.onPostExecute( result );
if ( v.position == position && result != null ) {
// If this item hasn't been recycled already, hide the
// progress and set and show the image
v.mImageView.setImageBitmap( result );
v.mImageView.setVisibility( View.VISIBLE );
v.mProgressBar.setVisibility( View.GONE );
}
}
}.execute( viewHolder );
and in ViewHolder :
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView mTitle;
public TextView mDescription;
public ImageView mImage;
public int position;
public ViewHolder(View itemView) {
super(itemView);
mTitle = (TextView) itemView.findViewById(R.id.row_title);
mDescription = (TextView) itemView.findViewById(R.id.row_description);
mImage = (ImageView) itemView.findViewById(R.id.row_image);
}
}
And one more thing - your ViewHolder should have position parameter. And think about caching.
Try this:
add Context to your constructor
public SimpleCardViewAdapter(List<CardViewData> dataset, Activity activity){
this.mActivity = activity;
}
change in onBindViewHolder method:
new Thread(new getImageTask(var, viewHolder.mImage)).start();
and change your task like this:
class getImageTask implements Runnable {
String imageUrl;
ImageView imageView
getImageTask(String imgUrl, ImageView imageView){
imageUrl = imgUrl;
this.imageView = imageView;
}
#Override
public void run() {
try {
URL url = new URL(imageUrl);
//change this line also
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//set you downloaded image now...
//new change ....
mActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
//Your code to run in GUI thread here
if(bitmap != null)
imageView.setImageBitmap(bitmap);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Message msg = new Message();
Bundle b = new Bundle();
b.putString("mfeApi", "1");
msg.setData(b);
handlerGroupedProductsImage.sendMessage(msg);
}
}
***but it will not cache bitmap, every time you scroll your recycler inside app it will download it again and again.
i am trying lazy loading with LruCache as shown here : Example using Androids lrucache.
public class TCImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
Context cv;
public TCImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int maxKb = am.getMemoryClass() * 1024;
int limitKb = maxKb / 8; // 1/8th of total ram
cache = new TCLruCache(limitKb);
cv = context;
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
#Override
protected int sizeOf(String key, Bitmap value) {
int kbOfBitmap = value.getByteCount() / 1024;
return kbOfBitmap;
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
//bmp = BitmapFactory.decodeResource(cv.getResources(), url);
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
//super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
}
#Override
public void onLowMemory() {
}
#Override
public void onTrimMemory(int level) {
/* if (level >= TRIM_MEMORY_MODERATE) {
cache.evictAll();
}
else if (level >= TRIM_MEMORY_BACKGROUND) {
cache.trimToSize(cache.size() / 2);
}*/
}
}
the TCimageloader is as shown in above code. my getview is as shown below :
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(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
// imageView.setPadding(10,10,10,10);
} else {
imageView = (ImageView) convertView;
}
imagloader = new TCImageLoader(mContext);
imagloader.display(mThumbIds[position], imageView, R.drawable.ic_launcher);
//Picasso.with(mContext).load(mThumbIds[position]).placeholder(R.drawable.ic_launcher).into(imageView);
imageView.setImageResource(R.drawable.ic_launcher);
return imageView;
}
but the problem i am facing is that when I scroll fast the getView has already been called and display method is already called. so the image views keep changing until the last called is implemented.
i am trying to make a custom gallery and this will also help me in downloading images from urls. I will have to use same method . will just have to change the file address to url address
I'm developing an Android app but I'm a newbie and I got stuck...
My ListView single element has an ImageView and some TextViews, but sometimes (when I scroll the page and there are more than 7-8 elements) it doesn't display the right image in the right row.
I'm using a custom Image Loader to manage the downloaded images.
Here's my Adapter:
public class AddVideogameActivityAdapter extends BaseAdapter {
private ArrayList<Videogame> videogames;
private Typeface typefaceMedium;
private Typeface typefaceLight;
private ImageLoader loader;
private LayoutInflater mInflater;
public AddVideogameActivityAdapter(Context context, ArrayList<Videogame> results) {
videogames = results;
mInflater = LayoutInflater.from(context);
typefaceMedium = Typeface.createFromAsset(context.getAssets(), "Roboto-Medium.ttf");
typefaceLight = Typeface.createFromAsset(context.getAssets(), "Roboto-Light.ttf");
loader = new ImageLoader(context);
}
public int getCount() {
return videogames.size();
}
public Object getItem(int position) {
return videogames.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_element,null);
holder = new ViewHolder();
holder.imgView = (ImageView) convertView.findViewById(R.id.thumbView);
holder.txtName = (TextView) convertView.findViewById(R.id.elementView);
holder.txtPlatform = (TextView) convertView.findViewById(R.id.elementView2);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
try {
Videogame vgame = (Videogame) videogames.get(position);
holder.txtName.setText(vgame.getTitle());
holder.txtName.setTypeface(typefaceMedium);
holder.txtPlatform.setText(videogames.get(position).getPlatform());
holder.txtPlatform.setTypeface(typefaceLight);
holder.imgUrl = videogames.get(position).getImage();
loader.display(holder.imgUrl, holder.imgView, R.drawable.youtube_icon);
}
catch (Exception e) {
e.printStackTrace();
Log.e(com.example.ludos2_0.MainActivity.TAG,
"Exception: " + e.getLocalizedMessage());
}
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtPlatform;
public String imgUrl;
ImageView imgView;
}
}
Sorry for my english and thank you for your help!
EDIT:
Here's also the Loader:
public class ImageLoader implements ComponentCallbacks2 {
private TCLruCache cache;
public ImageLoader(Context context) {
ActivityManager am = (ActivityManager) context.getSystemService(
Context.ACTIVITY_SERVICE);
int memoryClass = am.getMemoryClass() * 1024 * 1024;
cache = new TCLruCache(memoryClass);
}
public void display(String url, ImageView imageview, int defaultresource) {
imageview.setImageResource(defaultresource);
Bitmap image = cache.get(url);
if (image != null) {
imageview.setImageBitmap(image);
}
else {
new SetImageTask(imageview).execute(url);
}
}
private class TCLruCache extends LruCache<String, Bitmap> {
public TCLruCache(int maxSize) {
super(maxSize);
}
}
private class SetImageTask extends AsyncTask<String, Void, Integer> {
private ImageView imageview;
private Bitmap bmp;
public SetImageTask(ImageView imageview) {
this.imageview = imageview;
}
#Override
protected Integer doInBackground(String... params) {
String url = params[0];
try {
bmp = getBitmapFromURL(url);
if (bmp != null) {
cache.put(url, bmp);
}
else {
return 0;
}
} catch (Exception e) {
e.printStackTrace();
return 0;
}
return 1;
}
#Override
protected void onPostExecute(Integer result) {
if (result == 1) {
imageview.setImageBitmap(bmp);
}
super.onPostExecute(result);
}
private Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection
= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
}
RE-EDIT
Activity code:
public class AddVideogameActivity extends ListActivity {
private TextView searchField = null;
private final Handler handler = new Handler();
private ArrayList<Videogame> videogamesList = null;
private static AddVideogameActivity mContext = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_book);
mContext = this;
searchField = (TextView) findViewById(R.id.searchField);
searchField.setMaxLines(1);
searchField.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
searchField.setHint("");
}
});
// Setup the list view and its listener
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.d(MainActivity.TAG,
"AddBookActivity ---> AddButton:onClick()");
// Sets typefaces for TextView
String videogameId = videogamesList.get(position).getId();
String videogameName = videogamesList.get(position).getTitle();
String thumbnail = videogamesList.get(position).getThumbnail();
String description = videogamesList.get(position)
.getDescription();
String image = videogamesList.get(position).getImage();
String platform = videogamesList.get(position).getPlatform();
if (videogameName != null && videogameName.length() > 0
&& thumbnail != null && thumbnail.length() > 0
&& description != null && description.length() > 0
&& image != null && image.length() > 0
&& platform != null && platform.length() > 0) {
if (ListsManager.getInstance().addVideogame(
new Videogame(videogameId, videogameName,
thumbnail, image, description, platform)) == 0) {
Log.d(MainActivity.TAG,
"AddBookActivity --> Videogame:[" + videogameId
+ "#" + videogameName + "]");
Toast toast = Toast.makeText(mContext, "["
+ videogameName + "] Saved !",
Toast.LENGTH_LONG);
toast.show();
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Videogame already in the list ! ");
Toast toast = Toast.makeText(mContext,
"Error! Videogame already in the list!",
Toast.LENGTH_LONG);
toast.show();
}
} else {
Log.e(MainActivity.TAG,
"AddBookActivity --> Error ! Invalid Videogame Name or Thumbnail or Id or Deck");
Toast toast = Toast
.makeText(
mContext,
"Error ! Invalid Videogame Name or Thumbnail or Id or Deck",
Toast.LENGTH_LONG);
toast.show();
}
Intent newIntent = new Intent(getApplicationContext(),
MainActivity.class);
startActivity(newIntent);
}
});
// Setup the search button and its listener
Button searchButton = (Button) findViewById(R.id.searchButton);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(com.example.ludos2_0.MainActivity.TAG, "Search Game ...");
String searchInputString = searchField.getText().toString();
if (searchInputString != null && searchInputString.length() > 0) {
try {
String requestURL = ("http://www.giantbomb.com/api/search/?api_key=fcf60d6d67b98b0d17b3905d1a90b3fd31ed1e8e&format=json&query="
+ Uri.encode(searchInputString) + "&resources=game");
// String requestURL =
// String.format("https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&category=Music&orderby=relevance&q=%s",Uri.encode(searchInputString));
Log.d(com.example.ludos2_0.MainActivity.TAG, requestURL);
DownloadGiantBombJSONData giantbombAsyncTask = new DownloadGiantBombJSONData();
giantbombAsyncTask.execute(new String[] { requestURL });
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
if (videogamesList == null)
videogamesList = new ArrayList<Videogame>();
else
updateVideogamesListView(videogamesList);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_book, menu);
return true;
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
public void updateVideogamesListView(ArrayList<Videogame> values) {
AddVideogameActivityAdapter adapter = new AddVideogameActivityAdapter(this, values);
setListAdapter(adapter);
}
#Override
protected void onDestroy() {
super.onDestroy();
}
}
The other classes involved in building the ListView are the REST classes and the AsyncTask class that downloads and parses the JSon files.
What does your ListView look like, does it look like this:
<ListView android:id="#id/android:list"
android:layout_weight="1"
android:layout_width="match_parent"
android:layout_height="0dip" ></ListView>
Especially the id of the ListView. Check your layout file, probably the bug exists there.
I'm loading images in gridviev asynchronusly.But my gridview displaying only a single image in the last cell of gridview.My adapter class and asynchronus class is given below, thanks.
Adapter class:
class OrderAdapter extends ArrayAdapter<String>
{
LayoutInflater inflater;
String name3[];
public OrderAdapter(Context context,int resource,LayoutInflater inflater,String name2[])
{
super(context, resource,R.id.img,name2);
this.inflater=inflater;
this.name3=name2;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View row=inflater.inflate(R.layout.row,parent,false);
final ImageView img=(ImageView)row.findViewById(R.id.img);
String imgurl=name3[position];
Log.e("urlchandan",name3[position]);
AsyncImageLoaderv asyncImageLoaderv=new AsyncImageLoaderv();
Bitmap cachedImage = asyncImageLoaderv.loadDrawable(imgurl, new AsyncImageLoaderv.ImageCallback()
{
public void imageLoaded(Bitmap imageDrawable, String imageUrl) {
img.setImageBitmap(imageDrawable);
}
});
img.setImageBitmap(cachedImage);
return row;
}
}
Asynchronous class
public class AsyncImageLoaderv {
private HashMap<String, SoftReference<Bitmap>> imageCache;
public AsyncImageLoaderv() {
imageCache = new HashMap<String, SoftReference<Bitmap>>();
}
public Bitmap loadDrawable(final String imageUrl, final ImageCallback imageCallback) {
if (imageCache.containsKey(imageUrl)) {
SoftReference<Bitmap> softReference = imageCache.get(imageUrl);
Bitmap drawable = softReference.get();
if (drawable != null) {
return drawable;
}
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message message) {
imageCallback.imageLoaded((Bitmap) message.obj, imageUrl);
}
};
new Thread() {
#Override
public void run() {
try{
Log.d("ur",imageUrl);
Bitmap drawable = loadImageFromUrl(imageUrl);
imageCache.put(imageUrl, new SoftReference<Bitmap>(drawable));
Message message = handler.obtainMessage(0, drawable);
handler.sendMessage(message);
}catch(Exception e){Log.e("thread stellent",e.toString());}
}
}.start();
return null;
}
public static Bitmap loadImageFromUrl(String url) {
InputStream inputStream;Bitmap b;
try {
inputStream = (InputStream) new URL(url).getContent();
BitmapFactory.Options bpo= new BitmapFactory.Options();
bpo.inSampleSize=2;
b=BitmapFactory.decodeStream(new PatchInputStream(inputStream), null,bpo );
return b;
} catch (IOException e) {
throw new RuntimeException(e);
}
//return null;
}
public interface ImageCallback {
public void imageLoaded(Bitmap imageBitmap, String imageUrl);
}
}
You can't do it the way you're trying. You need to have your asynchronous loader store the resulting image in some data structure your adapter can access by position (e.g. a list, a hashmap, whatever). Your getView() should then simply pull the image from the correct position. Your asynchronous loader will populate the data structure and perform a notifyDataSetChanged() to have the list redraw itself with the newly loaded image.
I got the solution by making the ImageView img in adatper inflater as final because it avoids
the images to display at a single cell in gridview . And my images was of big size and got the error decoder return false and this error is solved by taking another class
--
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
public class PatchInputStream extends FilterInputStream {
public PatchInputStream(InputStream in) {
super(in);
}
public long skip(long n) throws IOException {
long m = 0L;
while (m < n) {
long _m = in.skip(n-m);
if (_m == 0L) break;
m += _m;
}
return m;
}
}
this class is used in AsyncImageLoaderv given above .
b=BitmapFactory.decodeStream(new PatchInputStream(inputStream), null,bpo );