Grid view onclick is not working - java

I need to make ItemClickListener on grid view. I am adding buttons dynamically on gridvie. Using Base adapter. I need to onItemClickListener in my activity not on baseadapter class.
My xml code :
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp"
/>
DirectOrder class:
public class DIrectOrder extends Activity {
DbHelper db;
ArrayList<HashMap<String, String>> category = new ArrayList<HashMap<String, String>>();
ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
BaseAdapter baseAdapter;
LinearLayout categroyLayout;
String strCategory = "";
GridView grdView;
static String[] itemName = new String[10];;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setContentView(R.layout.cash_directorder);
db = new DbHelper(DIrectOrder.this);
grdView = (GridView) findViewById(R.id.gridview);
categroyLayout = (LinearLayout) findViewById(R.id.lay_category);
category = db.retrieve_category_name();
strCategory = category.get(0).get("name");
items = db.retrieve_item_details(strCategory);
for (int i = 0; i < category.size(); i++) {
Button butCategory = new Button(this);
butCategory.setText(category.get(i).get("name"));
butCategory.setId(Integer.parseInt(items.get(i).get("Id")));
categroyLayout.addView(butCategory);
}
Log.i("Item name ::::", "" + items.get(0).get("Item_Name"));
for (int i = 0; i < items.size(); i++) {
itemName[i] = items.get(i).get("Item_Name");
}
grdView.setAdapter(new categoryAdapter(this, itemName));
// I need on click of the gridview on here //
grdView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Log.i("Clciking", "Click");
}
});
}
}
My base adapter class:
public class categoryAdapter extends BaseAdapter {
private Context mContext;
String[] itemname;
public categoryAdapter(Context c, String[] itemname) {
mContext = c;
this.itemname = itemname;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return itemname.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#SuppressWarnings("null")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Button butCatrgory = new Button(mContext);
butCatrgory.setId(position);
butCatrgory.setHeight(android.view.ViewGroup.LayoutParams.MATCH_PARENT);
butCatrgory.setText(itemname[position]);
return butCatrgory;
}
}

Add the following lines in your MyBaseAdapter class' getview method after butCatrgory.setId(position);
butCatrgory.setEnabled(false);
butCatrgory.setClickable(false);

Button are by default focusable and that should prevent OnItemClickListener to be called. Add
butCatrgory.setFocusable(false);
inside your getView

Related

Button setOnClickListener in a ListView

