How can I write ArrayList Adapter? [duplicate] - java

This question already has answers here:
How to use ArrayAdapter<myClass>
(5 answers)
Closed 9 years ago.
I want to fields of arrayList to listView but how can I write adapter I dont know. Please help me!!!
I need a my adapter class . I have to see on listView tutar:1.34 kalem="xx"
Class:
public class Income {
String kalem;
int tutar;
public int getTutar() {
return tutar;
}
public void setTutar(int tutar) {
this.tutar = tutar;
}
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getKalem() {
return kalem;
}
public void setKalem(String kalem) {
this.kalem = kalem;
}
}
ArrayList:
sqliteHelper helper = new sqliteHelper(getApplicationContext());
ArrayList<Income> liste=helper.getAllIncome();

There are two ways you can build the adapter:--
Use some adapter provided by Android system like:-
SimpleCursorAdapter
ArrayAdapter,etc
example:--
ListView listView = (ListView) findViewById(R.id.<list_view_id>);
ArrayList<Income> income_array_list = <get the arraylist from whatever sources>;
ArrayAdapter<Income> arrayAdapter = new ArrayAdapter<Income>(
this,
android.R.layout.simple_list_item_1,
income_array_list );
listView.setAdapter(arrayAdapter);
Create your own custom adapter.
I just used only two field just to show you how to build custom adapter,Rest you can build by looking this code.
Example:-
IncomeListAdapter class
private class IncomeListAdapter extends BaseAdapter {
ArrayList<Income> mDisplayedValues;
LayoutInflater inflater;
public IncomeListAdapter(Context context) {
// TODO Auto-generated constructor stub
mDisplayedValues = <your_Income_list>;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mDisplayedValues.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#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 = convertView;
ViewHolder holder;
if (v == null) {
v = inflater.inflate(R.layout.listrow_income, null);
holder = new ViewHolder();
holder.tvTutar = (TextView) v
.findViewById(R.id.tvTutar);
holder.tvId = (TextView) v.findViewById(R.id.tvId);
v.setTag(holder);
} else
holder = (ViewHolder) v.getTag();
holder.tvTutar.setText(mDisplayedValues.get(position).getTutar());
holder.tvId.setText(mDisplayedValues.get(position).getId());
return v;
}
class ViewHolder {
TextView tvTutar;
TextView tvId;
}
}
listrow_income.xml:--
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:gravity="center"
android:orientation="horizontal"
android:padding="8dp" >
<TextView
android:id="#+id/tvTutar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#323232" />
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#android:color/white" />
</LinearLayout>

Try this
private ListView lv;
public void onCreate(Bundle saveInstanceState) {
setContentView(R.layout.your_layout);
lv = (ListView) findViewById(R.id.your_list_view_id);
// Instanciating an array list (you don't need to do this,
// you already have yours).
sqliteHelper helper = new sqliteHelper(getApplicationContext());
ArrayList<Income> your_array_list = helper.getAllIncome();
// This is the array adapter, it takes the context of the activity as a
// first parameter, the type of list view as a second parameter and your
// array as a third parameter.
ArrayAdapter<Income> arrayAdapter = new ArrayAdapter<Income>(
this,
android.R.layout.simple_list_item_1,
your_array_list );
lv.setAdapter(arrayAdapter);
}

Related

How to Set ListView Adapter

