Android getView and ImageAdapter - android

I would like to implement that kind of gallery, but with the difference of getting images remotly.
The idea is to update the view only when an image has been downloaded.
=> I need to update the view only when going to onComplete.
Please find below my code :
public class displayAlbums extends Activity {
private static String URL_GRAPH_API = "https://graph.facebook.com/";
private static final String TAG = "displayAlbums";
private ArrayList<Bitmap> thumbnails = new ArrayList<Bitmap>();
private ArrayList<URI> thumbnails_uri = new ArrayList<URI>();
private ImageAdapter imageAdapter;
private int imageCounter = 0;
public boolean[] thumbnailsselection;
public Albums album;
private Context displayAlbums_context;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galleryitem);
this.displayAlbums_context = this;
Log.d(TAG, "on create");
findViewById(R.id.itemCheckBox).setVisibility(View.GONE);
final GridView imagegrid = (GridView) findViewById(R.id.PhoneImageGrid);
populateThumbnailsList();
processThumbnailsToDownload(thumbnails_uri, new PictureRequestListener() {
#Override
public void onComplete(Bitmap bitmap) {
if(imageAdapter == null) {
Log.d(TAG, "image adapter is null");
imageAdapter = new ImageAdapter(displayAlbums_context);
imagegrid.setAdapter(imageAdapter);
}
imagegrid.setId(imageCounter);
thumbnails.add(bitmap);
imageCounter++;
//imageAdapter.notifyDataSetChanged();
}
});
}
public void processThumbnailsToDownload(ArrayList<URI> thumbnails_uri, final FbRequestListener listener) {
Log.v(TAG,"processThumbnailsToDownload CALLED");
for(URI thumbnail_uri : thumbnails_uri ) {
new HttpConnection(ConnectionManager.getConnectionHandler(listener)).bitmap(thumbnail_uri);
}
}
public void populateThumbnailsList() {
URI uri = null;
for(final Albums album : LoadObjects.albums ) {
Bundle parameters = new Bundle();
parameters.putString("access_token", FbpicturesActivity.mFacebook.getAccessToken());
try {
uri = new URI(URL_GRAPH_API + album.getAid() + "/picture" + "?" +Util.encodeUrl(parameters) );
thumbnails_uri.add(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context myContext;
public ImageAdapter(Context displayAlbums_context) {
Log.v(TAG,"IMAGE ADAPTER");
mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
Log.d(TAG,"thumnail_uri size"+thumbnails_uri.size());
return thumbnails_uri.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
Log.v(TAG,"GET VIEW CALLED");
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = mInflater.inflate(R.layout.galleryitem, null);
holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
//holder.checkbox.setId(position);
//holder.imageview.setId(position);
Log.d(TAG,"thumnail size"+thumbnails.size());
Log.d(TAG,"thumnail position"+thumbnails.get(position));
holder.imageview.setImageBitmap(thumbnails.get(position));
holder.checkbox.setChecked(true);
holder.id = position;
return convertView;
}
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
galleryItem.xml :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<Button android:id="#+id/selectBtn"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:text="Select" android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:minWidth="200px" />
<GridView android:id="#+id/PhoneImageGrid"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:columnWidth="90dp"
android:stretchMode="columnWidth" android:gravity="center"
android:layout_above="#id/selectBtn" />
<ImageView android:id="#+id/thumbImage" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_centerInParent="true" />
<CheckBox android:id="#+id/itemCheckBox" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
Please note i have added some Log.v to understand when getView is called :
=> http://pastebin.com/L9PYBYDa
questions :
1) Why getView is called 4 times ?
2) Why holder.imageview.setImageBitmap(thumbnails.get(position)) returns java.lang.IndexOutOfBoundsException: Invalid index 1, size is 1 ?
3) Do you have any advice to implement my gallery with remote image ?
Thank you very much for your help

1) getView will be called at least (numberOfVisibleRows+ 1 or +2) times. I say at least because it can be called as many times as the system wants. There is no guarantee on that.
2)Because thumbnails is lower than size 2 or is null. You have to debug to see that
3) Check this out

Related

Implement click only on image not on text in custom listview

