How An use of all images from the parse - android

I need to pull all the image from parse.
this is the error in the logCat:
Attempt to invoke interface method 'java.lang.Object java.util.List.get(int)' on a null object reference
The error is here:
String ObjectId = ParseObjects.get(position).getObjectId();
This is my code:
public void PullImage(final ImageView image,int position){
progressDialog = ProgressDialog.show(mContext, "", "Downloading Image...", true);
String ObjectId = ParseObjects.get(position).getObjectId();
query.getInBackground(ObjectId, new GetCallback < ParseObject > () {
public void done (ParseObject object, ParseException e){
if (object != null) {
ParseFile file = (ParseFile) object.get("ImageFile");
file.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// surface.addImage(bitmap);
// float Xplace = targetImageforpull.getX();
// float Yplace = targetImageforpull.getY();
image.setImageBitmap(bitmap);
//use this bitmap as you want
progressDialog.dismiss();
} else {
// something went wrong
}
}
});
} else {
Toast.makeText(mContext, "Exception", Toast.LENGTH_SHORT).show();
}
}
});
}
I know that my problem is here:
public void SetParse(){
query = new ParseQuery<ParseObject>("User");
// query.whereEqualTo("Column", bitmap);
size = 0;
try {
size = query.count();
} catch (ParseException e) {
e.printStackTrace();
}
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
ParseObjects = objects;
// The query was successful.
} else {
// Something went wrong.
}
}
});
}
all code:
public class CustomGrid extends BaseAdapter {
private Context mContext;
private Bitmap btimaprecieve;
List<ParseObject> ParseObjects;
ParseQuery<ParseObject> query;
ProgressDialog progressDialog;
int size;
public CustomGrid(Context c) {
mContext = c;
SetParse();
}
//---returns the number of images---
public int getCount() {
return size;
}
//---returns the ID of an item---
public Object getItem(int position) {
return imageId[position];
}
public long getItemId(int position) {
return position;
}
//---returns an ImageView view---
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(120, 120));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(25, 25, 25, 25);
} else {
imageView = (ImageView) convertView;
}
PullImage(imageView,position);
// imageView.setImageResource(imageId[position]);
return imageView;
}
public void SetParse(){
query = new ParseQuery<ParseObject>("User");
// query.whereEqualTo("Column", bitmap);
size = 0;
try {
size = query.count();
} catch (ParseException e) {
e.printStackTrace();
}
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
// ParseObjects = objects;
ParseObjects = new ArrayList<ParseObject>(objects);
if(ParseObjects == null){
Log.d("ParseObjects is null ", "ParseObjects is null");
}
if(objects == null){
Log.d("objects is null ", "objects is null");
}
// The query was successful.
} else {
// Something went wrong.
}
}
});
}
public void PullImage(final ImageView image,int position){
progressDialog = ProgressDialog.show(mContext, "", "Downloading Image...", true);
String ObjectId = ParseObjects.get(position).getObjectId();
query.getInBackground(ObjectId, new GetCallback < ParseObject > () {
public void done (ParseObject object, ParseException e){
if (object != null) {
ParseFile file = (ParseFile) object.get("ImageFile");
file.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
// surface.addImage(bitmap);
// float Xplace = targetImageforpull.getX();
// float Yplace = targetImageforpull.getY();
image.setImageBitmap(bitmap);
//use this bitmap as you want
progressDialog.dismiss();
} else {
// something went wrong
}
}
});
} else {
Toast.makeText(mContext, "Exception", Toast.LENGTH_SHORT).show();
}
}
});
}
private Integer [] imageId = {
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
R.drawable.like_button,
};
public Bitmap add(Bitmap bitmap_recieve) {
return btimaprecieve;
}
}

i'm use glide(or any other lib(volley, picasa) for loading ing by URL)
userQuery.getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject parseObject, ParseException e) {
if((ParseFile) parseObject.get("photo")!= null){
Glide.with(context).load(((ParseFile) parseObject.get("photo")).getUrl()).asBitmap().dontAnimate().centerCrop().transform(new CircleTransform(context))
.diskCacheStrategy(DiskCacheStrategy.SOURCE).into(hd.logo);
}
}
});
If you need bitmap u can fat it after loading from your img view.
be carefully, if your callback returns ParseArray, u must get object with your picture by position like this ParseObjects.get(position).getObjectId(); But if you have ParseObject you must write ParseObjects.getObjectId();(without get(position)). Check your callback.