I need help to make listview adapter. Below is code please make the adapter both value name with roomid.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
RoomModel.java
public class RoomModel {
private String name, id, roomid;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getroomId() {
return roomid;
}
public void setroomId(String roomid) {
this.roomid = roomid;
}
}
try the following Adapter......
public class MyAdapter extends BaseAdapter {
Context con;
ArrayList<your type> mlist;
RoomModel sched;
public MyAdapter(Context con,ArrayList<your type> mlist )
{
this.con=con;
this.mlist=mlist;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mlist.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mlist[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
sched=mlist.get(position);
LayoutInflater inflater=(LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView=inflater.inflate(R.layout.your_layout,parent,false);
TextView tv1=(TextView)convertView.findViewById(R.id.your_textview);
tv1.setText(sched.getId());
TextView tv2=(TextView)convertView.findViewById(R.id.your_textview);
tv2.setText(sched.getName());
TextView tv3=(TextView)convertView.findViewById(R.id.your_textview);
tv3.setText(sched.getroomId());
return convertView;
}
}
and change the following code.
JSONArray rooms = jsonObject.getJSONArray("rooms");
for (int i = 0; i < rooms.length(); i++) {
JSONObject room = rooms.getJSONObject(i);
String name = room.optString("room");
String roomid = room.optString("roomid");
final RoomModel sched = new RoomModel();
sched.setName(name);
sched.setroomId(roomid);
CustomListViewValuesArr.add(sched);}
listView = (ListView) findViewById(R.id.ChatlistView);
MyAdapter adapter=new MyAdapter(this,CustomListViewValuesArr);
listView.setAdapter(adapter);
OK as requested by Sandeep, I will give you simple hint but I can't give you full codes that you can directly copy and paste. Just follow instructions
Create an XML file for single item of the list which may have certain elements as you need, for example It's single_item.xml which has 3 TextView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="#+id/tvId"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Sample Id"
android:textColor="#0414f4"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="10sp" />
<TextView
android:id="#+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginTop="10dp"
android:text="Sample Title"
android:textColor="#000"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="#+id/tvBody"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Sample body"
android:textSize="16sp"/>
</LinearLayout>
and after getting the reference of listView from main layout set the adapter like this, And here modelList is an ArrayList.
mAdapter = new CustomAdapter(MainActivity.this, R.layout.single_item, modelList);
mAdapter.notifyDataSetChanged();
mListView.setAdapter(mAdapter);
Then the class CustomAdapter looks like this
public class CustomAdapter extends ArrayAdapter<Model> {
ArrayList<Model> modelList;
Context context;
public CustomAdapter(Context context, int resource, ArrayList<Model> objects) {
super(context, resource, objects);
this.modelList = objects;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.single_item,parent,false);
}
// Lookup view for data population
TextView tvId = (TextView) convertView.findViewById(R.id.tvId);
TextView tvTitle = (TextView) convertView.findViewById(R.id.tvTitle);
TextView tvBody = (TextView) convertView.findViewById(R.id.tvBody);
// Populate the data into the template view using the data object
tvId.setText(String.valueOf(model.getId()));
tvTitle.setText(model.getroomId());
tvBody.setText(model.getName());
// Return the completed view to render on screen
return convertView;
}
}
NOTE : I have commented and made it simple as possible to help you. Hope this may help. You can comment if any problem raised.

list view item selected background changed , it changes other item also

