Hello guys i am trying to add a search functionality in my activity that uses a listView to show vehicle information. I tried many solution but none work for me.
Actually i have added a textView in VehicleActivity & i want to filter the content of my listView when user type something in textView.
this the code of VehicleActivity
public class VehicleActivity extends Activity
{
//The PlaceHolder For The View's
ListView listView;
private ListAdapter mAdapter;
//Static Variable For Passing The VehicleActivity Context To SessionExpired()
public static Context mContext;
//public ImageView img_arrow;
public int context_menu_index;
//Alert DialogBox
public AlertDialog AltDialog;
public boolean CDialog_value = false; //Used when command of immoblize & De-Imoblize use fired
//Exception Handling
static PostException PstExp;
//Text View
EditText editsearch;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState)
{
try
{
Log.d("VA OnC", "Before Super");
super.onCreate(savedInstanceState);
mContext = getBaseContext();
setTitleBar(); //Setting The Title Bar
setContentView(R.layout.activity_vehicle); //Passing The XML Layout
//Getting Infromation From Parent Activity
Intent intent_veh = getIntent();
User_ID = intent_veh.getIntExtra("UID", 0); //UserId
session_key = intent_veh.getStringExtra("Key"); //Session Key
permissions = new int [(intent_veh.getIntArrayExtra("Rights")).length]; //Permissions Length
permissions = intent_veh.getIntArrayExtra("Rights"); //Permissions Assignment
//To Overwrite The Last Value Of The Variables
EmptyActivity = false;
//Initializing GetVehicleList Object
obj_GVL = new GetVehicleList(VehicleActivity.this, User_ID, session_key);
//Calling The Method That Will Fetch Information From Server
obj_GVL.getVehicleInfo();
Log.d("VA ", "Before EA Check");
if( EmptyActivity == false )
{
//Passing XML layout To ListView
Log.d("VA ", "Before listView = (ListView) findViewById(R.id.list_view)");
listView = (ListView) findViewById(R.id.list_view);
Log.d("VA ", "Before listView.setAdapter(new EfficientAdapter(this))");
mAdapter = new EfficientAdapter(this);
listView.setAdapter(mAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
//listView.setAdapter(new EfficientAdapter(this));
//Search Box Code Start
editsearch = (EditText) findViewById(R.id.search);
//Search Box Code End
Log.d("VA ", "Before listView.setOnItemClickListener()");
Log.d("VA ", "Before VehicleList.Location[0] =");
}
}
catch( Exception e)
{
//Some Code
}
catch(Error e2)
{
//Some Code
}
}
//Some code
}
This is code of My Adapter which is part of Vehicle Activity
//Passing Actual Data To PlaceHolder Of ListView
private class EfficientAdapter extends BaseAdapter
{
private LayoutInflater mInflater;
public EfficientAdapter(Context context)
{
//mInflater = LayoutInflater.from(context);
}
public int getCount()
{
return VehicleList.Vehicle_ID.length;
//return GetVehicleList.ID.length;
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(final int position, View convertView, ViewGroup parent)
{
ViewHolder holder;
try
{
if (convertView == null)
{
mInflater = (LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.three_col_row, null);
holder = new ViewHolder();
holder.text1 = (TextView) convertView.findViewById(R.id.imei);
holder.text2 = (TextView) convertView.findViewById(R.id.status);
holder.text3 = (TextView) convertView.findViewById(R.id.location);
holder.text4 = (TextView) convertView.findViewById(R.id.speed);
holder.text5 = (TextView) convertView.findViewById(R.id.date);
holder.img_option = (ImageView) convertView.findViewById(R.id.img_arrow);
convertView.setTag(holder);
holder.img_option.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
VehicleActivity.this.registerForContextMenu(listView);
VehicleActivity.this.openContextMenu(listView);
VehicleActivity.this.context_menu_index = VehicleActivity.this.listView.getPositionForView(v);
}
});
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.img_option.setFocusable(true);
holder.img_option.setClickable(true);
holder.img_option.setTag(holder);
//Setting The Font Style
holder.text1.setTypeface(null, Typeface.BOLD);
holder.text2.setTypeface(null, Typeface.ITALIC);
//Passing The Actual Values To TextViews
holder. text1.setText("ID: " +VehicleList.IMEI[position]);
holder.text2.setText("Status: " +VehicleList.Status[position]);
holder.text3.setText("Location: " +VehicleList.Location[position]);
holder.text4.setText("Speed: " +VehicleList.Speed[position]);
holder.text5.setText("Date: " +VehicleList.Date[position]);
convertView.setBackgroundColor(position % 2 == 0 ? Color.parseColor("#eaeaea") : Color.parseColor("#d3e3f3"));
}
catch( Exception e)
{
PstExp = new PostException("VA.EA.GETVEW Ln:830", //Block
(e.getMessage() == null)? "null": "Android App VA.EA.GETVEW() \n"+e.getMessage().toString(), //Message
(e.getStackTrace() == null)? "null": "Android App VA.EA.GETVEW() \n"+e.getStackTrace().toString(), //Stack Trace
(e.getCause() == null)? "null": "Android App VA.EA.GETVEW() \n"+e.getCause().toString() ); //Inner Exception
}
catch(Error e2)
{
PstExp = new PostException("VA.EA.GETVEW Ln:837", //Block
(e2.getMessage() == null)? "null": "Android App VA.EA.GETVEW() \n"+e2.getMessage().toString(), //Message
(e2.getStackTrace() == null)? "null": "Android App VA.EA.GETVEW() \n"+e2.getStackTrace().toString(), //Stack Trace
(e2.getCause() == null)? "null": "Android App VA.EA.GETVEW() \n"+e2.getCause().toString() ); //Inner Exception
}
return convertView;
}
public class ViewHolder
{
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
ImageView img_option;
}
}
this the code of VehicleList
public class VehicleList
{
public static int[] Vehicle_ID;
public static String[] IMEI;
public static String[] Status;
public static String[] Location;
public static String[] Speed;
public static String[] Date;
public static Double[] Latitude;
public static Double[] Longitude;
String error="", msg="";
}
From your question, what I have understood is, you need to implement search functionality when you enter the text in Search edit box. So the above code is working perfectly i guess(at least initially, when the activity is loaded for the first time). In your case you need to add textChangeListener for the edit text box as follows.
editsearch.addTextChangedListener(this);
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
Move these lines in to a method,
mAdapter = new EfficientAdapter(this);
listView.setAdapter(mAdapter);
listView.setTextFilterEnabled(true);
and call the method inside
public void onTextChanged(CharSequence s, int start, int before, int count)
Hope this helps.
Related
I have a TextView outside ListView and i need to add prices when the plus button (ie,quantity is incremented )in ListView is clicked.In my program i am not able to add prices when new position ListView button is clicked.I need to find the total price to be payed by the customer when plus button is clicked in ListView
public class ListAdapter1 extends BaseAdapter {
public int qty=1;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
private TextView total;
private String[] listViewItems,prices,weight;
TypedArray images;
public static int pValue;
private Context context;
public static boolean t=false;
CustomButtonListener customButtonListener;
public void setTextView(TextView total)
{
this.total = total;
}
public ListAdapter1(Context context, String[] listViewItems, TypedArray images, String[] weight, String[] prices) {
this.context = context;
this.listViewItems = listViewItems;
this.images = images;
this.prices=prices;
this.weight=weight;
}
public void setCustomButtonListener(CustomButtonListener customButtonListner)
{
this.customButtonListener = customButtonListner;
}
#Override
public int getCount() {
return 5;
}
#Override
public String getItem(int position) {
return listViewItems[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
View row;
final ListViewHolder listViewHolder;
if(convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.product,parent,false);
listViewHolder = new ListViewHolder();
listViewHolder.tvProductName = (TextView) row.findViewById(R.id.tvProductName)
listViewHolder.tvPrices = (TextView) row.findViewById(R.id.tvProductPrice);
listViewHolder.btnPlus = (ImageButton) row.findViewById(R.id.ib_addnew);
listViewHolder.edTextQuantity = (EditText) row.findViewById(R.id.editTextQuantity);
listViewHolder.btnMinus = (ImageButton) row.findViewById(R.id.ib_remove);
row.setTag(listViewHolder);
}
else
{
row=convertView;
listViewHolder= (ListViewHolder) row.getTag();
}
try{
listViewHolder.edTextQuantity.setText(quantity.get(position) );
}catch(Exception e){
e.printStackTrace();
}
listViewHolder.btnMinus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
if (mValue <=0) {
System.out.println("not valid");
mValue=0;
listViewHolder.edTextQuantity.setText("" +mValue);
}
else{
pValue=pValue/mValue;
mValue--;
pValue=pValue*mValue;
total.setText(String.valueOf(pValue));
System.out.println("mvalue after reducing-----------"+mValue);
System.out.println("pvalue-----------"+pValue);
listViewHolder.edTextQuantity.setText( "" +mValue );
}
}
});
listViewHolder.btnPlus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, " " + position, Toast.LENGTH_SHORT).show();
int mValue = Integer.parseInt(listViewHolder.edTextQuantity.getText().toString());
pValue=Integer.parseInt(listViewHolder.tvPrices.getText().toString());
mValue++;
listViewHolder.edTextQuantity.setText("" + mValue);
System.out.println("mValue after increment---" + mValue);
pValue=pValue*mValue;
System.out.println("pvalue-----------"+pValue);
total.setText(String.valueOf(pValue));
}
});
return row;
}
I need to get total price when any of the ListView button is clicked.
First you need to store value in HashMap<> when user click the plus and minus button.
Then sum the all values in HashMap.
For Example
try{
int sum = 0;
for(HashMap<String, String> map : arrayList) {
sum += Integer.parseInt(map.get("mark"));
}
} catch (Exception e) {
//Manage your exception
}
// sum has the value for the marks total.
System.out.println("Total Marks: "+sum);
Refere my previous answer Here
For that you need to create interface which notify in activity where you want that count.
put snippet in adapter to initialize interface and setter.
public interface IEvent {
void onItemChange(int count);
}
private IEvent iEvent;
//setter method for interface
public void setQuanityEvent(IEvent ievent) {
this.lastPageHandler = handler;
}
put this code in btnMinus.setOnClickListener
//if ievent interface variable register via set
if (ievent != null) {
//pValue is quality COUNT you want to send outside listview.
ievent.onItemChange(pValue);
}
activity code after creating adapter instance
//ListAdapter1 adapter = new ListAdapter1(your params);
adapter.setQuanityEvent(new ListAdapter1.IEvent() {
#Override
public void onItemChange(int count) {
}
}
});
I have 3 arraylist that i have combined to show in listview. Wehen i click on to generate listview, it works fine the first time but when i hit back and then click the button again, the listview shows nothing. Not sure what is cause it. I checked other post but couldnt find an answer. I am not too good with Arraylist so any details would be greatly appreciated.
I have also noticed this message in Log cat. not sure what it means.
onVisibilityChanged() is called, visibility : 0
public class Edit extends Activity implements OnItemClickListener {
private int pic;
public String filename ="User Info";
//Declaring SHareddPreference as userprofile
static SharedPreferences userprofile;
ListView listView;
List<RowItem> rowItems;
// String[] titles, descriptions;
File imgpath=null;
Context context=this;
CustomListAdapter adapter;
private List<String> Titles = new ArrayList<String>();
private List<String> Actions = new ArrayList<String>();
private List<Bitmap> Images = new ArrayList<Bitmap>();
int x;
int y=1;
int z=1;
static int a=1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aname);
listView = (ListView)findViewById(R.id.listing);
userprofile = getSharedPreferences(filename,0);
Intent pdf=getIntent();
pic= userprofile.getInt("lastpic",pic);
x=pic;
Log.d("editpic",new Integer(pic).toString());
while(y!=x){
String comment = commentresult();
Titles.add(comment);
y++;
Log.d("y",new Integer(y).toString());
}
while(z!=x){
String act = actionresult();
Actions.add(act);
z++;
Log.d("z",new Integer(z).toString());}
while(a!=x){
Bitmap photo = getbitmap();
Images.add(photo);
a++;
Log.d("a",new Integer(a).toString());}
Titles.toArray();
Actions.toArray();
Images.toArray();
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < Images.size(); i++) {
RowItem item = new RowItem(Images.get(i), Titles.get(i),Actions.get(i));
rowItems.add(item);
}
Log.d("TAG", "listview null? " + (listView == null));
CustomListAdapter adapter = new CustomListAdapter(this,
R.layout.aname_list_item, rowItems);
Log.d("TAG", "adapter=null? " + (adapter == null));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
listView.setOnItemClickListener(this);
}
public static Bitmap getbitmap() {
String photo1 =userprofile.getString("picpath"+a, "");
File imgpath=new File(photo1);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bmp=DecodeImage.decodeFile(imgpath, 800, 1000, true);
bmp.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Bitmap photo2=bmp;
return photo2;
}
#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();
}
public String commentresult()
{
// String com2 = null;
// while(y!=x){
String comment=userprofile.getString("comment"+y, "");
String com1=comment;
String com2=com1;
// }
return com2;
}
public String actionresult()
{
// String act2 = null;
// while(y!=x){
String action=userprofile.getString("action"+z, "");
String act1=action;
String act2=act1;
// }
return act2;
}
private static final long delay = 2000L;
private boolean mRecentlyBackPressed = false;
private Handler mExitHandler = new Handler();
private Runnable mExitRunnable = new Runnable() {
#Override
public void run() {
mRecentlyBackPressed=false;
}
};
#Override
public void onBackPressed() {
//You may also add condition if (doubleBackToExitPressedOnce || fragmentManager.getBackStackEntryCount() != 0) // in case of Fragment-based add
if (mRecentlyBackPressed) {
mExitHandler.removeCallbacks(mExitRunnable);
mExitHandler = null;
super.onBackPressed();
}
else
{
mRecentlyBackPressed = true;
Toast.makeText(this, "press again to exit", Toast.LENGTH_SHORT).show();
mExitHandler.postDelayed(mExitRunnable, delay);
}
}
#Override
public void onDestroy() {
// Destroy the AdView.
super.onDestroy();
}
Custom List Adapter:
public class CustomListAdapter extends ArrayAdapter<RowItem> {
Context context;
List<RowItem> items;
public CustomListAdapter(Context context, int resourceId,
List<RowItem> items) {
super(context, resourceId, items);
this.context = context;
this.items = items;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public RowItem getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
/*private view holder class*/
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtDesc;
}
public View getView(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.aname_list_item, null);
holder = new ViewHolder();
holder.txtDesc = (TextView) convertView.findViewById(R.id.desc);
holder.txtTitle = (TextView) convertView.findViewById(R.id.rab);
holder.imageView = (ImageView) convertView.findViewById(R.id.icon);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
// String name=items.get(position).getDesc();
holder.txtDesc.setText(rowItem.getDesc());
holder.txtTitle.setText(rowItem.getTitle());
holder.imageView.setImageBitmap(rowItem.getImageId());
// holder.imageView.setImageResource(Images.get(position) .getPlaceholderleft());
return convertView;
}
}
It looks like this is because you've made your variables x, y, z and a all static, which means there is a single instance of the variables shared by all instances of the class. Therefore, when you call onCreate the second time, all your while loop termination conditions are already met, so the while loops never execute. It's unclear to me why you've made these static, so unless you need them to be, you should remove the static keyword for these variables.
Why are you creating another object of ListView in onCreate() and onResume()
Remove code from onResume()
Also replace this line in onCreate()
old line ListView listView = (ListView)findViewById(R.id.listing);
New line listView = (ListView)findViewById(R.id.listing);
Now i want to make filter but i really don't know how to do it. I've read some tutorials and tried but it still does not work. Please help me!
i want to implement the search functionality.
code of class apdater:
public class PlaceAdapter extends BaseAdapter {
private static ArrayList<Place> searchArrayList;
private LayoutInflater mInflater;
public PlaceAdapter(Context context, ArrayList<Place> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView
.findViewById(R.id.label_place);
holder.txtAddress = (TextView) convertView
.findViewById(R.id.label_address);
holder.txtPhone = (TextView) convertView
.findViewById(R.id.label_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtAddress.setText(searchArrayList.get(position).getAddress());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtAddress;
TextView txtPhone;
}
}
code of class activity
public class ServiceDetail extends Activity {
private String DB_NAME = "Danang Travel.sqlite";
private PlaceAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servicedetail);
final ArrayList<Place> searchResults = GetSearchResults();
final EditText filterEditText = (EditText) findViewById(R.id.filter_text);
final ListView lvPlace = (ListView) findViewById(R.id.listView1);
adapter = new PlaceAdapter(this, searchResults);
lvPlace.setAdapter(adapter);
lvPlace.setTextFilterEnabled(true);
// Set Focus*****************************************
lvPlace.setFocusableInTouchMode(true);
lvPlace.requestFocus();
lvPlace.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
// arg0.setBackgroundColor(arg1 ? Color.GRAY : Color.BLACK);
// lvPlace.setItemsCanFocus(true);
}
});
// lvPlace.setClickable(true);
/******************************************************/
// filter search
filterEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
//ServiceDetail.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lvPlace.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Object o = lvPlace.getItemAtPosition(position);
Place fullObject = (Place) o;
Toast toast = Toast.makeText(ServiceDetail.this,
"You have chosen: " + " " + fullObject.getName(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
}
private ArrayList<Place> GetSearchResults() {
ArrayList<Place> results = new ArrayList<Place>();
SQLiteDatabase DB = null;
Intent t = getIntent();
Bundle extra = t.getExtras();
String temp = extra.getString("k");
try {
DB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
Cursor c = DB.rawQuery(
"SELECT Name,Address,TypeID FROM ServiceDetail Where SerID = '"
+ temp + "' ORDER BY Name", null);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Place k = new Place();
// The Cursor is now set to the right position
String n = c.getString(c.getColumnIndex("Name"));
String a = c.getString(c.getColumnIndex("Address"));
String p = c.getString(c.getColumnIndex("TypeID"));
k.setName(n);
k.setAddress(a);
k.setPhone(p);
results.add(k);
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
DB.close();
}
return results;
}
}
Now i want to make filter but i really don't know how to do it. I've read some tutorials and tried but it still does not work. Please help me!
Here you go :)
//Firstly here is your edittext on which you want to filter
EditTextfilterText = (EditText) findViewById(R.id.search_box);
filterText.clearComposingText();
//Give the edittext the watcher as a text listener
filterText.addTextChangedListener(filterTextWatcher);
//This will listen to key events such as you entering something inside the edit text
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
//Called after text changed
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
//Called each time you enter something into the edittext to filter your list or whatever
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//Adapter creating code
//......
//Filter calling code
adapter.getFilter().filter(s, new FilterListener() {
#Override
public void onFilterComplete(int count) {
//Just for fun do something here once filtering is done
}
});
}
}
};
Now inside your custom adapter you would have the following:
public Filter getFilter() {
filter = new DrugListFilter();
return filter;
}
private class MyFilterName extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults retval = new FilterResults();
ArrayList<something> filt = new ArrayList<something>();
//... Some code to filter your current Adapter data by the constaint
//Pass the results to retval
retval.count = filt.size();
retval.values = filt;
}
//return retval
return retval;
}
//This is called once performFiltering is done
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems.clear();
//This is your array of filtered items
filteredItems.addAll((ArrayList)results.values);
doneFilter = true;
//Notify the dataset that it needs to update
notifyDataSetChanged();
}
}
I have a multicolumn List view like the one shown in the image, i used custom adapters to populate this custom list.so the question is how to get data on click of submit button means when i click submit button i should get data like name, price and quantity of only checked checkbox....Thanx in advance.
In my Main xml i have a listview and in mainlist xml i have txtname, txtprice, edittext and checkbox and use efficient adapter.
i'm able to view data in list view, bt the problem is i m unable to save data on click of submit button... so plz help me out, with a sample code, bcz m new to android..
the following is my code..
public class Menu extends Activity {
ListView list;
Cursor cursorMenu;
Button btnPlaceOrder;
Button btnShowOrders;
String Descstr="";
String strtotal="";
List<String[]> lstSelectedItems = null;
DBAdapter db = new DBAdapter(this);
private String[] strName;
private String[] strPrice;
private String[] strDescription;
private class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
}
public int getCount() {
try {
return strName.length;
} catch (Exception e) {
//Toast.makeText(Menu.this, "No Data !", Toast.LENGTH_LONG).show();
return 0;
}
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menulist, null);
holder = new ViewHolder();
holder.text = (TextView) convertView
.findViewById(R.id.txtItemName);
holder.text2 = (TextView) convertView
.findViewById(R.id.txtPrice);
holder.text3 = (TextView) convertView
.findViewById(R.id.txtDescription);
holder.etext3 = (EditText) convertView
.findViewById(R.id.txtQty);
holder.chk = (CheckBox) convertView
.findViewById(R.id.chkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text.setText(strName[position]);
holder.text2.setText(strPrice[position]);
holder.text3.setText(strDescription[position]);
return convertView;
}
class ViewHolder {
TextView text;
TextView text2;
TextView text3;
EditText etext3;
CheckBox chk;
}
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
btnPlaceOrder = (Button) findViewById(R.id.btnPlaceOrder);
btnPlaceOrder.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
}
});
/*db.open();
cursorMenu = db.menu_getAllTitles();
int rowcount = cursorMenu.getCount();
System.out.println("---- +++++ " + rowcount);
System.out.println("---- column +++++ " + cursorMenu.getColumnCount());
int index = 0;
if (rowcount > 0) {
strName = new String[rowcount];
strPrice = new String[rowcount];
strDescription = new String[rowcount];
if (cursorMenu.moveToFirst()) {
do {
strName[index] = cursorMenu.getString(1);
strDescription[index] = cursorMenu.getString(2);
strPrice[index] = cursorMenu.getString(3);
Log.v(TAG, "Name-- " + strName[index] + "Price-- "
+ strPrice[index]);
index++;
} while (cursorMenu.moveToNext());
}
cursorMenu.close();
} else {
Toast.makeText(this, "No Data found", Toast.LENGTH_LONG).show();
}*/
list = (ListView) findViewById(R.id.lstMenu);
list.setAdapter(new EfficientAdapter(this));
System.out.println("--List Child count-----"+list.getChildCount());
System.out.println("--List count-----"+list.getCount());
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Toast.makeText(getBaseContext(),
"You clciked " + strName[arg2] + "\t" + strPrice[arg2],
Toast.LENGTH_LONG).show();
}
});
}
}
http://www.vogella.de/articles/AndroidListView/article.html go through this example you can get every thing regards listview.
I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
I think an AutoCompleteTextView might be more suitable to implement this feature.
Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}