Related

Parse.com RecyclerView dont show Image

I have a RecyclerView with Parse.com to show a Class and the image is not loading.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
recipes = new ArrayList<Recipe>();
connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
mInternet = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
//Parse.enableLocalDatastore(getApplicationContext());
// Enable Local Datastore.
if(mWifi.isConnected() && count == 0) {
Log.d("Invoke order","first if");
//Parse.initialize(getApplicationContext(), "HX6n9WMdhKg5BPhC7d22IKHV34jyTst5OHQxtxUD", "U9DotgCbByVP4eZ9oFae61w3Hnno0xFUgefYJOq4");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Collection");
progressDialog = ProgressDialog.show(ListActivity.this, "",
"Update", true);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> recipesList, ParseException e) {
if (e == null) {
ParseObject.pinAllInBackground(recipesList);
Log.d("score", "Retrieved " + recipesList.size() + " recipes");
for ( ParseObject obj : recipesList) {
final ParseObject object = obj;
ParseFile image = (ParseFile) obj.get("File");
image.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
Log.d("picture",Integer.toString(data.length));
if (e == null) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ImageView image4 = (ImageView) findViewById(R.id.alarmPic);
// Set the Bitmap into the
// ImageView
image4.setImageBitmap(bmp);
initializeData(object, bmp);
Log.d("mytag", "prblem2");
} else {
Log.d("mytag", "coldnt load picture");
}
}
});
initializeData(obj, bmp);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
initializeAdapter();
progressDialog.dismiss();
}
});
count++;
}if(!mWifi.isConnected() && count != 0) {//error on image
Log.d("Invoke order","second if");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Collection");
query.fromLocalDatastore();
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> list, ParseException e) {
if(e == null){
Log.d("score", "Retrieved " + list.size() + " recipes");
for(ParseObject obj : list){
final ParseObject object = obj;
ParseFile image = (ParseFile)obj.get("File");
image.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
Log.d("picture",Integer.toString(data.length));
if (e == null) {
bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
ImageView image22 = (ImageView) findViewById(R.id.alarmPic);
// Set the Bitmap into the
// ImageView
image22.setImageBitmap(bmp);
initializeData(object, bmp);
Log.d("mytag", "prblem1");
} else {
Log.d("mytag", "coldnt load picture");
}
}
});
initializeData(obj, bmp);
}
}else {
Log.d("score", "Error: " + e.getMessage());
}
initializeAdapter();
}
});
}
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView)findViewById(R.id.recyclerView);
manager = new LinearLayoutManager(getApplicationContext());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(manager);
//added to avoid no adapter set exception
//recipes = new ArrayList<>();
RVAdapter adapter = new RVAdapter(recipes);
recyclerView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
private void initializeAdapter(){
RVAdapter adapter = new RVAdapter(recipes);
recyclerView.setAdapter(adapter);
}
private void initializeData(ParseObject obj,Bitmap bmp){
recipes.add(new Recipe(obj.getString("Description"), obj.getString("shortDescription"), obj.getString("Name"), bmp));
Log.d("score", Integer.toString(recipes.size()));
}
}
You could use an AsynkTask
class getBitmapFromURL extends AsyncTask<String, Void, Bitmap> {
ParseFile img;
public getBitmapFromURL(ParseFile img) {
this.img = img;
}
protected Bitmap doInBackground(String... urls) {
try {
URL url = new URL(img.getUrl());
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(input);
} catch (IOException e) {
}
return null;
}
protected void onPostExecute(final Bitmap bitmap) {
if (bitmap != null) {
image22.setImageBitmap(bitmap);
}
}
}
and use it like this
ParseFile image = (ParseFile)obj.get("File");
new getBitmapFromURL(image).execute("");
Do this inside the onBindViewHolder method of the RecyclerView.Adapter http://developer.android.com/training/material/lists-cards.html
#Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
viewHolder.image22.setImageBitmap(bitmap);
}
Just get the files url and put it into Picasso.
String url = parseFile.getUrl();

Adapter not showing data obtained from Parse.com through AsyncTask