i m new in list view , i want to item click on listview it change background color , it change but i after scroll it changes other item background view also. i cant find out where i am wrong ?
code snippet :
ListColorChange.java
package com.example.spinnerfilter;
public class ListColorChange extends Activity {
private ListView phproductinfo;
ArrayList<ProductInfo> arrayListProf;
ChangeColorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
init();
}
int mselected = -1;
public void init() {
phproductinfo = (ListView) findViewById(R.id.phlist);
arraylistInit();
adapter = new ChangeColorAdapter(ListColorChange.this, arrayListProf);
phproductinfo.setAdapter(adapter);
phproductinfo.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
mselected = position;
ProductInfo info = arrayListProf.get(position);
info.setOngoing(true);
adapter.notifyDataSetChanged();
}
});
}
private void arraylistInit() {
String name[] = { "India", "Austrai", "Xyxz", "Pask", "New", "India",
"Austrai", "Xyxz", "Pask", "New", "India", "Austrai", "Xyxz",
"Pask", "New", "India", "Austrai", "Xyxz", "Pask", "New",
"India", "India", "Austrai", "Xyxz", "Pask", "New", "India",
"India", "Austrai", "Xyxz", "Pask", "New", "India", "India",
"Austrai", "Xyxz", "Pask", "New", "India" };
arrayListProf = new ArrayList<ProductInfo>();
for (int i = 0; i < name.length; i++) {
ProductInfo info = new ProductInfo();
info.setDisplay_name(name[i]);
info.setOngoing(false);
arrayListProf.add(info);
}
}
public class ChangeColorAdapter extends BaseAdapter
{
public ChangeColorAdapter(ListColorChange listColorChange,
ArrayList<ProductInfo> arrayListProf) {
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayListProf.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arrayListProf.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
ViewHolder vh;
if (convertView == null) {
LayoutInflater inflater = LayoutInflater
.from(ListColorChange.this);
convertView = inflater.inflate(R.layout.productlist, null);
TextView product_name = (TextView) convertView
.findViewById(R.id.prod_name);
vh = new ViewHolder(convertView);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
if (arrayListProf != null && arrayListProf.size() > 0) {
ProductInfo pi = arrayListProf.get(position);
if (pi.getDisplay_name() != null) {
vh.product_name.setText(pi.getDisplay_name());
}
if (arrayListProf.get(position).isOngoing() && mselected == position) {
convertView.setBackgroundColor(Color.parseColor("#ff0000"));
}
}
return convertView;
}
class ViewHolder {
TextView product_name;
TextView qty;
TextView unit;
int position;
boolean ispu = false;
public ViewHolder(View view) {
// TODO Auto-generated constructor stub
product_name = (TextView) view.findViewById(R.id.prod_name);
qty = (TextView) view.findViewById(R.id.qty);
unit = (TextView) view.findViewById(R.id.unit);
}
}
}
}
xml file :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/phlist"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</ListView>
</LinearLayout>
This is the problem caused by the position at which click is not the same position after the scroll on ListView you can easily fix this by allowing your object to remember if it was selected by Onclick listnere
Assume this is the class you have whose type of list you have provided to the Adapter
class ProductInfo{
// here you already have your instance variables
boolean isSelected;
}
when you Onclick on an ProductInfo item make this instance variable of respective ProductInfo, true and change the background of the respective item in your Adapter which you must have extended from ArrayAdapter or BaseAdapter.
when you populate your List in ListView's adapter what you can check is if the isSelected is true than make respective item's background selected . otherwise don't
by doing so you will be independent of the position of the item with respective of the scroll. So your ProductInfo will retain the background change which was actually selected.
Update,
I am still right so i wrote a code snippet with output that you may check,
I have kept the code as simple as I can and wrote things in single file for simplicity, and the code is also available on github, where you check code properly
public class CustomListViewActivity extends Activity {
private ListView listView;
private ArrayList<ProductInfo> productInfos;
private ArrayAdapter<ProductInfo> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_list_view2);
initializeUI();
}
private void initializeUI() {
listView = (ListView)findViewById(R.id.CustomListViewActivity_listView_two);
productInfos = new ArrayList<>();
for (int i = 0; i < 50; i++) {
ProductInfo productInfo = new ProductInfo();
productInfo.setText("Product_1_"+i);
productInfos.add(productInfo);
}
adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_custom_one, productInfos);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ProductInfo productInfo = (ProductInfo) listView.getItemAtPosition(position);
productInfo.setSelected(true);
adapter.notifyDataSetChanged();
}
});
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<ProductInfo> a_productInfos;
private Context a_context;
private LayoutInflater a_layoutInflater;
public MyAdapter(Context context, int resource, ArrayList<ProductInfo> a_productInfos) {
super(context, resource, a_productInfos);
this.a_productInfos = a_productInfos;
this.a_context = context;
a_layoutInflater = LayoutInflater.from(this.a_context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = a_layoutInflater.inflate(R.layout.single_item_custom_one, parent, false);
holder = new ViewHolder();
holder.product_name = (TextView) row.findViewById(R.id.single_item_custom_one_textView);
holder.item_LinearLayout = (LinearLayout) row.findViewById(R.id.single_item_custom_one_linearLayout);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final ProductInfo productInfo = a_productInfos.get(position);
holder.product_name.setText(""+productInfo.getText());
if (productInfo.isSelected) {
holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ff44ff"));
}else {
holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
}
return row;
}
class ViewHolder {
TextView product_name;
LinearLayout item_LinearLayout;
}
#Override
public int getCount() {
return super.getCount();
}
}
private class ProductInfo {
private String text;
private boolean isSelected;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
}
activity_custom_list_view2.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/CustomListViewActivity_listView_two"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
single_item_custom_one.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/single_item_custom_one_linearLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/single_item_custom_one_textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeightSmall"
android:paddingEnd="?android:attr/listPreferredItemPaddingEnd"
android:paddingLeft="?android:attr/listPreferredItemPaddingLeft"
android:paddingRight="?android:attr/listPreferredItemPaddingRight"
android:paddingStart="?android:attr/listPreferredItemPaddingStart"
android:textAppearance="?android:attr/textAppearanceListItemSmall"
android:textColor="#000" />
</LinearLayout>
Output
Update the code
if (arrayListProf.get(position).isOngoing() && mselected ==position) {
convertView.setBackgroundColor(Color.parseColor("#ff0000"));
convertView.setTag(vh);
}

Nothings happening on clicking items of GridView