I have a custom Listview where it contains image & text and implemented the OnItemClickListener for list which should work only for image not for text. OnItemClick is working fine for image but there is a Fatal Exception when i click on text. Additionally image will be visible in list if it exists else it will be hide.
Tried with android:focusable="false", android:clickable="false" but still i am getting the below exception
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable.getBitmap()' on a null object reference
OnItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ImageView imageView1 = (ImageView) view.findViewById(R.id.imageList);
final GlideBitmapDrawable bitmapDrawable = (GlideBitmapDrawable) imageView1.getDrawable();
final Bitmap yourBitmap = bitmapDrawable.getBitmap();
Dialog builder = new Dialog(this);
builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
builder.getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.TRANSPARENT));
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialogInterface) {
//nothing;
}
});
ImageView imageView = new ImageView(this);
imageView.setImageBitmap(yourBitmap);
builder.addContentView(imageView, new RelativeLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
builder.show();
}
How can i implement click only on image?
In your custom layout xml, set
android:descendantFocusability="blocksDescendants"
to your root layout.
Edit
Check my Custom ListView.
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:gravity="center"
android:descendantFocusability="blocksDescendants"
android:layout_height="60dp">
<ImageView
android:id="#+id/m_imageview"
android:layout_width="0dp"
android:layout_weight="1"
android:src="#drawable/ic_launcher"
android:layout_height="50dp" />
<TextView
android:id="#+id/m_textview"
android:layout_width="0dp"
android:layout_weight="3"
android:layout_height="50dp"
android:gravity="center|center"
android:textColor="#ffffff"
android:text="hello"/>
<Button
android:id="#+id/m_buttonview"
android:layout_width="0dp"
android:layout_weight="2"
android:text="OK"
android:layout_height="50dp" />
</LinearLayout>
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView
android:id="#+id/lv_items"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:dividerHeight="2dp"
android:divider="#ffffff"
tools:context=".MainActivity" />
</RelativeLayout>
CustomListViewAdapter.java
public class CustomListViewAdapter extends ArrayAdapter<RowItem> {
Context context;
public CustomListViewAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
}
/*private view holder class*/
private class ViewHolder {
ImageView m_pic;
TextView m_title;
Button m_btn;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
RowItem rowItem = getItem(position);
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.listitem, null);
holder = new ViewHolder();
holder.m_title = (TextView) convertView.findViewById(R.id.m_textview);
holder.m_btn = (Button)convertView.findViewById(R.id.m_buttonview);
holder.m_pic = (ImageView) convertView.findViewById(R.id.m_imageview);
convertView.setTag(holder);
}
else
holder = (ViewHolder) convertView.getTag();
holder.m_title.setText(rowItem.getTxt());
holder.m_pic.setImageResource(rowItem.getImage());
holder.m_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, position + " clicked" , Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
RowItem.java
public class RowItem {
private int image;
private String txt;
public RowItem(int imageview , String textview)
{
this.image = imageview;
this.txt = textview;
}
public int getImage() {
return image;
}
public String getTxt() {
return txt;
}
public void setImage(int image) {
this.image = image;
}
public void setTxt(String txt) {
this.txt = txt;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
String m_txt[] = {"one" , "two" , "three" , "four", "five"};
int m_img [] = {R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher ,
R.drawable.ic_launcher};
ListView m_list;
List<RowItem> rowItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_list = (ListView)findViewById(R.id.lv_items);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < m_txt.length; i++) {
RowItem item = new RowItem(m_img[i],m_txt[i]);
rowItems.add(item);
}
CustomListViewAdapter adapter = new CustomListViewAdapter(this,
R.layout.listitem, rowItems);
m_list.setAdapter(adapter);
m_list.setOnItemClickListener(MainActivity.this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position) + ": " + rowItems.get(position).getTxt(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
}
This should helps you.
Happy coding.!!!
use a recyclerview.
a recylerview handles every list item as a view, it can hold clicklisteners for every view it holds and that view can hold clicklisteners for every view its holding.

Android : how to get value from assets and pass it thru array

I want to short my code length by using array.If I have 100 button or image view I have to write for 100 . I want to get value from assets folder and pass it in to array . how to use
String[] colorNames = getResources().getStringArray(R.array.colorList);
String[] animalNames = getResources().getStringArray(R.array.animalList);
Current working code :
public class Main extends Activity {
ImageView image;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drag);
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
image = (ImageView) findViewById(R.id.image);
Button btn1,btn2;
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
if(key.equals("animalIntent") )
{
btn1.setText("cat");
btn2.setText("dog");
// same for 100 button ............. here i want to short my code
} else {
btn1.setText("red");
btn2.setText("blue");
}
}
public void btn1(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.cat);
// same for 100 image view ............. here i want to short my code
} else {
image.setBackgroundResource(R.drawable.red);
}
}
public void btn2(View view) {
Intent intent = getIntent();
String key = intent.getStringExtra("YOUR_KEY");
if(key.equals("animalIntent") )
{
image.setBackgroundResource(R.drawable.dog);
} else {
image.setBackgroundResource(R.drawable.blue);
}
}
To do that you should use GridView,it would be best option. try the below sample code.
Step-1 add the gridview in your drag.xml
<GridView
android:id="#+id/grid"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/edt"
android:numColumns="2"
android:stretchMode="columnWidth" >
</GridView>
Step-2 Declare the variables and get the grid view reference.
GridView gridview;
Integer[] drawableIds = { R.drawable.poster1, R.drawable.poster2, R.drawable.poster3, R.drawable.poster4,
R.drawable.poster5 };
String[] colorNames = { "poster one", "poster two", "poster three", "poster four", "poster five" };
//In OnCreate() method add
gridview = (GridView) findViewById(R.id.grid);
gridview.setAdapter(new CustomGridAdapter(this, drawableIds, colorNames));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
Toast.makeText(Main.this, "" + position, Toast.LENGTH_LONG).show();
}
});
Step-3 create a class for grid adapter CustomGridAdapter.class
public class CustomGridAdapter extends BaseAdapter {
private Context context;
private Integer[] drawableitems;
private String[] drawablelabel;
public CustomGridAdapter(Context context, Integer[] drawableitems, String[] drawablelabel) {
this.context = context;
this.drawablelabel = drawablelabel;
this.drawableitems = drawableitems;
}
#Override
public int getCount() {
return drawableitems.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
RecordHolder holder = null;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
holder = new RecordHolder();
convertView = inflater.inflate(R.layout.grid_item, null);
holder.txtTitle = (TextView) convertView.findViewById(R.id.grid_item_label);
holder.imageItem = (ImageView) convertView.findViewById(R.id.grid_item_image);
convertView.setTag(holder);
} else {
holder = (RecordHolder) convertView.getTag();
}
holder.txtTitle.setText(drawablelabel[position]);
holder.imageItem.setImageResource(drawableitems[position]);
return convertView;
}
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
}
}
Add custom view for grid grid_item.xml in layout folder.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/llback"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ImageView
android:id="#+id/grid_item_image"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center" >
</ImageView>
<TextView
android:id="#+id/grid_item_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:textColor="#android:color/black"
android:textSize="18sp"
android:textStyle="bold" >
</TextView>
</LinearLayout>
Hope it will help you.