I am trying to obtain some data from Parse.com through an AsyncTaskRunner. ANd then I intend to show them in a ListView. My custom adapter code is attached below :
public class ParseObjectAdapter extends BaseAdapter {
Context mContext;
LayoutInflater mInflater;
List<ParseObject> parseArray;
DBShoppingHelper mydb2;
public ParseObjectAdapter(Context context, LayoutInflater inflater) {
mContext = context;
mInflater = inflater;
parseArray = new ArrayList<>();
}
#Override
public int getCount() {
try {
return parseArray.size();
}
catch (Exception e){
return 0;
}
}
#Override
public ParseObject getItem(int position) { return parseArray.get(position); }
#Override
public long getItemId(int position) {
return position;
}
public String getObjectId(int position){
return getItem(position).getObjectId();
}
public void sortByExpiry()
{
Comparator<ParseObject> comparator = new Comparator<ParseObject>() {
#Override
public int compare(ParseObject lhs, ParseObject rhs) {
return ((Integer) lhs.getInt("expiresIn")).compareTo(rhs.getInt("expiresIn"));
}
};
Collections.sort(parseArray, comparator);
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
ViewHolder holder;
// Inflate the custom row layout from your XML.
convertView = mInflater.inflate(R.layout.list_item, null);
// create a new "Holder" with subviews
holder = new ViewHolder();
holder.itemNameView = (TextView) convertView.findViewById(R.id.item_name);
holder.itemExpiryView = (TextView) convertView.findViewById(R.id.item_expiry);
// Taking care of the buttons
holder.editButton = (Button) convertView.findViewById(R.id.button_edit);
holder.deleteButton = (Button) convertView.findViewById(R.id.button_delete);
holder.shoppingListButton = (Button) convertView.findViewById(R.id.button_shopping);
// hang onto this holder for future recycling
convertView.setTag(holder);
int expiry = getItem(position).getInt("expiresIn");
if (expiry <= 0) {
holder.itemExpiryView.setTextColor(Color.rgb(255,80,54));
}
// Set listener on the buttons
holder.editButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(mContext, "Edit Button CLicked", Toast.LENGTH_SHORT).show();
ParseObject p = getItem(position);
Intent goToAddItem = new Intent(mContext,ItemAddPage.class);
goToAddItem.putExtra("catg_passed", p.getString("category"));
goToAddItem.putExtra("update_flag", "YES");
goToAddItem.putExtra("name passed", p.getString("itemName"));
goToAddItem.putExtra("expires_in_passed", p.getString("expiresIn"));
goToAddItem.putExtra("price_passed", p.getString("itemPrice"));
mContext.startActivity(goToAddItem);
}
});
holder.deleteButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ParseObject p = getItem(position);
String android_id = Settings.Secure.getString(mContext.getContentResolver(), Settings.Secure.ANDROID_ID);
ParseQuery itemToBeDeleted = new ParseQuery("Items");
itemToBeDeleted.whereEqualTo("ACL", p.getACL());
itemToBeDeleted.whereEqualTo("objectId", p.getObjectId());
final Date deletionDate = new Date();
itemToBeDeleted.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, com.parse.ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
if (Items.size() == 1) {
ParseObject itemToDelete = Items.get(0);
itemToDelete.put("deleted", true);
itemToDelete.put("deletedOn", deletionDate);
itemToDelete.saveEventually();
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
parseArray.remove(p);
sortByExpiry();
notifyDataSetChanged();
Toast.makeText(mContext, "Item deleted", Toast.LENGTH_SHORT).show();
}
});
holder.shoppingListButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
ParseObject p = getItem(position);
String add_to_list = p.getString("itemName");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
String add_date = sdf.format(new Date());
System.out.println(add_date);
mydb2.insertItem(add_to_list, add_date);
Toast.makeText(mContext, "Item added to shopping list", Toast.LENGTH_SHORT).show();
}
});
ParseObject p = getItem(position);
String name2 = p.getString("itemName");
Integer ex = p.getInt("expiresIn");
String days_s ="";
if (ex == 0) {
days_s = "Expires today" ;
}
else if (ex == -1) {
days_s = "Expired yesterday";
}
else if (ex < 0) {
days_s = "Expired " + Math.abs(ex) + " days ago";
}
else if (ex == 1) {
days_s = "Expires tomorrow";
}
else {
days_s = "Expires in " + ex + " days";
}
holder.itemNameView.setText(name2);
holder.itemExpiryView.setText(days_s);
return convertView;
}
public void onClick(View v)
{
Intent viewItem = new Intent(v.getContext(), ItemAddPage.class);
v.getContext().startActivity(viewItem);
}
private static class ViewHolder {
public TextView itemNameView;
public TextView itemExpiryView;
public Button editButton;
public Button deleteButton;
public Button shoppingListButton;
}
public void updateData(List<ParseObject> arrayPassed) {
// update the adapter's data set
parseArray = arrayPassed;
notifyDataSetChanged();
}
}
This is the method from which I am calling it..
public class WelcomeParse extends Activity {
ListView currentListView;
List<ParseObject> currentList;
ParseObjectAdapter itemAdder;
String catg;
DBShoppingHelper mydb2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.left_in, R.anim.right_out);
setTheme(android.R.style.Theme_Holo_Light_DarkActionBar);
setContentView(R.layout.activity_main);
itemAdder = new ParseObjectAdapter(this, getLayoutInflater());
mydb2 = new DBShoppingHelper(this);
AsyncTaskAllItems runner = new AsyncTaskAllItems();
runner.execute();
// itemAdder.notifyDataSetChanged();
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
public class AsyncTaskAllItems extends AsyncTask<String, String, String> {
private String resp;
private Integer numItems = 0;
#Override
protected String doInBackground(String... params) {
try {
ParseQuery itemsAll = new ParseQuery("Items");
itemsAll.whereEqualTo("owner", ParseUser.getCurrentUser().getUsername());
// itemsByCategory.whereEqualTo("category", catg);
itemsAll.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> Items, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + Items.size() + " scores");
Log.d("owner", ParseUser.getCurrentUser().getUsername());
// HERE SIZE is 0 then 'No Data Found!'
numItems = Items.size();
if (numItems > 0) {
currentList = Items;
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
resp = "Done";
}
// catch (InterruptedException e) {
// e.printStackTrace();
// resp = e.getMessage();
// }
catch (Exception e) {
e.printStackTrace();
resp = e.getMessage();
}
return resp;
}
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(String... text) {
}
}
}
I do not get any error and the log correctly shows the number of items that should be retrieved. But the view does not get updated with the relevant data.
COuld anyone please show me where I am wrong? Anything else you need, just let me know. Much appreciated.
Try after replacing
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
currentListView.setAdapter(itemAdder);
// onWindowFocusChanged(true);
}
With
#Override
protected void onPostExecute(String result) {
currentListView = (ListView) findViewById(R.id.all_list);
currentListView.setAdapter(itemAdder);
itemAdder.updateData(currentList);
if (numItems > 0) {
itemAdder.sortByExpiry();
}
}