I am using GridView for displaying the categories , i have used ImageButton and a Text View in Grid View but I am not able to setOnItemClickListener on those items( Imean nothings Happening on Clicking it)
My code is
this is My Adapter for GridView
public class MyAdapter extends BaseAdapter{
private ArrayList<String> listJewel_name;
private ArrayList<Integer> listJewellery;
private Activity activity;
//private LayoutInflater inflater;
public MyAdapter(Activity activity,ArrayList<String> listJewel_name, ArrayList<Integer> listJewellery) {
super();
this.listJewel_name = listJewel_name;
this.listJewellery = listJewellery;
this.activity = activity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listJewel_name.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listJewel_name.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageButton imgViewJewel;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.tvtext);
view.imgViewJewel = (ImageButton) convertView.findViewById(R.id.picture);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listJewel_name.get(position));
view.imgViewJewel.setImageResource(listJewellery.get(position));
return convertView;
}
}
My activity.class is
GridView gridView;
Button add;
private MyAdapter mAdapter;
private ArrayList<String> listJewel_name;
private ArrayList<Integer> listJewellery;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_select_jewellery_option);
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new MyAdapter(this,listJewel_name, listJewellery);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridview);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
String shri=mAdapter.getItem(position);
Toast.makeText(SelectJewelleryOption.this, shri , Toast.LENGTH_SHORT).show();
}
});
}
My XML file is
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.myjewelbox.SquareImageButtonView
android:id="#+id/picture"
android:layout_width="match_parent"
android:layout_height="130dp"
android:scaleType="fitCenter"
android:clickable="true" />
<TextView
android:id="#+id/tvtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="10dp"
android:paddingRight="1dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_gravity="bottom"
android:textColor="#color/Golden"
android:background="#55000000"
android:focusable="false"
/>
</FrameLayout>
And I have set this XMl file to my Main XML file's GridView
Set ItemClickListener for items of GridView in it's adapter,instead of set an ItemClickListener directly for GridView.
view.imgViewJewel.setItemClickListener(activity);
In your adapter class, setOnClickListener on your convertView before return line.
convertView.setOnClickListener(new onClickListener(){
//In this method you can get the items same as you are getting in your
//adapter, as follow:-
String name=listJewel_name.get(position);
//or you can do whatever you want as now you have the whole view that is
//clicked, so you can event get its children or start a new activity or
//whatever you want
}
return converView;
Make Sure android:focusable="false" in your First Child of GridView Layout
and
GridViews can't handle clickable items. Button for example won't work. And also if you have any other non-clickable item, you have to make sure that you didn't set the property: clikable="true".
Refer below link - It is same as what you expect
http://www.androidhub4you.com/2013/07/custom-grid-view-example-in-android.html

Gridview onclick listener its not working

I am using gridview of layout,its not working after the grid view items in the list,it shows "throwIndexOutOfBoundsException" in logcat error.without onclick function if i use toast its working,if i give an onlcick function for next activity its not working
Gridviewadapter.java
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private Activity activity;
public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
super();
this.listginfy = listginfy;
this.listimage = listimage;
this.activity = (Activity) ginfyActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listginfy.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listginfy.get(position);
}
public int getItemId() {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewGinfy;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listginfy.get(position));
view.imgViewGinfy.setImageResource(listimage.get(position));
return convertView;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}
Mainactivity.java
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_ginfy);
prepareList();
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this,listginfy, listimage);
// Set custom adapter to gridview
gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mAdapter = results.get(position);
switch(mAdapter.getItemId())
{
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
});
}
public void prepareList()
{
listginfy = new ArrayList<String>();
listginfy.add("Prayers");
listginfy.add("Poojaroom");
listimage = new ArrayList<Integer>();
listimage.add(R.drawable.ginfyprayer);
listimage.add(R.drawable.poojaroom1);
}
}
Onclick function of gridview is not working
here i post my xml layout also.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:background="#drawable/border"
android:padding="5dp">
<ImageView
android:layout_height="64dp"
android:id="#+id/imageView1"
android:layout_width="64dp"
android:src="#drawable/icon"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:clickable="True">
</ImageView>
<TextView
android:text="TextView"
android:layout_height="wrap_content"
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_below="#+id/imageView1"
android:layout_marginTop="2dp"
android:layout_centerHorizontal="true"
android:textSize="18sp"
android:ellipsize="marquee"></TextView>
</RelativeLayout>
home_ginfy.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView
android:layout_height="wrap_content"
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:numColumns="auto_fit"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
android:clickable="True">
</GridView>
</LinearLayout>
you have a lot of error in your code.. (like android:clickable="True" in your layout >> remove that)
just for test, replace your code with:
// Implement On Item click listener
gridView.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
switch(position)
{
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
});
The getItemId for your adapter always return 0..
replace
mAdapter = results.get(position);
switch(mAdapter.getItemId())
by
switch(position)
I have been using something like this. In your case this should work.
public class GridviewAdapter extends BaseAdapter
{
private ArrayList<String> listginfy;
private ArrayList<Integer> listimage;
private Activity activity;
public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
super();
this.listginfy = listginfy;
this.listimage = listimage;
this.activity = (Activity) ginfyActivity;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listginfy.size();
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return listginfy.get(position);
}
public int getItemId() {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder
{
public ImageView imgViewGinfy;
public TextView txtViewTitle;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if(convertView==null)
{
view = new ViewHolder();
convertView = inflator.inflate(R.layout.gridview_row, null);
view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);
convertView.setTag(view);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (position){
case 1:
Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
startActivity(newActivity);
break;
case 2:
Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
startActivity(new1Activity);
break;
default:
Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
}
}
}
}
else
{
view = (ViewHolder) convertView.getTag();
}
view.txtViewTitle.setText(listginfy.get(position));
view.imgViewGinfy.setImageResource(listimage.get(position));
return convertView;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}