Data not showing in static way using listview

I am new to android and i am working on listview. I am trying to show data using listview in xml and adapter in class file. I am working on following 3 files.
First file: activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.listpractice.MainActivity" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
></ListView>
</RelativeLayout>
Second file: row1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight" >
<ImageView
android:id="#+id/icon"
android:contentDescription="#string/hello_world"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:layout_marginEnd="10dp"
android:src="#drawable/ic_launcher"
/>
<TextView
android:id="#+id/firstTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:textSize="30sp"
android:text="#string/hello_world"
/>
<TextView
android:id="#+id/secondTextView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/icon"
android:layout_toEndOf="#id/icon"
android:layout_below="#id/firstTextView"
android:textSize="13sp"
android:text="#string/hello_world"
/>
</RelativeLayout>
Third file: MainActivity.java
package com.listpractice;
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
public class MainActivity extends ListActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
My Problem : Now i want to show data of row1.xml but i don't have dynamic data. how can i show data using third(.class) file.
check out this link it will help http://androidexample.com/Create_A_Simple_Listview_-_Android_Example/index.php?view=article_discription&aid=65&aaid=90
either you need to create adapter file
public class CustomBaseAdapter extends BaseAdapter{
Context context;
List<RowItem> rowItems;
public CustomBaseAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
//TextView txtDesc;
ImageView imgarrow;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater)
context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
//holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.title);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
holder.imgarrow=(ImageView)convertView.findViewById(R.id.arrow_icon);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
//holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageResource(rowItem.getImageId());
holder.imgarrow.setImageResource(rowItem.getImg());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
MainActivity
public class MainActivity extends Activity implements OnItemClickListener{
public static final String[] titles = new String[] { "Krish",
"John Cena", "Kane","Roman Reigns"};
public static final Integer[] images = { R.drawable.fourth,R.drawable.second,R.drawable.first,R.drawable.third};
public static final Integer[] imagearow = {R.drawable.arrow,R.drawable.arrow,R.drawable.arrow,R.drawable.arrow };
ListView listView;
List<RowItem> rowItems;
private ImageView btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.list_item_home);
//list_travels=(ListView)findViewById(R.id.list_travels);
btn=(ImageView)findViewById(R.id.btnaddhotels);
btn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
Intent i=new Intent(HomeScreen.this,Registerhotel_resorts.class);
startActivity(i);
}
});
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < titles.length; i++) {
RowItem item = new RowItem(images[i], titles[i],imagearow[i]);
rowItems.add(item);
}
listView = (ListView) findViewById(R.id.list_hotels);
CustomBaseAdapter adapter = new CustomBaseAdapter(this, rowItems);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast toast = Toast.makeText(getApplicationContext(),
"Item " + (position + 1) + ": " + rowItems.get(position),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
Intent i1=new Intent(HomeScreen.this,KrishnaParkResort.class);
startActivity(i1);
}
}
You should read this article on Building Layouts with an Adapter. It has some handy concepts which you will need to get your head around.
The fundamental concept is that you need to link your ListView to an Adapter which populates the rows and adds them to the ListView.
Looking at your row1.xml, it looks like you will need a collection of objects which contain;
An image for icon
String for firstTextView
String for secondTextView
You can build a little snippet to create an array of prepopulated objects for test purposes.
public class YourObject {
private Bitmap icon;
private String text1;
private String text2;
public YourObject(Bitmap icon, String text1, String text2) {
this.icon = icon;
this.text1 = text1;
this.text2 = text2;
}
// GETTERS AND SETTERS
}
Then create a collection of them
List<YourObject> data = new ArrayList<>();
for (int z = 0; z < 5; z++) {
YourObject yourObject = new YourObject(yourIcon, "Text1: " + z, "Text2: " + z);
data.add(yourObject);
}
Once you have this collection, you send it to a your Adapter constructor along with the reference to row1.xml, then follow the guide to populate the rows.