Retrieving image files from parse - android

I'm trying to retrieve images that I have upload from my app:
intent = getIntent();
String id = intent.getStringExtra("id");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Items");
query.getInBackground(id, new GetCallback<ParseObject>()
{
#Override
public void done(ParseObject object, ParseException e)
{
if (e == null)
{
setTitle(object.getString("name"));
textPlatform.setText(object.getString("platform"));
textPrice.setText(String.valueOf(object.getDouble("price")));
textDelivery.setText(String.valueOf(object.getDouble("delivery")));
textLocation.setText(object.getString("location"));
textCondition.setText(object.getString("condition"));
textSeller.setText(object.getString("seller"));
ParseFile applicantResume = (ParseFile) object.get("image");
applicantResume.getDataInBackground(new GetDataCallback()
{
public void done(byte[] data, ParseException e)
{
if (e == null)
{
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);
imgItem.setImageBitmap(bmp);
}
else
{
e.printStackTrace();
}
}
});
} else
{
e.printStackTrace();
}
}
});
I can successfully retrieve the other items just not the file (which I know exists and is under the column "image").
Thank You in advanced
This is how i am doing it:
I get the file from parse using getParseFile method:
ParseFile postImage = object.getParseFile(ParseConstants.PARSE_KEY_FILE);
String imageUrl = postImage.getUrl() ;//live url
Uri imageUri = Uri.parse(imageUrl);
and then I use Picasso to display the image:
Picasso.with(context).load(imageUri.toString()).into(mPostImage);
by this you can display the image....
ParseFile image = (ParseFile) userData.getParseFile("user_image");
//call the function
displayImage(image, image_expert);
//and here is the function
private void displayImage(ParseFile thumbnail, final ImageView img) {
if (thumbnail != null) {
thumbnail.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory.decodeByteArray(data, 0,
data.length);
if (bmp != null) {
Log.e("parse file ok", " null");
// img.setImageBitmap(Bitmap.createScaledBitmap(bmp,
// (display.getWidth() / 5),
// (display.getWidth() /50), false));
img.setImageBitmap(getRoundedCornerBitmap(bmp, 10));
// img.setPadding(10, 10, 0, 0);
}
} else {
Log.e("paser after downloade", " null");
}
}
});
} else {
Log.e("parse file", " null");
// img.setImageResource(R.drawable.ic_launcher);
img.setPadding(10, 10, 10, 10);
}
}