listview onclick android

I am creating an app that has a contacts list inside it. Currently the list works and displays all of my contacts just the way i want it. However i need to add a click function to them. I want to call them once i press one of them. How can i do that? I already have an onListItemClick method in the same activity due to an rss reader. How can i filter it out? Take a look at my code:
//Load contacts into ListView on people screen
contactListView = (ListView) findViewById(R.id.contactsListView);
contactstock = new ArrayList<ContactStock>();
mCursor = managedQuery(ContactsContract.Data.CONTENT_URI, null, Data.MIMETYPE + "='" + Phone.CONTENT_ITEM_TYPE + "'", null,
ContactsContract.Data.DISPLAY_NAME + " ASC");
int number = mCursor.getColumnIndex(Phone.NUMBER);
int name = mCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME);
while (mCursor.moveToNext()) {
String phName = mCursor.getString(name);
String phNumber = mCursor.getString(number);
contactstock.add(new ContactStock(phName, phNumber));
}
contactListView.setAdapter(new ContactListAdapter(MainActivity.this,
contactstock));
ContactStock.java:
public class ContactStock {
private String name;
private String number;
public ContactStock(String name, String number) {
this.name = name;
this.number = number;
}
public void setName(String name) {
this.name = name;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getNumber() {
return this.number;
}
}
ContactListAdapter.java:
public class ContactListAdapter extends ArrayAdapter {
private final Activity activity;
private final List stocks;
public ContactListAdapter(Activity activity, List objects) {
super(activity, R.layout.listview_detail_tab_contact_list, objects);
this.activity = activity;
this.stocks = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View rowView = convertView;
ContactStockView sv = null;
if (rowView == null) {
// Get a new instance of the row layout view
LayoutInflater inflater = activity.getLayoutInflater();
rowView = inflater.inflate(
R.layout.listview_detail_tab_contact_list, null);
// Hold the view objects in an object,
// so they don't need to be re-fetched
sv = new ContactStockView();
sv.name = (TextView) rowView.findViewById(R.id.contact_name);
sv.number = (TextView) rowView.findViewById(R.id.contact_number);
// Cache the view objects in the tag,
// so they can be re-accessed later
rowView.setTag(sv);
} else {
sv = (ContactStockView) rowView.getTag();
}
// Transfer the stock data from the data object
// to the view objects
ContactStock currentStock = (ContactStock) stocks.get(position);
sv.name.setText(currentStock.getName());
sv.number.setText(currentStock.getNumber());
// TODO Auto-generated method stub
return rowView;
}
protected static class ContactStockView {
protected TextView name;
protected TextView number;
}
}
My current listview code(for rss viewer):
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Uri uri = Uri.parse(links.get(position).toString());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
ListView row xml:
<?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:orientation="horizontal" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:src="#drawable/defaultavatar" />
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:text="Who am I"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/contact_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="000000000" />
</LinearLayout>
</LinearLayout>
I got the phone number from the contact i tapped by using this code:
contactstock.get(arg2).getNumber()
You should set both listviews and set onItemClickListener for each one.
ListView l1 = (ListView)findViewById(R.id.list1);
ListView l2 = (ListView)findViewById(R.id.list2);
// listener for the first one
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
// listener for the other
l2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
I think what you say is you are having 2 listview.
You can use setOnItemClickListener to the listview instead of using onListItemClick.
contactListView.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
}});

Categories

Resources