Android Gridview - Not able to select image inside Griditem with Android-Box remote

I am creating a android app in which i have list of channels(items) in a Custom GridView.
I have a favorite icon associated with each channel to add them in favorites list.
On click of this favorite icon the channel gets added to the Favorites List of channels.
When i use a android box remote i am not able to select the ImageView for favorite.
Instead the whole GridItem gets selected.
The single grid item is a LinearLayout which mainly has two ImageViews in it.
View code for a single grid-item of the gridview
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:focusable="false"
android:clickable="true"
android:orientation="vertical" >
<ImageView
android:id="#+id/channelLogo"
android:layout_width="75dip"
android:layout_height="75dip"
android:layout_gravity="center"
android:focusable="false"
android:contentDescription="#string/app_name"/>
<TextView
android:id="#+id/channelName"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<TextView
android:id="#+id/channelStatus"
android:layout_width="fill_parent"
android:focusable="false"
android:layout_height="fill_parent"
android:gravity="center"
/>
<ImageView
android:id="#+id/addToFavourite"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:focusableInTouchMode="true"
android:clickable="true"
android:focusable="false"
android:contentDescription="Add to favourites"
android:src="#drawable/addfavorites"
/>
</LinearLayout>
Code for my grid adapter where i handle the click of the ImageView (for adding a channel to favorite).
public class GridAdapter extends BaseAdapter {
private Context mContext;
private int resourceId;
private ArrayList<Item> itemList = new ArrayList<Item>();
private ArrayList<Category> categoryList = new ArrayList<Category>();
private int size;
private Integer[] mThumbIds;
private ViewGroup gridGroup;
private static final String PREFS_FAVOURITES = "favourites";
public GridAdapter(MainActivity c, int layoutResourceId, ArrayList<Item> data, int gsize) {
mContext = c;
resourceId = layoutResourceId;
itemList = data;
size = gsize;
mThumbIds = new Integer[gsize];
for(int i=0;i<mThumbIds.length;i++) {
mThumbIds[i] = R.drawable.ic_launcher;
}
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int arg0) {
return mThumbIds[arg0];
}
#Override
public long getItemId(int arg0) {
return arg0;
}
class ViewHolder {
ImageView imageUrl;
TextView channelNameTxt;
TextView channelStatusTxt;
ImageView imgFavourite;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
String contextClass = mContext.getClass().toString();
ViewHolder holder;
gridGroup = parent;
View grid = null;
if(convertView==null){
grid = new View(mContext);
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
if (contextClass.contains("MainActivity") || contextClass.contains("FavoriteActivity")) {
grid = inflater.inflate(R.layout.grid_item, parent, false);
}
}else{
grid = (View)convertView;
return grid;
}
if (contextClass.contains("MainActivity")) {
if (position < itemList.size()) {
holder = new ViewHolder();
holder.channelNameTxt = (TextView) grid
.findViewById(R.id.channelName);
String channelName = itemList.get(position).getChannelName().replace("\n", "").replace("\r", "");
holder.channelNameTxt.setText(channelName);
holder.channelStatusTxt = (TextView) grid
.findViewById(R.id.channelStatus);
holder.channelStatusTxt
.setText(itemList.get(position).getStatus());
if(itemList.get(position).getStatus().equalsIgnoreCase("Online")) {
holder.channelStatusTxt.setTextColor(Color.GREEN);
} else if(itemList.get(position).getStatus().equalsIgnoreCase("Offline")) {
holder.channelStatusTxt.setTextColor(Color.RED);
}
holder.imageUrl = null;
try {
holder.imageUrl = (ImageView) grid
.findViewById(R.id.channelLogo);
holder.imageUrl.setTag(itemList.get(position).getImageUrl());
new DownloadImagesTask().execute(holder.imageUrl);
notifyDataSetChanged();
} catch (Exception ex) {
System.out.println(ex.toString());
}
final Item info = itemList.get(position);
holder.imgFavourite = (ImageView)grid.findViewById(R.id.addToFavourite);
holder.imgFavourite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//GridView gridview1;
if(mContext.getClass().toString().contains("MainActivity")) {
GridView gv = (GridView)gridGroup;
final int position = gv.getPositionForView((View) v.getParent());
Toast.makeText(mContext, "Position is :" + position, Toast.LENGTH_SHORT).show();
SharedPreferences settings = mContext.getSharedPreferences(PREFS_FAVOURITES, 0);
String favourites = settings.getString("favourites", "");
Item clicked_item = itemList.get(position);
String sep1 = "<sep1>";
String sep = "<sep>";
String favourite = clicked_item.getChannelUrl()+sep1+clicked_item.getChannelName()+sep1+clicked_item.getStatus()+sep1+"Favorite"+sep1+clicked_item.getImageUrl()+sep;
favourite = favourite.replace("\n", "").replace("\r", "");
if(!favourites.contains(favourite))
favourites = favourites+favourite;
SharedPreferences.Editor editor = settings.edit();
editor.putString("favourites", favourites);
editor.commit();
}
}
});
grid.setTag(holder);
}
}
return grid;
}
This works fine on a android phone.