Android ListView wrong images

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.

loading images from SD card directory in GridView

I've created an app that allows the user to create a photo album(Folder) on External Storage. Now I am trying to retrieve the images from said directory and display them inside a GridView. I'm using an AsyncTask to iterate through the directory of files using listFiles() and then creating a bitmap once I grab each image, recycle it, and then use it again. My problem is that nothing is showing up in my GridView. I've set up a few Log breaks and LogCat shows me that the iteration does happen and the images are retrieved. This leads me to think that I made a mistake somewhere in my Adapter class that binds the bitmaps to the Grid, possibly in getView? Or maybe I'm wrong. Any help on what I'm doing wrong? I tried to comment the code as much as possible and I've left out the unecessary pieces. Thanks
public class AlbumGridView extends Activity implements OnItemClickListener {
private GridView sdcardImages;
private ImageAdapter imageAdapter;
private Display display;
private Bitmap bitmap;
private Bitmap b;
File[] imageList;
private static final String TAG = "AlbumGridView";
String path;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.album_view);
//display =
//((Object) getSystemService(Context.WINDOW_SERVICE))).getDefaultDisplay();
path = getIntent().getStringExtra("key");
Toast.makeText(this, path, Toast.LENGTH_SHORT).show();
setupViews();
setProgressBarIndeterminateVisibility(true);
loadImages();
}
protected void onDestroy() {
super.onDestroy();
final GridView grid = sdcardImages;
final int count = grid.getCount();
ImageView v = null;
for (int i = 0; i < count; i++) {
v = (ImageView) grid.getChildAt(i);
((BitmapDrawable) v.getDrawable()).setCallback(null);
}
}
// Set up the GridView
private void setupViews() {
sdcardImages = (GridView) findViewById(R.id.gvAlbumView);
// sdcardImages.setNumColumns(display.getWidth()/95);
sdcardImages.setClipToPadding(false);
sdcardImages.setOnItemClickListener(AlbumGridView.this);
imageAdapter = new ImageAdapter(getApplicationContext());
// imageAdapter.setImageList(path);
sdcardImages.setAdapter(imageAdapter);
}
private void addImage(LoadedImage... value) {
for (LoadedImage image : value) {
imageAdapter.addPhoto(image);
imageAdapter.notifyDataSetChanged();
}
}
// Save Bitmap images to a list and return that list
#Override
public Object onRetainNonConfigurationInstance() {
final GridView grid = sdcardImages;
final int count = grid.getChildCount();
final LoadedImage[] list = new LoadedImage[count];
for (int i = 0; i < count; i++) {
final ImageView v = (ImageView) grid.getChildAt(i);
list[i] = new LoadedImage(
((BitmapDrawable) v.getDrawable()).getBitmap());
}
return list;
}
private void loadImages() {
// TODO Auto-generated method stub
final Object data = getLastNonConfigurationInstance();
if (data == null) {
new LoadImagesFromSDCard().execute();
} else {
final LoadedImage[] photos = (LoadedImage[]) data;
if (photos.length == 0) {
new LoadImagesFromSDCard().execute();
}
for (LoadedImage photo : photos) {
addImage(photo);
}
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
}
/-------------------------------------------------------------------------------------/
//Adapter for the GridView
public class ImageAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();
private String path;
private Bitmap bitmap;
public ImageAdapter(Context context) {
mContext = context;
}
public void addPhoto(LoadedImage photo) {
photos.add(photo);
}
public int getCount() {
return photos.size();
}
public Object getItem(int position) {
return photos.get(position);
}
public long getItemId(int position) {
return position;
}
/*
* public File[] setImageList(String path) {
*
* //this.path = path; //this.imageList = imageList; //File imagesDir =
* new File(path); //imageList = imagesDir.listFiles();
*
* File imagesDir = new File(path); imageList = imagesDir.listFiles();
* for (File image : imageList) try { bitmap =
* BitmapFactory.decodeStream(image.toURL().openStream()); //use bitmap
* and recycle afterwards LoadedImage lm = new LoadedImage(bitmap);
* this.addPhoto(lm); bitmap.recycle();
*
* } catch (IOException e) { e.printStackTrace(); } return imageList;
*
* }
*/
public View getView(int position, View convertView, ViewGroup parent) {
final ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
} else {
imageView = (ImageView) convertView;
}
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setPadding(2, 2, 2, 2);
// imageView.setImageBitmap(photos.get(position).getBitmap());
try {
imageView
.setImageBitmap(BitmapFactory
.decodeStream(imageList[position].toURL()
.openStream()));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return imageView;
}
}
/*-------------------------------------------------------------------------*/
//AsyncTask to get the images
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... arg0) {
// Load images from SD card in Background
// Display each image on the screen
File imagesDir = new File(path);
imageList = imagesDir.listFiles();
for (File image : imageList)
try {
if (bitmap != null) {
bitmap.recycle();
bitmap = null;
}
bitmap = BitmapFactory.decodeStream(image.toURL()
.openStream());
Log.e(TAG, "Grabbed Image " + image.getName());
// use bitmap then recycle after
LoadedImage lm = new LoadedImage(bitmap);
// addImage(lm);
// imageAdapter.addPhoto(lm);
// imageAdapter.setImageList(path);
// imageAdapter.addPhoto(lm);
// imageAdapter.setImageList(path);
// bitmap.recycle();
// addImage(lm);
// imageAdapter.addPhoto(lm);
Log.e(TAG, "Added Image " + lm.toString());
// imageAdapter.setImageList(path);
addImage(lm);
// bitmap.recycle();
// bitmap.recycle();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
Here's the solution btw, sorry It took so long to I wasn't aware that others were waiting for the answer. Sorry. The relevant code is below.
This is AsyncTask that will query the device's MediaStore and retrieve all the photos. Note that this is retrieving the thumbnails and not the full size images, and more specifically it's the MICRO_KIND. There is also a Thumbnail.MINI_KIND as well.
/*----------------------------ASYNC TASK TO LOAD THE PHOTOS--------------------------------------------------------*/
public class LoadPhotos extends AsyncTask<Object, Object, Object> {
#Override
protected Object doInBackground(Object... params) {
try {
final String[] columns = { MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns,
null, null, orderBy);
int image_column_index = imagecursor
.getColumnIndex(MediaStore.Images.Media._ID);
AllPhotosActivity.count = imagecursor.getCount();
AllPhotosActivity.windows = new Bitmap[AllPhotosActivity.count];
for (int i = 0; i < AllPhotosActivity.count; i++) {
imagecursor.moveToPosition(i);
// i = index;
int id = imagecursor.getInt(image_column_index);
windows[i] = MediaStore.Images.Thumbnails.getThumbnail(
getApplicationContext().getContentResolver(), id,
MediaStore.Images.Thumbnails.MICRO_KIND, null);
}
imagecursor.close();
} catch (Exception e) {
e.printStackTrace();
Log.d("AllPhotosActivity",
"Error occured while fetching all photos on device.");
}
return null;
}
#Override
protected void onPostExecute(Object result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Handler mHandler = new Handler();
mHandler.post(new Runnable() {
public void run() {
pd.dismiss();
// imageAdapter.notifyDataSetChanged();
// sdcardImages.setAdapter(imageAdapter);
}
});
// pd.dismiss();
imagegrid.setAdapter(imageAdapter);
// pd.dismiss();
}
#Override
protected void onProgressUpdate(Object... values) {
// TODO Auto-generated method stub
super.onProgressUpdate(values);
}
}
Here's the adapter for the GridView that's going to bind your thumbnails to the gridview. My issue was simply in the getView method of my ImageAdapter, notice I'm setting my ImageView resources from different indexes of an array of Bitmaps I called windows.
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
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) {
ImageView i = (ImageView) convertView;
if (i != null) {
i.setImageBitmap(windows[position]);
} else {
i = new ImageView(mContext.getApplicationContext());
// i.setPadding(3, 3, 3, 3);
// i.setScaleType(ImageView.ScaleType.FIT_CENTER);
i.setAdjustViewBounds(true);
// i.setMaxHeight(200);
// i.setMaxWidth(200);
i.setPadding(3, 3, 3, 3);
i.setLayoutParams(new GridView.LayoutParams(92, 92));
i.setImageBitmap(windows[position]);
}
return i;
}
public int getCount() {
// TODO Auto-generated method stub
return count;
}
}

Categories

Resources