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();
Related
In the an async task in the doinbackground method I am getting a null return value for List of FeedItems.
Below is my asynctask class code. How do I return a List of FeedItems? I have added items to List<FeedItem> inside the for loop. How do I return the value of List from inside the for loop (or any other way)?
private class AsynFetchTask extends AsyncTask<Void, FeedItem, List<FeedItem>> {
private int count = 0;
#Override
protected List<FeedItem> doInBackground(Void... params) {
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("NewsAndUpdates");
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> list, ParseException e) {
if (e==null){
List<FeedItem> feedItems= new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final FeedItem item = new FeedItem();
item.setTitle(list.get(i).getString("Title"));
item.setDescription(list.get(i).getString("Description"));
item.setTime(list.get(i).getDate("createdAt"));
ParseFile file = list.get(i).getParseFile("File");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
item.setThumbnail(bmp);
publishProgress(item);
}else {
Toast.makeText(MainActivity.this, R.string.No_Internet,Toast.LENGTH_LONG).show();
}
}
});
if (item != null) {
feedItems.add(item);
}
}
}else {
Toast.makeText(MainActivity.this, R.string.No_Internet,Toast.LENGTH_LONG).show();
}
}
});
return null;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(List<FeedItem> feedItems) {
super.onPostExecute(feedItems);
adapter=new RecyclerViewAdapter(MainActivity.this,feedItems);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
Instead of returning null in your doInBackground, return feedItems like this:
private class AsynFetchTask extends AsyncTask<Void, FeedItem, List<FeedItem>> {
private int count = 0;
#Override
protected List<FeedItem> doInBackground(Void... params) {
ParseQuery<ParseObject> parseQuery = ParseQuery.getQuery("NewsAndUpdates");
parseQuery.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> list, ParseException e) {
if (e==null){
List<FeedItem> feedItems= new ArrayList<>();
for (int i = 0; i < list.size(); i++) {
final FeedItem item = new FeedItem();
item.setTitle(list.get(i).getString("Title"));
item.setDescription(list.get(i).getString("Description"));
item.setTime(list.get(i).getDate("createdAt"));
ParseFile file = list.get(i).getParseFile("File");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
if (e==null){
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
item.setThumbnail(bmp);
publishProgress(item);
}else {
Toast.makeText(MainActivity.this, R.string.No_Internet,Toast.LENGTH_LONG).show();
}
}
});
if (item != null) {
feedItems.add(item);
}
}
}else {
Toast.makeText(MainActivity.this, R.string.No_Internet,Toast.LENGTH_LONG).show();
}
}
});
return feedItems;
}
#Override
protected void onProgressUpdate(FeedItem... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(List<FeedItem> feedItems) {
super.onPostExecute(feedItems);
adapter=new RecyclerViewAdapter(MainActivity.this,feedItems);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
}
}
Hi I am populating a custom listview from parse user table. In that if the row doesn't containing a image I want to show one local image. For that I need to convert the drawable image into bitmap inside a fragment. I tried couple of methods. But none work and I don't know what is the error.
And my code is...
postImage = po.getParseFile("pic");
if (postImage != null && postImage.getUrl() != null && postImage.getUrl().length() > 0) {
postImage.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
people.setPic(bmp);
}
});
} else {
Bitmap icon = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.sanjay);
Log.d("ImageCoversion", BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.sanjay).toString());
people.setPic(icon);
}
I am getting error in getActivity().getResources() inside else block.
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.support.v4.app.FragmentActivity.getResources()' on a null object reference
And my full doInBackground code is
protected List<People> doInBackground(List<People>... params) {
try {
final ParseQuery<ParseUser> query = ParseUser.getQuery();
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> objects, ParseException e) {
ParseFile image = null;
if (e == null) {
peopleList.clear();
obj = objects;
for (ParseObject po : objects) {
//image = (ParseFile) po.get("pic");
ParseFile postImage;
final People people = new People();
people.setName(po.getString("username"));
people.setLastMessage(po.getString("email"));
people.setObjectId(po.getObjectId());
//people.setProfilePic(image.getUrl());
postImage = po.getParseFile("pic");
if (postImage != null && postImage.getUrl() != null && postImage.getUrl().length() > 0) {
postImage.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] bytes, ParseException e) {
Bitmap bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
people.setPic(bmp);
}
});
} else {
Bitmap icon = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.sanjay);
Log.d("ImageCoversion", icon.toString());
people.setPic(icon);
}
peopleList.add(people);
}
} else {
Log.d("*****Error", e.getMessage());
}
}
});
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return peopleList;
}
Try declaring Activity a = getActivity(); at the beginning of your code
In this else instead of :
Bitmap icon = BitmapFactory.decodeResource(getActivity().getResources(), R.drawable.sanjay);
use :
Bitmap icon = BitmapFactory.decodeResource(a.getResources(), R.drawable.sanjay);
Sometimes getActivity() returns null.
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.
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);
}
}
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.