In my list view ,I have Edittext and some textviews. when I am trying to iterate over listview to get edittext values, I got some problems.I want to perform actions only if my edittext in the listview is not empty. otherwise i want to continue the iteration.I need only non empty values from the edittexts when iterate through listview. my listview name is "list" here.
my code is
if (list != null) {
for (int i = 0; i < list.getChildCount(); i++) {
ed2 = (EditText) list.getChildAt(i).findViewById(R.id.pcs);
if (ed2.getText().toString().trim().length() != 0) {
TextView im_codetext = (TextView) vie.findViewById(R.id.code);
imcode = im_codetext.getText().toString();
try {
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor cr = newDB.rawQuery("select distinct im_srp_pc, im_subgroup_code from itemmaster where im_code =" + imcode, null);
while (cr.moveToNext()) {
srppc = cr.getString(cr.getColumnIndex("im_srp_pc"));
String subcode = cr.getString(cr.getColumnIndex("im_subgroup_code"));
databas.put("subgp", subcode);
}
srps = Float.valueOf(srpval);
qtys = Integer.valueOf(ed2.getText().toString());
} catch (NumberFormatException e) {
srps = 0;
}
float amnts = srps * qtys;
sumnet = sumnet + amnts;
else{
Log.v(" empty", " empty");
}
}
}
}
My adapter class is
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.srp);
holder.textview3 = (TextView) convertView.findViewById(R.id.code);
holder.editText2 = (EditText) convertView.findViewById(R.id.pcs);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
String [] names = new String[550];
String [] codes = new String[550];
String [] prize = new String[550];
DatabaseHelper dbHelper = new DatabaseHelper(Orders.this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp "
+ " from itemmaster", null);
c.moveToFirst();
while (c.moveToNext()){
Log.v("item detailss", c.toString());
String cod = c.getString(c.getColumnIndex("im_code"));
codes[c.getPosition()] =cod;
String desc1 = c.getString(c.getColumnIndex("im_desc"));
names[c.getPosition()] = desc1;
String price = c.getString(c.getColumnIndex("im_srp"));
prize[c.getPosition()] = price;
}
holder.textView1.setText(names[position+1]);
holder.textview3.setText(codes[position+1]);
holder.textView2.setText(prize[position+1]);
holder.editText2.setText(arrTemp[position]);
holder.editText2.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
// arrTemp[holder.ref] = arg0.toString();
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1,editText2;
int ref;
}
}
please help.thanks in advance.
I have a Solution.
Declare a HashMap in your custom adapter class.
public class CustomAdapter extends BaseAdapter{
public HashMap<Integer,String> textMap = new HashMap<Integer,String>();
....
In getView() Method get text from HasMap and set in EditText.
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.list_item, null);
holder.editText = (EditText)rowView.findViewById(R.id.editText);
holder.editText.setText(textMap.get(position));
....
And in TextChangeListner add text in HashMap by position.
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
// arrTemp[holder.ref] = arg0.toString();
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
textMap.put(position,holder.editText.getText().toString());
}
});
Now in your Activity you can get HashMap of adapter and get its value by position. and if there is no text in particuller position ,means edttext is empty.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
listView = (ListView)findViewById(R.id.listView);
final CustomAdapter customAdapter = new CustomAdapter(this,names);
listView.setAdapter(customAdapter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for(int i=0;i<names.length;i++){
Toast.makeText(MainActivity.this, customAdapter.textMap.get(i), Toast.LENGTH_SHORT).show();
}
}
});
Related
I have a list view containing textview and edit texts and i have to add these values in array list.As i am trying it not all values are added to Arraylist,only values of that particular visible view gets added.How should I modify my code so that all the data gets added to arraylist.
list = (ListView) findViewById(R.id.list);
personList = new ArrayList<HashMap<String,String>>();
flags=0;
getData();
placeord=(Button)findViewById(R.id.placeorder);
placeord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isNetworkConnected()) {
ArrayList<String> m = new ArrayList<String>();
ArrayList<String> si = new ArrayList<String>();
EditText q;
TextView sizes;
for (int i =0; i<= list.getLastVisiblePosition() - list.getFirstVisiblePosition(); i++) {
View v = list.getChildAt(i);
q = (EditText) v.findViewById(R.id.numberofitems);
sizes = (TextView) v.findViewById(R.id.size);
if(q.getText().toString().length()>0) {
si.add(sizes.getText().toString());
flags=1;
}
m.add(q.getText().toString());
}
if (flags == 0) {
Toast.makeText(getApplicationContext(), "please add some quantity", Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(getApplicationContext(),val,Toast.LENGTH_SHORT).show();
Intent intent = new Intent(placecolor.this, placeorder2.class);
Bundle extras1 = new Bundle();
extras1.putStringArrayList("numberofitems", m);
extras1.putStringArrayList("sizes", si);
intent.putExtras(extras1);
startActivity(intent);
}
}
}
}
It happens because android recycle the view of ListView and Recyclerview. You need to add(save) data of EditText by implementing OnTextChangeListener. By implementing it you can get the entered text and assign it to particular position in List<>.
Example :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.listview_list, null);
holder.textView = (TextView) convertView.findViewById(R.id.textView);
holder.editText = (EditText) convertView.findViewById(R.id.editText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView.setText(arr[position].name);
holder.editText.setText(arr[position].nameValue);
holder.editText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arr[holder.ref].nameValue = arg0.toString(); // Set value in list
}
});
return convertView;
}
When I am trying to set value to the list view using custom adapter it shows only the last entered value in the hash map. hash map is static.I dont know why I am not getting all the values in the hashmap for that keys I am used in hashmap.
here my code
public class Nextclass extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nextclass);
list = (ListView)findViewById(R.id.list1);
SelectItems();
ViewItems();
}
private List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct code ,desc ,name "
+ " from item", null);
while (c.moveToNext()){
String cod = c.getString(c.getColumnIndex("code"));
datanums.put("code", cod);
String desc1 = c.getString(c.getColumnIndex("desc"));
datanums.put("desc", desc1);
String name = c.getString(c.getColumnIndex("name"));
datanums.put("name", name);
datas.add(datanums);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
private void ViewItems() {
// TODO Auto-generated method stub
arrTemp = new String[datas.size()];
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
Log.v("list itemm",datas.toString());
}
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.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) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.code);
holder.textview3 = (TextView) convertView.findViewById(R.id.desc);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(datanums.get("name"));
holder.textview3.setText(datanums.get("code"));
holder.textView2.setText(datanums.get("desc"));
holder.editText1.setText(arrTemp[position]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1,editText2;
int ref;
}
return convertView;
}
private class ViewHolder {
public Object list;
TextView textView1,textView2,textview3;
EditText editText1;
int ref;
}
please help.I used alternate methods,but not worked.thanks in advance
holder.textView1.setText(datas.get(position).get("name"));
holder.textview3.setText(datas.get(position).get("code"));
holder.textView2.setText(datas.get(position).get("desc"));
you are adding hash map in the array list but in the adapter you are trying to get data from the hash map, instead of that you need to take value from arraylist which will return hashmap object and from that object you need to get value for your keys.
hope this will help.
when I am trying to set values to the list view using custom adapter it didn't display the data from hash map. values that I want to display in the list view is getting from the database.and my list view contains text views and edit texts.
my code is
private void SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp "
+ " from itemmaster", null);
Log.v("item detailss", c.toString());
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String im_code = c.getString(c.getColumnIndex("im_code"));
String desc = c.getString(c.getColumnIndex("im_desc"));
datanums.put("codec", im_code);
datanums.put("namec", desc);
String price = c.getString(c.getColumnIndex("im_srp"));
datanums.put("imsrpc", price);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
}
private void ViewItems() {
// TODO Auto-generated method stub
list.setAdapter(null);
arrTemp = new String[datas.size()];
datas.add(datanums);
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
Log.v("list itemm",datas.toString());
}
private class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.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) {
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.srp);
holder.textview3 = (TextView) convertView.findViewById(R.id.code);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
holder.editText2 = (EditText) convertView.findViewById(R.id.pcs);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
holder.textView1.setText(datanums.get("namec"));
holder.textView2.setText(datanums.get("imsrpc"));
holder.textview3.setText(datanums.get("codec"));
holder.editText1.setText(arrTemp[position]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
}
});
return convertView;
}
private class ViewHolder {
TextView textView1,textView2,textview3;
EditText editText1,editText2;
int ref;
}
}
in this viewitems(), and selectitems(), are methods called from oncreate to retrieve and display value in the list view. I couldn't sort out the exact problem.but the edit texts are showing properly in the output.please help.
Add below line at start of the getView method
HashMap<String, String> datanums=datas.get(possition);
public List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp "
+ " from itemmaster", null);
Log.v("item detailss", c.toString());
while (c.moveToNext()){
HashMap<String, String> datanums = new HashMap<String, String>();
String im_code = c.getString(c.getColumnIndex("im_code"));
String desc = c.getString(c.getColumnIndex("im_desc"));
datanums.put("codec", im_code);
datanums.put("namec", desc);
String price = c.getString(c.getColumnIndex("im_srp"));
datanums.put("imsrpc", price);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
/* In your Activity or adapter class call this method(this will return the list) and check the condition if( arraylist!=null && arraylist.size()>0) */
Use this code to set your text view. Hope this works.
holder.textView1.setText(datas.get(position).get("namec"));
holder.textview3.setText(datas.get(position).get("codec"));
holder.textview3.setText(datas.get(position).get("srpc"));
I have two EditTexts in my ListView. All I want is adding a TextWatcher to both the EditTexts , so I can avoid duplicating and changing values in it while scrolling. I can successfully add the TextWatcher to one of the EditTexts, but could not implement for two EditTexts. I tried other answers from stackoverflow. But I didn't get desired output.
This is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.orders);
list = (ListView)findViewById(R.id.list1);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
SelectItems();
ViewItems();
}
public List<Map<String, String>> SelectItems() {
// TODO Auto-generated method stub
try {
datas = new ArrayList<Map<String, String>>();
DatabaseHelper dbHelper = new DatabaseHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp"
+ " from itemmaster", null);
c.moveToFirst();
while (c.moveToNext()){
datanums.put("name",c.getString(c.getColumnIndex("im_desc")));
datanums.put("code", c.getString(c.getColumnIndex("im_code")));
datanums.put("imsrp",c.getString(c.getColumnIndex("im_srp")));
datas.add(datanums);
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
return datas;
}
public void ViewItems() {
// TODO Auto-generated method stub
arrTemp = new String[datas.size()];
MyListAdapter myListAdapter = new MyListAdapter();
list.setAdapter(myListAdapter);
}
public class MyListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(datas != null && datas.size() != 0){
return datas.size();
}
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return datas.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
//ViewHolder holder = null;
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
LayoutInflater inflater = Orders.this.getLayoutInflater();
convertView = inflater.inflate(R.layout.order_simple_row, null);
holder.textView1 = (TextView) convertView.findViewById(R.id.name);
holder.textView2 = (TextView) convertView.findViewById(R.id.srp);
holder.textview3 = (TextView) convertView.findViewById(R.id.code);
holder.editText1 = (EditText) convertView.findViewById(R.id.cases);
holder.editText2 = (EditText) convertView.findViewById(R.id.pcs);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.ref = position;
String [] names = new String[550];
String [] codes = new String[550];
String [] prize = new String[550];
DatabaseHelper dbHelper = new DatabaseHelper(Orders.this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("select distinct im_code ,im_desc ,im_srp "
+ " from itemmaster", null);
Log.v("item detailss", c.toString());
c.moveToFirst();
while (c.moveToNext()){
String cod = c.getString(c.getColumnIndex("im_code"));
codes[c.getPosition()] =cod;
String desc1 = c.getString(c.getColumnIndex("im_desc"));
names[c.getPosition()] = desc1;
String price = c.getString(c.getColumnIndex("im_srp"));
prize[c.getPosition()] = price;
}
newDB.close();
holder.textView1.setText(names[position+1]);
holder.textview3.setText(codes[position+1]);
holder.textView2.setText(prize[position+1]);
holder.editText1.setText(arrTemp[holder.ref]);
holder.editText2.setText(arrTemp[holder.ref]);
holder.editText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
arrTemp[holder.ref] = arg0.toString();
datas.get(position).put("pref", holder.editText1.toString().trim());
}
});
return convertView;
}
private class ViewHolder {
TextView textView1,textView2,textview3;
EditText editText1,editText2;
public int ref;
}
}
please help me to do this in right way.
Recently I had a similar problem, here is how I solved it using HashMap:
In the adapter constructor, initialize HashMap and make sure to clear it:
public MyAdapter(Context context, String[] texts){
this.context = context;
this.texts = texts;
hashMapTexts = new HashMap<String,String>();
for(String text: texts){
hashMapTexts.put(text, "");
}
Then, correct your private class ViewHolder inside the adapter like that:
private class ViewHolder {
private TextView listItemTextView;
private EditText listItemEditText;
private int position;
public ViewHolder(View view) {
listItemTextView = (TextView)view.findViewById(R.id.list_item_text_view);
listItemEditText = (EditText)view.findViewById(R.id.list_item_edit_text);
}
}
Then, initialize the ViewHolder in the overriden getView() method:
if(convertView == null){
convertView = View.inflate(context, R.layout.list_item, null);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder)convertView.getTag();
}
Get the position of the ViewHolder in the same method:
viewHolder.position = position;
Set the texts for your views:
viewHolder.listItemTextView.setText(texts[position]);
viewHolder.listItemEditText.setText(hashMapTexts.get(texts[position]));
and now use the TextWatcher:
viewHolder.listItemFormEditText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
hashMapTexts.put(texts[viewHolder.position], s.toString());
}
});
return convertView;
I suggest you to start with easier case, like mine, then apply it to your specific scenario.
Use different textwatchers for each edit text if you want to perform
different operations on each edit text
EditText1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 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 afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Apply same for other EditText too
et1.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// 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 afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Its been a week since I'm stuck with this problem.
I developed an application with a listView and editText to make a search. When I make a search the new list is showed very well but when I click on the item it redirect me to the item of the inicial list.
I don't know what to do please help me. These are my codes.
-For the ReaderListAdapter :
public class ReaderListAdapter extends BaseAdapter {
ArrayList<Reader> listReader = new ArrayList<Reader>();
ArrayList<Reader> arrayList;
LayoutInflater layoutInflater;
Context context;
int lastPosition = -1;
// constructeur
public ReaderListAdapter(Context context, ArrayList<Reader> listReader) {
this.listReader = listReader;
this.context = context;
arrayList = new ArrayList<Reader> ();;
layoutInflater = LayoutInflater.from(this.context);
arrayList.addAll(listReader);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return listReader.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return listReader.get(position);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
static class ViewHolder {
TextView nomView;
TextView priceView;
ImageView pictureView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = layoutInflater.inflate(R.layout.reader_row, null);
holder = new ViewHolder();
// initialisation des vues
holder.nomView = (TextView) convertView.findViewById(R.id.name);
holder.priceView = (TextView) convertView.findViewById(R.id.price);
holder.pictureView = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// affchier les données convenablement dans leurs positions
holder.nomView.setText(listReader.get(position).getName());
holder.priceView.setText(String.valueOf(listReader.get(position).getPrice()));
holder.pictureView.setBackgroundDrawable(listReader.get(position).getPicture());
// changer R.anim.ton_effet
Animation animation = AnimationUtils.loadAnimation(context,(position > lastPosition)
? R.anim.up_from_bottom: R.anim.up_from_bottom);
convertView.startAnimation(animation);
position=lastPosition;
return convertView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
listReader.clear();
if(charText.length()==0){
listReader.addAll(arrayList);
}
else{
for (Reader c : arrayList) {
if (c.getName().toLowerCase(Locale.getDefault())
.contains(charText)) {
listReader.add(c);
}
}
}
notifyDataSetChanged();
}
}
-For the MainActivity:
public class MainActivity extends Activity {
String[] listNames = { "kooora","yahoo", "hespress"};
int[] listPrices = { 1, 2, 3 };
ArrayList<Reader> listReader = new ArrayList<Reader>();;
ArrayList<Reader> listReaderNew;
ListView lv;
EditText search;
ReaderListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listReader);
search = (EditText) findViewById(R.id.search);
Drawable[] listPictures = {getResources().getDrawable(R.drawable.a1),getResources().getDrawable(R.drawable.a2),getResources().getDrawable(R.drawable.a3)};
for (int i = 0; i < listPictures.length; i++) {
listReader.add(new Reader(i + 1, listNames[i], listPictures[i], listPrices[i]));
}
adapter=new ReaderListAdapter(getApplicationContext(), listReader);
lv.setAdapter(adapter);
//lv.setAdapter(new ReaderListAdapter(getApplicationContext(), listReader));
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
#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
String text = search.getText().toString().toLowerCase(Locale.getDefault());
MainActivity.this.adapter.filter(text);
}});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Intent intent=new Intent(MainActivity.this,WebActivity.class);
switch (position) {
case 0:
intent.setData(Uri.parse("http://www.kooora.com")) ;break;
case 1:
intent.setData(Uri.parse("http://www.yahoo.com")) ;break;
case 2:
intent.setData(Uri.parse("http://www.hespress.com")) ;break; }if (intent != null) {
startActivity(intent);
}}});}}
Please help me. Thanks in advance!
I think the code in onItemClick is causing this.
The problem:
searchTerm = "yahoo"
You filter yahoo and show the listitem for yahoo. Lets says its position in the list is 0. When the user clicks it, the onItemClick will be called and case 0: will be executed.
The correct logic should be,
Reader reader = parent.getAdapter().getItem(position);
String searchTerm = reader.getName(); // or whichever is the id for that listitem
if(searchTerm.contains("yahoo")) {
intent.setData(Uri.parse("http://www.yahoo.com"))
} // and so on