I'm trying to get the onclick event of a button inside a listview, but it's not working
fragment_contact.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="404dp"
android:layout_weight="0.64"
android:orientation="horizontal"
android:paddingBottom="40dip" >
<ListView
android:id="#+id/contactlistview"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="fill"
android:layout_weight="10"
android:textSize="5pt"
android:visibility="visible" />
</LinearLayout>
fragment_contact_content.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="vertical"
android:weightSum="1">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/btn_edit_contact"
android:layout_gravity="right" />
</LinearLayout>
FragmentContact.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_contact, container, false);
ListAdapter adapter_contact = new SimpleAdapter(
getActivity(), allcontact,
R.layout.fragment_contact_content, new String[]{"name", "level", "function", "phone", "email"},
new int[]{R.id.contact, R.id.level, R.id.function, R.id.phone, R.id.email});
listview_contact = (ListView) view.findViewById(R.id.contactlistview);
listview_contact.setItemsCanFocus(true);
listview_contact.setAdapter(adapter_contact);
Button btn_edit_contact = (Button) view.findViewById(R.id.btn_edit_contact);
btn_edit_contact.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("Do something");
}
});
return view;
}
I also tried inflating fragment_contact_content.xml but the button still does nothing.
Use custom Adapter and in getView Write your code
public class MealAdapter extends BaseAdapter{
private int mHour, mMinute;
int minutes,hour;
String strtime;
customButtonListener customListner;
private Context context;
private List<Meal> rowItems;
public MealAdapter(Context context, List<Meal> rowItems) {
this.context = context;
this.rowItems = rowItems;
}
#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));
}
private class OptionHolder
{
ImageButton btn_time;
ImageButton btn_delete;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
// TODO Auto-generated method stub
final OptionHolder holder;
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.meal_list_item, null);
holder = new OptionHolder();
holder.btn_time= (ImageButton) convertView.findViewById(R.id.btn_time);
holder.btn_delete =(ImageButton) convertView.findViewById(R.id.btn_delete_meal);
convertView.setTag(holder);
}
else
{
holder = (OptionHolder) convertView.getTag();
}
final Meal row_pos=rowItems.get(position);
row_pos.setMeal("");
row_pos.setDetail("");
holder.ed_meal.setText(row_pos.getMeal());
holder.ed_detail.setText(row_pos.getDetail());
holder.ed_time.setText(row_pos.getTime());
holder.btn_time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
final Calendar c = Calendar.getInstance();
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
// Launch Time Picker Dialog
TimePickerDialog tpd = new TimePickerDialog(MealPlannerFragment.con,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// Display Selected time in textbox
strtime=(hourOfDay + ":" + minute);
row_pos.setTime(strtime);
row_pos.setMunite(minute);
row_pos.setHour(hourOfDay);
holder.ed_time.setText(row_pos.getTime());
}
}, mHour, mMinute, false);
tpd.show();
}
});
holder.btn_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (customListner != null) {
customListner.onButtonClickListner(position,row_pos);
}
}
});
return convertView;
}
public interface customButtonListener {
public void onButtonClickListner(int position,Meal row_pos);
}
public void setCustomButtonListner(customButtonListener listener) {
this.customListner = listener;
}
}
`
you can not get Listview cell's Button event directly in onCreateView. you have to make CustomAdapter class for that.
you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public MyCustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return list.get(pos).getId();
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.fragment_contact_content, null);
}
//Handle button and add onClickListener
Button editBtn = (Button)view.findViewById(R.id.btn_edit_contact);
editBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
//some other task
notifyDataSetChanged();
}
});
return view;
}
}
Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_activity);
//generate list
ArrayList<String> list = new ArrayList<String>();
list.add("item1");
list.add("item2");
//instantiate custom adapter
MyCustomAdapter adapter = new MyCustomAdapter(list, this);
//handle listview and assign adapter
ListView lView = (ListView)findViewById(R.id.my_listview);
lView.setAdapter(adapter);
}
You can refer this link: http://www.c-sharpcorner.com/UploadFile/9e8439/create-custom-listener-on-button-in-listitem-listview-in-a/
just handle on click listener inside getview where you find the button using findviewbyid
I hope it helps!

No Solution for NullPointerException

I want to create a BaseAdapter for a ListView. From my database I get an ArrayList that contains the entries for the ListView. The onCreate Method works fine but if I click the button to insert data to the database and display it in the ListView my app crashes. I'm looking for the Solution but can't find it. Maybe you do.
Logcat says there is a NullPointerException at the point where the text of the TextView is set (LaunchActivity$CustomAdapter.getView).
LaunchActivity.java
public class LaunchActivity extends Activity {
ImageView buttonAdd;
EditText insertText;
SubjectAdapter helper;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launch);
helper=new SubjectAdapter(this);
listView = (ListView) findViewById(R.id.listViewLaunch);
listView.setEmptyView(findViewById(R.id.emptyView));
insertText = (EditText) findViewById(R.id.editTextLaunch);
buttonAdd = (ImageView) findViewById(R.id.imageViewLaunch);
buttonAdd.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String subject = insertText.getText().toString();
long id=helper.insertData(subject);
if(id<0){
Log.d("Personal", "insertData not successfull");
} else {
// Hiding the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(insertText.getWindowToken(), 0);
// loading ListView with newly added data
loadListViewData();
Log.d("Personal", "insertData successfull");
Toast.makeText(LaunchActivity.this, subject+" hinzugefĆ¼gt", Toast.LENGTH_LONG).show();
insertText.setText("");
}
}
});
loadListViewData();
}
public void loadListViewData() {
// database handler
SubjectAdapter helper = new SubjectAdapter(getApplicationContext());
// Get Data from Database and set ArrayList
ArrayList<String> list = (ArrayList<String>) helper.getData();
// Creating adapter for ListView
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), list);
// attaching data adapter to ListView
listView.setAdapter(adapter);
}
class CustomAdapter extends BaseAdapter{
ArrayList<String> list = new ArrayList<String>();
Context context;
// Constructor
CustomAdapter(Context context, ArrayList<String> list){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
// LayoutInflation and Recycling
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_listview, parent, false);
}
TextView myText = (TextView) findViewById(R.id.textList);
// Get String from ArrayList
String temp = list.get(position);
// Set Text for TextView inside ListView
myText.setText(temp);
return row;
}
}
}
If row is null you have to inflate and assign the result to row!
row = inflater.inflate(R.layout.item_listview, parent, false);
Also you'll want to get myText from row:
TextView myText = (TextView) row.findViewById(R.id.textList);
First create object of ArrayList<String> in getData() and check code below:
public void loadListViewData() {
// database handler
SubjectAdapter helper = new SubjectAdapter(getApplicationContext());
// Get Data from Database and set ArrayList
ArrayList<String> list = helper.getData();
// Creating adapter for ListView
CustomAdapter adapter = new CustomAdapter(getApplicationContext(), list);
// attaching data adapter to ListView
listView.setAdapter(adapter);
}
class CustomAdapter extends BaseAdapter{
ArrayList<String> list = null;
Context context;
// Constructor
CustomAdapter(Context context, ArrayList<String> list){
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
// LayoutInflation and Recycling
if(row == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.item_listview, parent, false);
}
TextView myText = (TextView) findViewById(R.id.textList);
// Get String from ArrayList
String temp = list.get(position);
// Set Text for TextView inside ListView
myText.setText(temp);
return row;
}
}
and make sure return type of getData() will be ArrayList<String>
hope it will help.

How to get values from a multichoice listview alertdialog

I have an ArrayList of Person class containing age and name of the person. In the adapter (extends BaseAdapter), I have two TextViews(for setting the values of age and name) and a checkbox. This is needed to be inflated into alert dialog.
How can I implement this using multichoice of the alert dialog.
Also I did look at some examples but did not understand about the boolean[] values attribute in the alert dialog, this is the code I have so far but it still needs to implement that multichoice mode..
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true"
android:choiceMode="multipleChoice">
</ListView>
My alertdialog..
AlertDialog.Builder ab=new AlertDialog.Builder(CustomListActivity.this);
LayoutInflater linf=(LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View v1=linf.inflate(R.layout.dialog_list, null);
ab.setView(v1);
//ab.setTitle("Select a group");
lv=(ListView) v1.findViewById(R.id.listView1);
ma=new MyAdapter(CustomListActivity.this, plist);
lv.setAdapter(ma);
And MYAdapter ..
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
}
Change your adapter to following and just call getSelected on adapter.
public class MyAdapter extends BaseAdapter
{
Context ctx;
ArrayList<Person> plist;
LayoutInflater linf;
public PersonHolder ph=null;
private ArrayList<Integer> selected=new ArrayList<Integer>();
public MyAdapter(Context ctx, ArrayList<Person> plist) {
super();
this.ctx = ctx;
this.plist = plist;
}
public class PersonHolder
{
public TextView age;
public TextView name;
public CheckBox check;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return plist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return plist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
// TODO Auto-generated method stub
linf=(LayoutInflater) ctx.getSystemService(ctx.LAYOUT_INFLATER_SERVICE);
if(convertView==null)
{
convertView=linf.inflate(R.layout.row_item, null);
ph=new PersonHolder();
ph.age=(TextView) convertView.findViewById(R.id.text1);
ph.name=(TextView) convertView.findViewById(R.id.text2);
ph.check=(CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(ph);
}
else
{
ph=(PersonHolder) convertView.getTag();
}
Person p=(Person) getItem(position);
ph.age.setText(p.getAge());
ph.name.setText(p.getName());
ph.check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// if(ph.check.isChecked())
// {
ph.check.setSelected(arg1);
if(arg1){
selected.add(position);
}else{
selected.remove(position);
}
// }
// else
// {
// ph.check.setSelected(false);
// }
}
});
return convertView;
}
public ArrayList<Integer> getSelected(){
return selected;
}
}
I have created a multichoice dialog myself, this is what i am doing, basically you need to catch each click to the listview and memorize whatever it is you selected/set there.
private void startDayPickerDialog() {
String[] days = getActivity().getResources().getStringArray(R.array.dayNames);
days = Arrays.copyOf(days, 7);
final Adapter a = new Adapter(getActivity());
AlertDialog d = new AlertDialog.Builder(getActivity())
.setTitle(R.string.repeat)
.setAdapter(a, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).setPositiveButton(R.string.done, new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
}).create();
d.getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> lv, View view, int position, long id) {
CheckBox cb = (CheckBox)view.findViewById(R.id.checkbox);
cb.setChecked(!cb.isChecked());
a.getItem(position).setChecked(!a.getItem(position).isChecked());
}
});
d.setCanceledOnTouchOutside(true);
d.show();
}

Set onItemClick to Custom adapter ListView

When I had problems trying to fix the position of my listView items to the desired intent when filtered, and got info I could override the problem using a custom adapter, I have done that but I do not know how to assign the clicks to each items, please check below code:
public class IndexPageActivity extends Activity {
ListView listView;
EditText editTextB;
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener((OnItemClickListener) this);
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements OnItemClickListener{
ArrayList<SingleRow> pagelist;
Context context;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<SingleRow>();
Resources res = c.getResources();
String [] pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(new SingleRow(pagedatas[i]));
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public Object getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return row;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int i, long arg3) {
// TODO Auto-generated method stub
}
}
I will appreciate any help given. Thank Yhu!
EDIT
Will this work?
if (index == 0) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page1.html");
startActivity(i);
} else if (index == 1) {
Intent i = new Intent(this, WebViewActivity.class);
i.putExtra("keyHTML", "file:///android_asset/page2.html");
startActivity(i);
Edited ALL
I just got what you need, I added a filter to your baseAdapter and then on text change within the editText You filter the listView and then you go to the activity needed.
here is the full code but you need to bare in mind that I have changed the following:
I changed the pageList to ArrayList instead of
There is a bug in filtering that when I erase what I wrote in the EditText it doesnt update the ListView, you need to figure out why.
I changed the returned value of the function getItem(int i) from Object to String
Within the onItemClick you have to search for the name instead of the position.
here is the code:
public class IndexPageActivity extends Activity implements OnItemClickListener{
ListView listView;
EditText editTextB;
PagesAdapter adapter1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
adapter1 = new PagesAdapter(this);
listView.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listView.setOnItemClickListener(this);
editTextB.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
IndexPageActivity.this.adapter1.getFilter().filter(cs.toString());
adapter1.notifyDataSetChanged();
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Intent i;
String name = adapter1.getItem(position);
Log.d("id", name);
if (name.equals("Item1"))
{
i = new Intent(this, anActivity.class);
startActivity(i);
}
else if (name.equals("Item2"))
{
i = new Intent(this, anActivity2.class);
startActivity(i);
}
}
}
class SingleRow {
String pagedata;
SingleRow(String pagedata){
this.pagedata=pagedata;
}
}
class PagesAdapter extends BaseAdapter implements Filterable{
ArrayList<String> pagelist;
List<String> arrayList;
Context context;
String [] pagedatas;
PagesAdapter(Context c){
context=c;
pagelist = new ArrayList<String>();
Resources res = c.getResources();
pagedatas = res.getStringArray(R.array.pages_data);
for (int i=0;i<463;i++){
pagelist.add(pagedatas[i]);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return pagelist.size();
}
#Override
public String getItem(int i) {
// TODO Auto-generated method stub
return pagelist.get(i);
}
#Override
public long getItemId(int i) {
// TODO Auto-generated method stub
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewG) {
// TODO Auto-generated method stub
LayoutInflater inflater=(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row=inflater.inflate(R.layout.single_row,viewG,false);
TextView pagetitle = (TextView) row.findViewById(R.id.textViewRow);
String temp=pagelist.get(i);
pagetitle.setText(temp);
return row;
}
public class filter_here extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
// TODO Auto-generated method stub
FilterResults Result = new FilterResults();
// if constraint is empty return the original names
if(constraint.length() == 0 ){
Result.values = pagelist;
Result.count = pagelist.size();
return Result;
}
ArrayList<String> Filtered_Names = new ArrayList<String>();
String filterString = constraint.toString().toLowerCase();
String filterableString;
for(int i = 0; i<pagelist.size(); i++){
filterableString = pagelist.get(i);
if(filterableString.toLowerCase().contains(filterString)){
Filtered_Names.add(filterableString);
}
}
Result.values = Filtered_Names;
Result.count = Filtered_Names.size();
return Result;
}
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
// TODO Auto-generated method stub
pagelist = (ArrayList<String>) results.values;
notifyDataSetChanged();
}
}
#Override
public Filter getFilter() {
// TODO Auto-generated method stub
return new filter_here();
}
}
Two different ways for it:
1) If you want to use something like this at onCreate of your activity;
listView.setOnItemClickListener((OnItemClickListener) this);
You should implement OnItemClickListener to your activity:
IndexPageActivity extends Activity implements OnItemClickListener
and implement its onItemClick method at your activity. (also remove OnItemClickListener interface from your custom adapter)
2) You can simply use below without implementing OnItemClickListener to any class:
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: handle row clicks here
}
I suggest 2nd option. That is easier.
Edit: This not relevant to your problem but you should reuse your views/rows at listView. Change your getView method to:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.single_row, parent, false);
} else {
view = convertView;
}
TextView pagetitle = (TextView) view.findViewById(R.id.textViewRow);
SingleRow temp=pagelist.get(i);
pagetitle.setText(temp.pagedata);
return view;
}
Set your setOnItemClickListenerlike this:
#Override
protected void onCreate(Bundle savfedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.indexpage);
listView = (ListView) findViewById(R.id.pageList);
editTextB = (EditText) findViewById(R.id.searchB);
listView.setAdapter(new PagesAdapter(this));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Your code here
//int position is the index of the list item you clicked
//use it to manipulate the item for each click
}
});
}

Android custom listview row wont let me add

I have a listview which is working fine just using simple_list_view1. But now I need to add an icon to the left. So i've created a iconrow.xml in res/layout/. When I try and set that as the layout it errors and wont let me use android.R.layout.iconrow,. Clearly i'm doing something wrong here! It's an array being built up that will populate the data.
My xml is:
<?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="wrap_content"
android:orientation="horizontal">
<ImageView
android:id="#+id/icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#android:drawable/ic_delete" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
My code is:
Cursor c = db.rawQuery(SQLStatement, null);
if(c.getCount() != 0) {
Log.e("LocationListView", "Found Items");
c.moveToFirst();
ArrayList mItemName = new ArrayList();
final ArrayList mItemID = new ArrayList();
c.moveToFirst();
while(!c.isAfterLast()) {
mItemName.add(c.getString(c.getColumnIndex("Name")));
mItemID.add(c.getString(c.getColumnIndex(ColType)));
c.moveToNext();
}
rowCount = mItemName.size();
listView = (ListView) findViewById(R.id.lvLocation);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.iconrow, android.R.id.text1, mItemName);
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(adapter);
listView.setClickable(true);
The error is on the android.R.layout.iconrow
Any help will be appreciated.
Tom
EDIT: Here is my code now - The errors on tv.setText(mItemName.get(arg0).toString());
c.moveToFirst();
final ArrayList<String> mItemID = new ArrayList<String>();
c.moveToFirst();
while(!c.isAfterLast()) {
mItemName.add(c.getString(c.getColumnIndex("Name")));
mItemID.add(c.getString(c.getColumnIndex(ColType)));
c.moveToNext();
}
rowCount = mItemName.size();
listView = (ListView) findViewById(R.id.lvLocation);
// final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// R.layout.iconrow, R.id.text, mItemName);
tv.setText(mItemName.get(arg0).toString());
int[] colors = {0, 0xFFFF0000, 0};
listView.setDivider(new GradientDrawable(Orientation.RIGHT_LEFT, colors));
listView.setDividerHeight(1);
listView.setAdapter(new CustomAdapter());
listView.setClickable(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object o = listView.getItemAtPosition(position);
String StationObjectID = mItemID.get(position);
Intent SwapPage = new Intent(arg1.getContext(), LocationListView.class);
SwapPage.putExtra("ID", StationObjectID);
SwapPage.putExtra("Type", Type);
startActivityForResult(SwapPage, 0);
}
});
} else {
Log.e("LocationListView", "Not Found Items");
Context context = getApplicationContext();
CharSequence text = "No data returned";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
db.close();
}
public void goBack(View view) {
if(Global.returnPage.equals("MainPage")) {
Intent addItem = new Intent(view.getContext(), MainPage.class);
startActivityForResult(addItem, 0);
} else {
Intent addItem = new Intent(view.getContext(), LocationListView.class);
addItem.putExtra("Type", Global.stepListType);
Log.e("PushThrough", Global.stepListType);
addItem.putExtra("ID", Global.stepListID);
Log.e("PushThrough", Global.stepListID);
startActivityForResult(addItem, 0);
}
}
public void addItem(View view){
Intent addItem = new Intent(view.getContext(), AddItem.class);
addItem.putExtra("Count", rowCount);
if(Adding.equals("Building")){
addItem.putExtra("Type", "0");
} else if(Adding.equals("Room")){
addItem.putExtra("Type", "1001");
addItem.putExtra("PrevID", dataID);
} else if (Adding.equals("Area")){
addItem.putExtra("Type", "532");
addItem.putExtra("PrevID", dataID);
}
startActivityForResult(addItem, 0);
}
public void onResume()
{
super.onResume();
Log.e("Tom", "resumed");
}
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return mItemName.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return v;
}
}
}
Create custom Adapter as
class CustomAdapter extends BaseAdapter
{
#Override
public int getCount() {
// TODO Auto-generated method stub
return mItemName.size;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
LayoutInflater inf=getLayoutInflater();
View v=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return v;
}
}
and then set this to your list as
listview.setAdapter(new CustomAdapter());
Another implementation is as follows:
public class CustomArrayAdapter extends ArrayAdapter<Applications>{
private MainActivity context;
private int layoutResourceId;
private int textresourceId;
ArrayList<Applications> objects=null;
public CustomArrayAdapter(MainActivity context, int resource,ArrayList<Applications> objects) {
super(context, resource);
this.context = context;
this.layoutResourceId = resource;
this.objects = objects;
Log.d("CustomArrayAdapter","Was here!!");
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return objects.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inf=getLayoutInflater();
View convertView=inf.inflate(R.layout.iconrow, arg2,true);
ImageView iv=(ImageView)v.findViewById(R.id.icon);
TextView tv=(TextView)v.findViewById(R.id.text);
return convertView;
}
}

Categories