Android - ArrayList<Integer> not displaying properly in custom listVIew

I have a custom listView with three textViews. The data comes from a class with three ArrayLists, two of which are strings and the last one is an Integer. I have no problems populating and adding items to the list as I saw that when I displayed the ArrayList values on logCat via log.d, all three ArrayLists had their respectful items.
It seems to me that there is something wrong with the way I display data.
Here are the files:
list_row_layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/variant"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="variant" />
<TextView
android:id="#+id/quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="quantity" />
<TextView
android:id="#+id/unit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginRight="221dp"
android:layout_toLeftOf="#+id/quantity"
android:text="unit" />
</RelativeLayout>
Here is the part in my activity_order_form.xml that has the listView element.
<RelativeLayout
android:id="#+id/relativeLayout3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_below="#+id/relativeLayout2"
android:orientation="vertical" >
<TextView
android:id="#+id/textViewVariantB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="94dp"
android:text="Variant"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textViewUnit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="123dp"
android:text="Unit"
android:textAppearance="?android:attr/textAppearanceLarge" />
<ListView
android:id="#+id/listViewProductOrder"
android:layout_width="match_parent"
android:layout_height="350dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textViewVariantB" >
</ListView>
</RelativeLayout>
Here is the class where the ArrayList are stored.
public class CurrentOrderClass {
private String productName;
//ArrayLists
private ArrayList<String> variantArray = new ArrayList<String>();
private ArrayList<String> unitArray = new ArrayList<String>();
private ArrayList<Integer> quantityArray = new ArrayList<Integer>();
//TODO ArrayList functions
public ArrayList<String> getUnitArray() {
return unitArray;
}
public void setUnitArray(ArrayList<String> unitArray) {
this.unitArray = unitArray;
}
public void addToUnitArray(String unit){
this.unitArray.add(unit);
}
public ArrayList<Integer> getQuantityArray() {
return quantityArray;
}
public void setQuantityArray(ArrayList<Integer> quantityArray) {
this.quantityArray = quantityArray;
}
public void addToQuantityArray(int quantity){
this.quantityArray.add(quantity);
}
public ArrayList<String> getVariantArray() {
return variantArray;
}
public void setVariantArray(ArrayList<String> variantArray) {
this.variantArray = variantArray;
}
public void addToVariantArray(String variantArray){
this.variantArray.add(variantArray);
}
}
Here is the CustomListAdapter.java file
public class CustomListAdapter extends BaseAdapter {
private ArrayList<CurrentOrderClass> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context context, ArrayList<CurrentOrderClass> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return listData.size();
}
#Override
public Object getItem(int position) {
return listData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.list_row_layout, null);
holder = new ViewHolder();
holder.variantView = (TextView) convertView.findViewById(R.id.variant);
holder.unitView = (TextView) convertView.findViewById(R.id.unit);
holder.quantityView = (TextView) convertView.findViewById(R.id.quantity);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.variantView.setText(listData.get(position).getVariantArray().get(position).toString());
holder.unitView.setText(listData.get(position).getUnitArray().get(position).toString());
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
return convertView;
}
static class ViewHolder {
TextView variantView;
TextView unitView;
TextView quantityView;
}
public void setListData(ArrayList<CurrentOrderClass> data){
listData = data;
}
}
This is part of my OrderForm.java activity, this shows the onCreate and the method that populates the listView.
public class OrderForm extends Activity {
public TextView tv;
private int variantPosition;
CustomListAdapter customListAdapter;
CurrentOrderClass currentOrder = new CurrentOrderClass();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_form);
tv = (TextView)findViewById(R.id.textViewProduct);
//set variants here
popolateItem();
//set current order listview here
ArrayList image_details = getListData();
final ListView lv1 = (ListView) findViewById(R.id.listViewProductOrder);
customListAdapter = new CustomListAdapter(this, image_details);
lv1.setAdapter(customListAdapter);
}
private ArrayList getListData() {
ArrayList results = new ArrayList();
if(currentOrder.getQuantityArray().size() > 10){
loopUntil = currentOrder.getQuantityArray().size();
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray();
currentOrder.getUnitArray();
currentOrder.getVariantArray();
results.add(currentOrder);
}
}
else{
loopUntil = 10;
for(int i = 0; i < loopUntil; i++){
currentOrder.getQuantityArray().add(i);
currentOrder.getUnitArray().add("Sample text here." + i);
currentOrder.getVariantArray().add("Another sample text here" + i);
results.add(currentOrder);
}
}
return results;
}
}
When I execute a Log.d statement to display the contents of my ArrayLists, it shows that my quantityArray has elements [0, 1, 2, 3, 4, 5, 6, 7, 9].
I know I can just convert quantityArray to an ArrayList from an ArayList, but I don't want to do that.
I think there's something wrong with my CustomListAdapter.
Any thoughts?
There is no where that you actually set the view, as in, it doesn't do anything, if convertView is null, you can't call any methods of it, convertView, if its is not null, will be ViewHolder in your context, what you need to do is have an object which is extending some type of view, instantiate it, give it methods to set the values, things like that.
For example here is what I use in an adapter that displays simple messages:
public class MessageView extends RelativeLayout {
private TextView mBody;
private String mBodyString = "";
private boolean mDrawn = false;
private boolean mLocal = false;
public MessageView(Context context) {
super(context);
this.drawView();
}
public MessageView(Context context, String body) {
super(context);
mBodyString = body;
this.drawView();
}
public MessageView(Context context, String body, boolean local) {
super(context);
mBodyString = body;
mLocal = local;
this.drawView();
}
private void drawView() {
if (mDrawn)
return;
mDrawn = true;
this.removeAllViews();
LayoutInflater li = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_TOP);
if(mLocal){
this.addView(li.inflate(R.layout.list_item_message_device, this, false),
params);
}else{
this.addView(li.inflate(R.layout.list_item_message_remote, this, false),
params);
}
mBody = (TextView) this.findViewById(R.id.tMessage);
mBody.setText(mBodyString);
}
public void setLocal(){
this.setLocal(true);
}
public void setLocal(boolean local){
mLocal = local;
mDrawn = false;
this.drawView();
}
public void setMessage(String body){
mBodyString = body;
mBody.setText(mBodyString);
}
}
I got it.
I changed
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityRow()));
to
holder.quantityView.setText(String.valueOf(listData.get(position).getQuantityArray().get(position)));

Categories

Resources