I created a custom adapter for my GridView that will display an image of a book (View image) and its name (View text);
, I declared the list of names of the books in the string file:
[strings.xml]
<string-array name="bookLabels">
<item>android security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>Linux Firewalls</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>Linux Basicsfor Hackers</item>
<item>Black Hat Python</item>
</string-array>
So I want to do the same thing with the images,instead of declaring them in the code like that :
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
I declared the names of the images in a string array named "bookImages",
<string-array name="bookImages">
<item>#drawable/android_security</item>
<item>#drawable/penetration_testing</item>
<item>#drawable/red_team</item>
<item>#drawable/lf</item>
<item>#drawable/the_art_of_exploitation</item>
<item>#drawable/web_application_hacker </item>
<item>#drawable/lbh </item>
<item>#drawable/bhp </item>
</string-array>
and then I recovered the location of all the images declared in to "bookimagesfromstring"array :
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " +
Arrays.toString(bookImagesFromString))
this is the source code of [main activity]
public class main extends AppCompatActivity {
String[] labels;
String[ ] pages;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Resources res = getResources();
labels = res.getStringArray(R.array.bookLabels);
pages = res.getStringArray(R.array.web_pages);
GridView gridView = findViewById(R.id.gridView1);
BookGrid myAdapter = new BookGrid(getApplicationContext(), labels);
gridView.setAdapter(myAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(
getApplicationContext(),
((TextView) v.findViewById(R.id.gridtextView))
.getText(), Toast.LENGTH_SHORT).show();
// Intent webPageIntent = new Intent(getApplicationContext(),
DisplayWebPage.class);
// webPageIntent.putExtra("WEB_PAGE", pages[ position ] );
// startActivity( webPageIntent );
}
});
}
}
And the [ BookGrid Class ]
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromString;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
Resources resi = context.getResources();
bookImagesFromString = resi.getStringArray(R.array.bookImages);
System.out.println("bookImages Images test 1: " + Arrays.toString(bookImagesFromString));
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
//To Avoid ArrayIndexOutOfBoundsException
//boolean inBounds = (position >= 0) && (position <= imageName.length);
txtv.setText(imageName[position]);
//imgv.setImageResource(bookImagesFromString[position]);
imgv.setImageResource(bookImages[position]);
} else {
}
return convertView;
}
the result for the "bookImagesFromString" array was as follows :
([res/drawable-v24/android_security.png, res/drawable-v24/penetration_testing.png, res/drawable-v24/red_team.png, res/drawable/lf.jpg, res/drawable-v24/the_art_of_exploitation.png, res/drawable-v24/web_application_hacker.png, res/drawable/lbh.png, res/drawable-v24/bhp.png])
So the question is how to convert the "bookImagesFromString" array to an array that contains the ID of each image ? -And after using it in this code part:
imgv.setImageResource(bookImagesID[position]);
Thanks.
Try string array like this:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker</item>
<item>lbh</item>
<item>bhp</item>
</string-array>
and adapter like this:
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private Integer[] bookImages;
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
Resources resi = context.getResources();
String[] bookImagesFromString = resi.getStringArray(R.array.bookImages);
bookImages = new Integer[bookImagesFromString.length];
for (int i = 0; i < bookImagesFromString.length; i++) {
bookImages[i] = (resi.getIdentifier(bookImagesFromString[i], "drawable", context.getPackageName()));
}
}
#Override
public int getCount() {
return imageName.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
/*
Resources rest = context.getResources();
String[] labels = rest.getStringArray(R.array.bookLabels);
System.out.println("bookImagess Tex: " + Arrays.toString(labels));
*/
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
}
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
imgv.setImageResource(bookImages[position]);
return convertView;
}
}
Hope that helps!
for the name of the images as I_A_Mok said I took just:
<string-array name="bookImages">
<item>android_security</item>
<item>penetration_testing</item>
<item>red_team</item>
<item>lf</item>
<item>the_art_of_exploitation</item>
<item>web_application_hacker </item>
<item>lbh </item>
<item>bhp </item>
</string-array>
So I had two solutions :
A method with Context:
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
Or without Context (this approach is faster than the first Retrieving Resources in Android) :
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
and here is the complete code
package com.example.gridview.BookGridWebView;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.gridview.R;
import java.lang.reflect.Field;
import java.util.Arrays;
public class BookGrid extends BaseAdapter {
private Context context;
private LayoutInflater inflater;
private String[] imageName;
private String[] bookImagesFromStringArray;
private Integer[] bookImages =
{
R.drawable.android_security,
R.drawable.penetration_testing,
R.drawable.red_team,
R.drawable.lf,
R.drawable.the_art_of_exploitation,
R.drawable.web_application_hacker,
R.drawable.lbh,
R.drawable.bhp
};
public BookGrid(Context context, String[] imageName) {
this.context = context;
this.imageName = imageName;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return bookImages.length;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
bookImagesFromStringArray =
context.getResources().getStringArray(R.array.bookImageName);
//the table contains the IDs of each Image
Integer[] bookIDs = getIds(context,bookImagesFromStringArray);
if (convertView == null) {
convertView = inflater.inflate(R.layout.layout_grid_image, parent, false);
TextView txtv = convertView.findViewById(R.id.gridtextView);
ImageView imgv = convertView.findViewById(R.id.gridImageView);
txtv.setText(imageName[position]);
// imgv.setImageResource(bookImages[position]);
imgv.setImageResource(bookIDs[position]);
} else {
}
return convertView;
}
public static Integer[] getIds(Context context, String[] str) {
Integer[] bookID = new Integer[str.length];
for (int i = 0; i < str.length; i++) {
bookID[i] = context.getResources().getIdentifier(str[i], "drawable", context.getPackageName());
}
return bookID;
}
public static Integer[] getIds(String[] str) {
Integer[] bookID = new Integer[str.length];
try {
for (int i = 0; i < str.length; i++) {
Class res = R.drawable.class;
Field field = res.getField(str[i]);
int drawableId = field.getInt(null);
bookID[i] = drawableId;
}
} catch (Exception e) {
Log.e("MyTag", "Failure to get drawable id.", e);
e.printStackTrace();
}
return bookID;
}
}
Thanks.
Related
Here's my code, please help check my problem
My string list that has the same name with the images in res drawable:
<resources>
<string name="app_name">Intent Practice 1</string>
<string-array name="list_name">
<item>akiza</item>
<item>blueeyes</item>
<item>buster</item>
<item>cyberdragon</item>
<item>darklaw</item>
<item>darkmagician</item>
<item>darkmagiciangirl</item>
<item>darkpaladin</item>
<item>dragunity</item>
<item>exodia</item>
<item>gaia</item>
<item>galaxyeyes</item>
<item>harpies</item>
<item>hope</item>
<item>joey</item>
<item>junk</item>
<item>kaibaseto</item>
<item>marik</item>
<item>neos</item>
<item>redeyes</item>
<item>shaddoll</item>
<item>shiningflare</item>
<item>skulled</item>
<item>spear</item>
<item>stardust</item>
<item>tourguide</item>
<item>wingeddragon</item>
<item>yamiyugi</item>
<item>yudai</item>
<item>yugimuto</item>
<item>yuma</item>
<item>yusei</item>
<item>question</item>
</string-array>
</resources>
I can set an ImageView using
ImageView imgQuestion, imgAnswer, temp;
static ArrayList<String> arrayName;
public static ArrayList<HinhAnh> arrayImg;
String questionName;
int REQUEST_CODE_IMG = 2703;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgAnswer = findViewById(R.id.imgAnswer);
imgQuestion = findViewById(R.id.imgQuestion);
String[] mangTen = getResources().getStringArray(R.array.list_name);
arrayName = new ArrayList<>(Arrays.asList(mangTen));
arrayImg = new ArrayList<>();
Collections.shuffle(arrayName);
**int idImg = getResources().getIdentifier(arrayName.get(1), "drawable", getPackageName());
imgQuestion.setImageResource(idImg);**
But I dont know how to add the list of images in to the arrayImg, I used:
for (int position = 0; position < arrayName.size(); position++){
int id = getResources().getIdentifier(arrayName.get(position), "drawable", getPackageName());
arrayImg.add(new HinhAnh(arrayName.get(position) + "", id));
Toast.makeText(this, arrayImg.get(1).getTen() + "", Toast.LENGTH_SHORT).show();
}
I used Toast to check if I add successfully then the error showed out
Caused by: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.get(ArrayList.java:437)
at com.example.intentpractice.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
My class HinhAnh
public class HinhAnh {
private String Ten;
private int Hinh;
public HinhAnh(String ten, int hinh) {
Ten = ten;
Hinh = hinh;
}
public String getTen() {
return Ten;
}
public void setTen(String ten) {
Ten = ten;
}
public int getHinh() {
return Hinh;
}
public void setHinh(int hinh) {
Hinh = hinh;
}
}
They all lead to my adapter is null then I cannot fill my gridview at all. Please help!!
Edit:
I changed the line to get(position) then it worked. But it still showed error point to my adapter, here's my adapter:
public class ImageAdapter extends BaseAdapter {
private Context context;
private int layout;
private List<HinhAnh> imageList;
public ImageAdapter(Context context, int layout, List<HinhAnh> imageList) {
this.context = context;
this.layout = layout;
this.imageList = imageList;
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
private class ViewHolder{
ImageView imgHinh;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(layout, null);
holder.imgHinh = convertView.findViewById(R.id.imgItem);
convertView.setTag(holder);
}
else{
holder = (ViewHolder) convertView.getTag();
}
holder.imgHinh.setImageResource(imageList.get(position).getHinh());
return convertView;
}
}
and where I called it
adapter = new ImageAdapter(this, R.layout.imageline, MainActivity.arrayImg);
gridView.setAdapter(adapter);
The error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.GridView.setAdapter(android.widget.ListAdapter)' on a null object reference
at com.example.intentpractice.Answers.onCreate(Answers.java:18)
Solved, I forgot returning getCount to array.size().
Thanks all!!!
There is a issue in your for loop for adding the images into the list.
For the position 0, there will be only one element in the arrayImg but you are calling arrayImg.get(1) which is causing java.lang.IndexOutOfBoundsException
change that line to:
for (int position = 0; position < arrayName.size(); position++){
int id = getResources().getIdentifier(arrayName.get(position), "drawable", getPackageName());
arrayImg.add(new HinhAnh(arrayName.get(position) + "", id));
Toast.makeText(this, arrayImg.get(position).getTen() + "", Toast.LENGTH_SHORT).show();
}
I have a GridView which shows all the images from phone. I'm able to select multiple images and save the selected images to arraylist. I want to restrict the size of the selected images to 1MB. For that I want to check the size of every image while selecting. If the size of clicked image is less than 1MB then it will get selected, otherwise not. Is there any way to do that?
Activity
public class CustomGalleryActivity extends AppCompatActivity implements View.OnClickListener {
private static Button selectImages;
private static GridView galleryImagesGridView;
private static ArrayList<String> galleryImageUrls;
private static GridViewAdapter imagesAdapter;
int file_size;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.customgallery_activity);
initViews();
setListeners();
fetchGalleryImages();
setUpGridView();
}
//Init all views
private void initViews() {
selectImages = (Button) findViewById(R.id.selectImagesBtn);
galleryImagesGridView = (GridView) findViewById(R.id.galleryImagesGridView);
}
//fetch all images from gallery
private void fetchGalleryImages() {
final String[] columns = {MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID};//get all columns of type images
final String orderBy = MediaStore.Images.Media.DATE_TAKEN;//order data by date
Cursor imagecursor = managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null,
null, orderBy + " DESC");//get all data in Cursor by sorting in DESC order
galleryImageUrls = new ArrayList<String>();//Init array
//Loop to cursor count
for (int i = 0; i < imagecursor.getCount(); i++) {
imagecursor.moveToPosition(i);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);//get column index
galleryImageUrls.add(imagecursor.getString(dataColumnIndex));//get Image from column index
System.out.println("Array path" + galleryImageUrls.get(i));
}
}
//Set Up GridView method
private void setUpGridView() {
imagesAdapter = new GridViewAdapter(CustomGalleryActivity.this, galleryImageUrls);
galleryImagesGridView.setAdapter(imagesAdapter);
}
//Set Listeners method
private void setListeners() {
selectImages.setOnClickListener(this);
}
//Show hide select button if images are selected or deselected
public void showSelectButton() {
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
if (selectedItems.size() > 0) {
selectImages.setText(selectedItems.size() + " - Images Selected");
selectImages.setVisibility(View.VISIBLE);
} else
selectImages.setVisibility(View.GONE);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.selectImagesBtn:
//When button is clicked then fill array with selected images
ArrayList<String> selectedItems = imagesAdapter.getCheckedItems();
//Send back result to MainActivity with selected images
Intent intent = new Intent();
intent.putExtra(UploadActivity.CustomGalleryIntentKey, selectedItems.toString());//Convert Array into string to pass data
setResult(RESULT_OK, intent);//Set result OK
finish();//finish activity
break;
}
}
}
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
public GridViewAdapter(Context context, ArrayList<String> imageUrls) {
this.context = context;
this.imageUrls = imageUrls;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("sammy_position "+buttonView.getTag());
File f = new File(imageUrls.get((Integer) buttonView.getTag()));
int file_size = Integer.parseInt(String.valueOf(f.length() / (1024*1024)));
// Filtering the image size
if(file_size<1){
mSparseBooleanArray.put((Integer) buttonView.getTag(), isChecked);//Insert selected checkbox value inside boolean array
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}else{
buttonView.setChecked(false);
Toast.makeText(context, "Select image of size 1MB or less", Toast.LENGTH_SHORT).show();
}
}
};
}
public void calculateImageSize(int imageId){
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
imageId);
Bitmap bitmap = bitmapOrg;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
double sizeInKB=(lengthbmp/1024);
double sizeInMB=(lengthbmp/(1024*1024));
Log.d("TAG","Size "+sizeInKB+"KB");
Log.d("TAG","Size "+sizeInMB+"MB");
}
Replace Adapter With this
import android.content.Context;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import java.util.ArrayList;
public class GridViewAdapter extends BaseAdapter {
private Context context;
private ArrayList<String> imageUrls;
private SparseBooleanArray mSparseBooleanArray;
private boolean isCustomGalleryActivity;
public GridViewAdapter(Context context, ArrayList<String> imageUrls, boolean isCustomGalleryActivity) {
this.context = context;
this.imageUrls = imageUrls;
this.isCustomGalleryActivity = isCustomGalleryActivity;
mSparseBooleanArray = new SparseBooleanArray();
}
//Method to return selected Images
public ArrayList<String> getCheckedItems() {
ArrayList<String> mTempArry = new ArrayList<String>();
for (int i = 0; i < imageUrls.size(); i++) {
if (mSparseBooleanArray.get(i)) {
mTempArry.add(imageUrls.get(i));
}
}
return mTempArry;
}
#Override
public int getCount() {
return imageUrls.size();
//return 10;
}
#Override
public Object getItem(int i) {
return imageUrls.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (view == null)
view = inflater.inflate(R.layout.customgridview_item, viewGroup, false);//Inflate layout
CheckBox mCheckBox = (CheckBox) view.findViewById(R.id.selectCheckBox);
final ImageView imageView = (ImageView) view.findViewById(R.id.galleryImageView);
//If Context is MainActivity then hide checkbox
if (!isCustomGalleryActivity)
mCheckBox.setVisibility(View.GONE);
Picasso.with(context).load("file://" + imageUrls.get(position)).placeholder(R.drawable.placeholder).into(imageView);
mCheckBox.setTag("file://" + imageUrls.get(position));
mCheckBox.setId(position);//Set Tag for CheckBox
mCheckBox.setChecked(mSparseBooleanArray.get(position));
mCheckBox.setOnCheckedChangeListener(mCheckedChangeListener);
return view;
}
CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mSparseBooleanArray.put((Integer) buttonView.getId(), isChecked);//Insert selected checkbox value inside boolean array
String imagePath = (String) buttonView.getTag();
((CustomGalleryActivity) context).showSelectButton();//call custom gallery activity method
}
};
}
Use this function to find out the size in kb & MB
I have made a custom adapter to populate my gridView. What I am doing is that i am trying to populate the gridview with two different data(that too are custom) which are: Movies and FavouriteMovies. when the dridview is updated using Movies it updates just fine but when it FavouriteMovies it does not. I am storing FavouriteMovies in a sqlite db and then querying it to return a cursor.the data returns perfectly and there is no error. the main problem is with my MoviesAdapter. inside this when i add Movies to adapter it adds to the list inside MoviesAdapter and it works perfectly but when I add FavouriteMovies to the adapter it does not add it inside the favouriteList inside MoviesAdapter and its size is always zero.
please help!!
here is my MoviesAdapter:
package com.akshitjain.popularmovies;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
public class MoviesAdapter extends BaseAdapter {
private Context mContext;
List<Movies> list = new ArrayList<>();
List<FavouriteMovies> favouriteList = new ArrayList<>();
public MoviesAdapter(Context c) {
this.mContext = c;
}
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
#Override
public Object getItem(int position) {
if (list != null)
return list.get(position);
else
return favouriteList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(mContext).inflate(R.layout.grid_item_movies, parent, false);
}
ImageView moviePoster = (ImageView) convertView.findViewById(R.id.grid_item_movie_image);
if (list != null) {
Movies movies = list.get(position);
String posterPath = movies.posterPath;
final String POSTER_FINAL_URL = Constants.IMAGE_BASE_URL + Constants.POSTER_SIZE_LARGE + posterPath;
Picasso.with(mContext).load(POSTER_FINAL_URL.trim()).into(moviePoster);
} else {
FavouriteMovies favouriteMovies = favouriteList.get(position);
byte[] bb = favouriteMovies.posterImage;
moviePoster.setImageBitmap(BitmapFactory.decodeByteArray(bb, 0, bb.length));
}
return convertView;
}
public void add(Movies movies) {
list.add(movies);
}
public void offlineAdd(FavouriteMovies favouriteMovies) {
favouriteList.add(favouriteMovies);
}
public void clear() {
list.clear();
}
}
and here is where I am adding to the adapter:
#Override
protected void onPostExecute(Movies[] strings) {
if (strings != null) {
mMoviesAdapter.clear();
for (Movies moviesStr : strings) {
mMoviesAdapter.add(moviesStr);
}
}else if(mFavouriteMovies != null){
mMoviesAdapter.clear();
for(FavouriteMovies favouriteMoviesStr : mFavouriteMovies){
mMoviesAdapter.offlineAdd(favouriteMoviesStr);
}
}
Log.v("FetchMoviesTask","Count :" + mMoviesAdapter.getItem(0));
mMoviesAdapter.notifyDataSetChanged();
}
So sorry for my crude language.
You will always have count == 0 if you set your favorite movies.
List<Movies> list = new ArrayList<>();
#Override
public int getCount() {
if (list != null)
return list.size();
else
return favouriteList.size();
}
This will always return a count of 0 since list never is null. You favorite movies get ignored.
Solutions
Since you are only displaying either movies or favorites you should use 2 adapters. If you don't want to do this,
Use a boolean. Just set showFavorites to true, and display those. Or if you keep your null checks,
set the List<Movie> = null; when displaying favorited, then it will also work.
use following adapter:-
boolean[] CheckedItem_Adap;
ImageLoader imgload;
int headercount = 0, childCount;
LinkedList<HashMap<String, String>> allData;
LinkedList<HashMap<String, String>> temp_Header;
LinkedList<HashMap<String, String>> temp_child = new LinkedList<HashMap<String, String>>();
ArrayList<String> header;
ArrayList<String> childCount1;
private int[] mSectionIndices;
private String[] mSectionLetters;
private LayoutInflater inflater;
private Activity context;
public Adapter_UserTimeLine_StickyGrid(Activity context1, LinkedList<HashMap<String, String>> list, boolean[] checkedItems, ArrayList<String> childCountArray, ArrayList<String> headerarray, LinkedList<HashMap<String, String>> temp_Headers_LinkList) {
this.CheckedItem_Adap = checkedItems;
allData = list;
inflater = LayoutInflater.from(context1);
imgload = new ImageLoader(context1);
childCount1 = childCountArray;
header = headerarray;
temp_Header = temp_Headers_LinkList;
context = context1;
}
#Override
public int getCount() {
return allData.size();
}
#Override
public Object getItem(int position) {
return allData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.sticky_listitems, parent, false);
}
holder.ivPostPic_Sticky = (ImageView) convertView.findViewById(R.id.ivPostPic_Sticky);
holder.ivSelectedToDelete_Sticky = (ImageView) convertView.findViewById(R.id.ivSelectedToDelete_Sticky);
holder.rlPostSticky_ManageSticky = (RelativeLayout) convertView.findViewById(R.id.rlPostSticky_ManageSticky);
if (CheckedItem_Adap[position] == true) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
} else if (CheckedItem_Adap[position] == false) {
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
}
if (allData.get(position).get("media_type").equals("text")) {
holder.ivPostPic_Sticky.setImageResource(R.drawable.line_small);
} else {
imgload.DisplayImage(Constants.Imge_baseUrl + allData.get(position).get("video_thumb"),
holder.ivPostPic_Sticky);
}
holder.rlPostSticky_ManageSticky.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (UserTimeLine_Activity.isDeleteSelected) {
if (CheckedItem_Adap[position] == false) {
UserTimeLine_Activity.Selected_PostIds.add(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.VISIBLE);
CheckedItem_Adap[position] = true;
} else {
UserTimeLine_Activity.Selected_PostIds.remove(allData.get(position).get("post_id"));
holder.ivSelectedToDelete_Sticky.setVisibility(View.GONE);
CheckedItem_Adap[position] = false;
}
for (int i = 0; i < UserTimeLine_Activity.Selected_PostIds.size(); i++) {
Log.e("postid", i + "-" + UserTimeLine_Activity.Selected_PostIds.get(i) + "");
}
if (UserTimeLine_Activity.Selected_PostIds.get(0).equals(UserTimeLine_Activity.Selected_PostIds.get(0))) { }
} else {
String media_type = allData.get(position).get("media_type");
String post_id = allData.get(position).get("post_id");
Intent in = new Intent(context, PostDetails_UserOwn_TimeLIne_Activity.class);
in.putExtra("media_type", media_type);
in.putExtra("post_id", post_id);
in.putExtra("position", String.valueOf(position));
in.putExtra("post_User_Name", allData.get(position).get("post_User_Name"));
context.startActivity(in);
}
}
});
return convertView;
}
#Override
public int getCountForHeader(int i) {
int c = Integer.valueOf(childCount1.get(i));
return c;
}
#Override
public int getNumHeaders() {
return temp_Header.size();
}
#Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
HeaderViewHolder holder = new HeaderViewHolder();
if (convertView == null) {
convertView = inflater.inflate(R.layout.headersticky_managepost, parent, false);
}
temp_Header.get(position).get("post_datetime");
TextView tvDate_Sticky = (TextView) convertView.findViewById(R.id.tvDate_Sticky);
for (int i = 0; i < temp_Header.size(); i++) {
}
String Date = temp_Header.get(position).get("post_datetime");
String FormatedDate = parseDateToddMMyyyy(Date);
tvDate_Sticky.setText(FormatedDate);
return convertView;
}
public String parseDateToddMMyyyy(String time) {
String inputPattern = "yyyy-MM-dd";
String outputPattern = "MMM-dd-yyyy";
SimpleDateFormat inputFormat = new SimpleDateFormat(inputPattern);
SimpleDateFormat outputFormat = new SimpleDateFormat(outputPattern);
Date date = null;
String str = null;
try {
date = inputFormat.parse(time);
str = outputFormat.format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return str;
}
class HeaderViewHolder {
TextView tvDate_Sticky;
}
class ViewHolder {
ImageView ivPostPic_Sticky, ivSelectedToDelete_Sticky;
RelativeLayout rlPostSticky_ManageSticky;
}
}
I have a custom BaseAdapter class that creates views for comments, usernames, and numbers. This BaseAdapter receives this information from An AsyncTask. The AsyncTask runs when the user reaches the bottom of the listView. The problem is the BaseAdapter wont add new data. When I try to add new data it deletes the current data in the list and then adds the new data. I want it to keep all the data and just add data to the bottom of the listView. All of these classes are in the same Activity. Here is my current code.
class CreateCommentLists extends BaseAdapter{
Context ctx_invitation;
String[] listComments;
String[] listNumbers;
String[] listUsernames;
public CreateCommentLists(String[] comments, String[] usernames, String[] numbers, DashboardActivity context)
{
super();
ctx_invitation = context;
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
#Override
public int getCount() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
public void add(String[] comments, String[] usernames,
String[] numbers) {
listComments = comments;
listNumbers = usernames;
listUsernames = numbers;
}
public int getCount1() {
if(null == listComments)
{
return 0;
}
// TODO Auto-generated method stub
return listComments.length;
}
public Object getItem1(int position) {
// TODO Auto-generated method stub
return listComments[position];
}
public long getItemId1(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView1(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = null;
try
{
String inflater = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater li = (LayoutInflater)ctx_invitation.getSystemService(inflater);
v = li.inflate(R.layout.list_item, null);
TextView commentView = (TextView)v.findViewById(R.id.listComment);
TextView NumbersView = (TextView)v.findViewById(R.id.listNumber);
TextView usernamesView = (TextView)v.findViewById(R.id.listPostedBy);
Button usernameButton = (Button)v.findViewById(R.id.listUsernameButton);
Button numberButton = (Button)v.findViewById(R.id.listNumberButton);
commentView.setText(listComments[position]);
NumbersView.setText(listNumbers[position]);
usernamesView.setText(listUsernames[position]);
usernameButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("usernameOfProfile",listUsernames[position]);
startActivity(i);
finish();
}
});
numberButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(getApplicationContext(), ProfileActivity.class);
i.putExtra("NumberProfile",listNumbers[position]);
startActivity(i);
finish();
}
});
}
catch(Exception e)
{
e.printStackTrace();
}
return v;
}
final CreateCommentLists mycmlist = new CreateCommentLists(comments, usernames, numbers, DashboardActivity.this);
lstComments = (ListView)findViewById(android.R.id.list);
lstComments.setAdapter(mycmlist);
final ProgressDialog progDailog = new ProgressDialog(DashboardActivity.this);
class loadComments extends AsyncTask<JSONObject, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
progDailog.setIndeterminate(false);
progDailog.setCancelable(true);
progDailog.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
progDailog.show();
progDailog.setContentView(R.layout.progress_circle);
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
}
protected JSONObject doInBackground(JSONObject... params) {
JSONObject json2 = CollectComments.collectComments(usernameforcomments, offsetNumber);
return json2;
}
#Override
protected void onPostExecute(JSONObject json2) {
try {
if (json2.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res2 = json2.getString(KEY_SUCCESS);
if(Integer.parseInt(res2) == 1){
JSONArray commentArray = json2.getJSONArray(KEY_COMMENT);
String comments[] = new String[commentArray.length()];
for ( int i=0; i<commentArray.length(); i++ ) {
comments[i] = commentArray.getString(i);
}
JSONArray numberArray = json2.getJSONArray(KEY_NUMBER);
String numbers[] = new String[numberArray.length()];
for ( int i=0; i<numberArray.length(); i++ ) {
numbers[i] = numberArray.getString(i);
}
JSONArray usernameArray = json2.getJSONArray(KEY_USERNAME);
String usernames[] = new String[usernameArray.length()];
for ( int i=0; i<usernameArray.length(); i++ ) {
usernames[i] = usernameArray.getString(i);
}
mycmlist.add(comments,usernames,numbers);
mycmlist.notifyDataSetChanged();
}//end if key is == 1
else{
// Error in registration
registerErrorMsg.setText(json2.getString(KEY_ERROR_MSG));
}//end else
}//end if
} //end try
catch (JSONException e) {
e.printStackTrace();
}//end catch
progDailog.dismiss();
}
}
mainListView = (ListView) findViewById(android.R.id.list);
class EndlessScrollListener implements OnScrollListener {
private int i = 0;
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public EndlessScrollListener() {
}
public EndlessScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if ((firstVisibleItem + visibleItemCount) == totalItemCount) {
new loadComments().execute();
mainListView.smoothScrollToPosition(0);
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
mainListView.setOnScrollListener(new EndlessScrollListener());
You try this :
public class Comment {
String username;
String content;
String number;
}
Class Adapter:
public class CommentAdapter extends BaseAdapter {
private List<Comment> listComment;
private Context context;
public CommentAdapter(List<Comment> listComment, Context context) {
super();
this.listComment = listComment;
this.context = context;
}
#Override
public int getCount() {
return listComment.size();
}
#Override
public Comment getItem(int position) {
return listComment.get(position);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = mInflater.inflate(R.layout.comment_item, null);
}
final TextView textViewUsername = (TextView) v
.findViewById(R.id.comment_Username);
final TextView textViewNumber = (TextView) v
.findViewById(R.id.comment_number);
final TextView textViewContent = (TextView) v
.findViewById(R.id.comment_Content);
final String username = listComment.get(position).getUsername();
final String number= listComment.get(position).getNumber();
String content = listComment.get(position).getContent();
textViewUsername.setText(username);
textViewNumber.setText(number);
textViewContent.setText(content);
return v;
}
}
When you need to add new comment to list. just create new Comment and add to listComment(listComment.add(newComment)), after that, call adapter.notifyDataSetChanged();
package com.example.baseadapter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends Activity implements OnItemClickListener {
public static final String[] title = new String[] {
"image 1", "image 2", "image 3", "image 4"
};
public static final Integer[] images = {
R.drawable.aa, R.drawable.bb, R.drawable.cc, R.drawable.cc, R.drawable.dd
};
ListView listview;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < title.length; i++) {
RowItem item = new RowItem(images[i], title[i]);
rowItems.add(item);
}
listview = (ListView)findViewById(R.id.listview);
customBaseAdapter cba = new customBaseAdapter(this, rowItems);
listview.setAdapter(cba);
listview.setOnItemClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(getApplicationContext(), "item selected", Toast.LENGTH_LONG).show();
}
public class customBaseAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItem;
public customBaseAdapter(Context context, List<RowItem> listItem) {
this.context = context;
rowItem = listItem;
Log.d("const", "const");
}
#Override
public int getCount() {
Log.d("count", "count");
return rowItem.size();
}
#Override
public Object getItem(int arg0) {
Log.d("item", "item");
return rowItem.get(arg0);
}
#Override
public long getItemId(int position) {
Log.d("const", "item id");
return rowItem.indexOf(getItem(position));
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Log.d("const", "getview");
LayoutInflater inflater = (LayoutInflater)context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
RowItem rowitem = (RowItem)getItem(position);
TextView textForTitle;
ImageView imgForImage;
convertView = inflater.inflate(R.layout.inflate, null);
textForTitle = (TextView)convertView.findViewById(R.id.textview);
imgForImage = (ImageView)convertView.findViewById(R.id.imageview);
textForTitle.setText(rowitem.getTitle());
imgForImage.setImageResource(rowitem.getImageId());
return convertView;
}
}
public class RowItem {
int imageId;
String title;
public RowItem(int imageId, String title) {
this.imageId = imageId;
this.title = title;
}
public int getImageId() {
return imageId;
}
public void setImageId(int imageId) {
this.imageId = imageId;
}
public String getTitle() {
return title;
}
public void setStringTitle(String title) {
this.title = title;
}
#Override
public String toString() {
return title;
}
}
}
I am trying to Create a Array Adapter to set content from an Array of text to the adapter but i am not able to set the adapter from the Activity. Am not sure what i should pass for the resource as Int
PlacesListAdapter.java
public class PlacesListAdapter extends ArrayAdapter<Place> {
public Context context;
private List<Place> places;
public PlacesListAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
public PlacesListAdapter(Context context, int resource, List<Place> places) {
super(context, resource, places);
this.context = context;
this.places = places;
// imageLoader = new ImageLoader(context.getApplicationContext());
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View view = convertView;
Place p = places.get(position);
if (convertView == null) {
LayoutInflater viewInflater;
viewInflater = LayoutInflater.from(getContext());
view = viewInflater.inflate(R.layout.item_place, null);
holder = new ViewHolder();
holder.placeTitle = (TextView) view.findViewById(R.id.place_title);
holder.placeDistance = (TextView) view
.findViewById(R.id.place_distance);
view.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.placeTitle.setText(p.getPlaceTitle());
holder.placeDistance.setText("200");
holder.placeCategoryIcon.setImageResource(R.drawable.marker);
return view;
}
static class ViewHolder {
TextView placeId;
TextView placeTitle;
TextView placeDistance;
ImageView placeCategoryIcon;
}
}
Place.java
public class Place {
String placeId = "", placeTitle = "", placeDistance = "",
placeCategoryIcon = "";
public Place(String placeId, String placeTitle, String placeDistance,
String placeCategoryIcon) {
this.placeId = placeId;
this.placeTitle = placeTitle;
this.placeDistance = placeDistance;
this.placeCategoryIcon = placeCategoryIcon;
}
public String getPlaceId() {
return placeId;
}
public void setPlaceId(String placeId) {
this.placeId = placeId;
}
public String getPlaceTitle() {
return placeTitle;
}
public void setPlaceTitle(String placeTitle) {
this.placeTitle = placeTitle;
}
public String getPlaceDistance() {
return placeDistance;
}
public void setPlaceDistance(String placeDistance) {
this.placeDistance = placeDistance;
}
public String getPlaceCategoryIcon() {
return placeCategoryIcon;
}
public void setPlaceCategoryIcon(String placeCategoryIcon) {
this.placeCategoryIcon = placeCategoryIcon;
}
}
Now in MainActiivty i am trying to set the adapter so that it populates the list from the Array
public class MainActivity extends SherlockFragmentActivity implements
SearchView.OnQueryTextListener {
private final String[] places = new String[] { "Mysore", "Bangalore", "Mangalore",
"Wayanad", "Bandipur National Park", "Chickmaglur",
"Bandipura", "Coorg", "Kodaikanal", "Hampi",
"Ghati Subramanya", "Mekedatu", "Muththathhi", "Shivasamudram",
"Talakadu", "Savana Durga" };
public SearchView mSearchView;
private TextView mStatusView;
private Menu mainMenu = null;
PlacesListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("Nomad", "onCreate");
ListView listView = (ListView) findViewById(R.id.place_list);
adapter = new PlacesListAdapter(this, resource, places);
}
}
I am not sure what to set for resources in adapter = new PlacesListAdapter(this, resource, places);
Initialize the resource variable:
// it doesn't matter what values you assing to the resource variable because you build
// the row layout yourself in the getView method of the adapter
int resource = android.R.layout.simple_list_item_1;
adapter = new PlacesListAdapter(this, resource, places);
Edit:
List<Place> thePlaces = new ArrayList<Place>();
for (int i = 0; i < places.length; i++) {
Place pl = new Place("NO_ID", places[i], "NO_DISTANCE", "NO_CATEGORYICON");
thePlaces.add(pl);
}
int resource = android.R.layout.simple_list_item_1;
adapter = new PlacesListAdapter(this, resource, thePlaces);
pass row layout id instead of default android layout if your are creating custom adapter by extending ArrayAdapter:
adapter = new PlacesListAdapter(this,R.layout.item_place, places);
instead of
adapter = new PlacesListAdapter(this, resource, places);