android listview, edittext same ID - android

I got a listView in a fragment. This listView use an BaseExpandableListAdapter. I got a list of question and for each of them, I have a list of answer. I add a Edittext after each last answer == last child (to add a new answer).
My problem is that each edittext has the same ID, so when I have more than one question, I can't write inside the edittext because two edittext have the same Id.
I don't know how to manage it :'(.
-> Fragment code :
public class HomeFragment extends Fragment implements AbsListView.OnItemClickListener {
private OnFragmentInteractionListener mListener;
/**
* The fragment's ListView/GridView.
*/
private AbsListView mListView;
/**
* The Adapter which will be used to populate the ListView/GridView with
* Views.
*/
private AdapterHomeFragment adapter;
private LinkedList<Question> listQuestion;
private ExpandableListView listView;
public static HomeFragment newInstance() {
HomeFragment fragment = new HomeFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
View rootView = inflater.inflate(R.layout.home_fragment, container, false);
listView = (ExpandableListView) rootView.findViewById(R.id.listView);
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
return rootView;
}
/*
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnFragmentInteractionListener");
}
}
*/
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
}
}
/**
* The default content for this Fragment has a TextView that is shown when
* the list is empty. If you would like to change the text, call this method
* to supply the text it should use.
*/
public void setEmptyText(CharSequence emptyText) {
View emptyView = mListView.getEmptyView();
if (emptyView instanceof TextView) {
((TextView) emptyView).setText(emptyText);
}
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
public void onFragmentInteraction(String id);
}
public void refreshData()
{
listQuestion = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
adapter = new AdapterHomeFragment(getActivity(), listQuestion);
listView.setAdapter(adapter);
listView.setGroupIndicator(null);
}
-> Adapter code :
public class AdapterHomeFragment extends BaseExpandableListAdapter {
private LinkedList<Question> groups;
public LayoutInflater inflater;
public Activity activity;
public AdapterHomeFragment(Activity act, LinkedList<Question> groups) {
activity = act;
this.groups = groups;
inflater = act.getLayoutInflater();
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return groups.get(groupPosition).getListAnswer().get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return 0;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return groups.get(groupPosition).getListAnswer().size() + 1;
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public void onGroupCollapsed(int groupPosition) {
super.onGroupCollapsed(groupPosition);
}
#Override
public void onGroupExpanded(int groupPosition) {
super.onGroupExpanded(groupPosition);
}
#Override
public long getGroupId(int groupPosition) {
return 0;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
int nbAnswer;
if (convertView == null) {
convertView = inflater.inflate(R.layout.rowquestion_home, null);
}
Question question = (Question) getGroup(groupPosition);
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setText(question.getQuestion());
((CheckedTextView) convertView.findViewById(R.id.rowquestion_home_question)).setChecked(isExpanded);
((TextView) convertView.findViewById(R.id.rowquestion_home_author)).setText("Anonymous" + question.getUserId().toString());
((TextView) convertView.findViewById(R.id.rowquestion_home_time)).setText(question.getDifferenceTime()+ " ago");
nbAnswer = question.getListAnswer().size();
if (nbAnswer == 1)
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answer");
else
((TextView) convertView.findViewById(R.id.rowquestion_home_nbAnswer)).setText(String.valueOf(question.getListAnswer().size()) + " answers");
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean verifyFormatString (String question)
{
boolean valid = false;
int i = 0;
while (!valid && i < question.length())
{
if (question.charAt(i) != ' ')
valid = true;
i += 1;
}
return valid;
}
-> Xml of the footer
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="40dp"
android:clickable="true"
android:orientation="vertical"
android:paddingLeft="40dp"
android:background="#color/layout_button"
tools:context=".MainActivity" >
<View
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/footer_answer_block"
/>
<EditText
android:id="#+id/footer_answer_edit_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:drawablePadding="5dp"
android:gravity="center_vertical"
android:hint="Add answer"
android:textSize="14sp"
android:textStyle="italic"
android:layout_toLeftOf="#+id/footer_answer_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</EditText>
<Button
android:id="#+id/footer_answer_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lines="1"
android:textSize="12sp"
android:text="add"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_below="#+id/footer_answer_block">
</Button>
If you have any idea how to resolve it, it will help me a lot !
Thank you.
When I click on the edittext the keyboard open but instant lose the focus on the edittext and it's impossible to write inside

You can use setTag() method of view. So whenever your getChildView() executes just set editText.setTag(position). Once user submit the answer you just need to find the tag that in which edit test user has typed by edittext.getTag(). It will return you the position which you tagged at the time of getChildView() execution. By that way you can get to know different answers once you have more than 1 question.
getChildView() Code
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (!isLastChild) {
Answer answer = (Answer) getChild(groupPosition, childPosition);
TextView text = null;
convertView = inflater.inflate(R.layout.rowanswer_home, null);
text = (TextView) convertView.findViewById(R.id.rowanswer_home_answer);
text.setText(answer.getAnswer());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_author);
text.setText("Anonymous"+answer.getUserId().toString());
text = (TextView) convertView.findViewById(R.id.rowanswer_home_time);
text.setText(answer.getDifferenceTime()+" ago");
}
else
{
TextView text = null;
convertView = inflater.inflate(R.layout.footer_answer, null);
final Question question = groups.get(groupPosition);
final EditText editText = (EditText)convertView.findViewById(R.id.footer_answer_edit_text);
editText.setTag(childPosition);
final Button button = (Button) convertView.findViewById(R.id.footer_answer_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String text_answer = editText.getText().toString();
QuestionManager.getQuestionManager().addAnswer(text_answer, question.getId());
groups = QuestionManager.getQuestionManager().getQuestionWithAnswerNotFromMe();
notifyDataSetChanged();
}
});
button.setEnabled(false);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// you can call or do what you want with your EditText here
String text = editText.getText().toString();
int answeredPosition = (Integer)editText.getTag();
Log.d("Answered Position",""+answeredPosition);// This is the position of question in listview for which user has typed the answer.
if (verifyFormatString(text)) {
button.setEnabled(true);
} else
button.setEnabled(false);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Log.d("test5780", String.valueOf(editText.getId()));
}
return convertView;
}
Let me know if it work or you need more descriptive answer.

Related

Apply Listener on some ListView columns

Background:
I have created a ListView with three columns sNo, product and price. First column is defined as TextView (whose value is auto generated) and the next two columns are EditText (whose value is filled up by the user).
What I want:
I want to add a new row to the ListView whenever:
User hit enter key on any EditText
There is no empty EditText (meaning all the EditText defined so far have some value in them).
Basically I want display a new orders list where users can add orders.
My code so far:
ListView Model:
public class NewTableModel {
private String sNo, product, price;
public NewTableModel(String sNo, String product, String price){
this.sNo = sNo;
this.product = product;
this.price = price;
}
public String getProduct(){ return product; }
public String getPrice(){ return price; }
public String getsNo() { return sNo; }
}
ListView adapter:
public class NewTableAdapter extends BaseAdapter {
private ArrayList<NewTableModel> productList;
private Activity activity;
public NewTableAdapter(Activity activity, ArrayList<NewTableModel> productList) {
super();
this.activity = activity;
this.productList = productList;
}
#Override
public int getCount() { return productList.size(); }
#Override
public Object getItem(int position) { return productList.get(position); }
#Override
public long getItemId(int position) { return position; }
public class ViewHolder {
TextView mSno;
EditText mProduct;
EditText mPrice;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.new_table_row, null);
holder = new ViewHolder();
holder.mSno = (TextView) convertView.findViewById(R.id.sno);
holder.mProduct = (EditText) convertView.findViewById(R.id.product);
holder.mPrice = (EditText) convertView.findViewById(R.id.price);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
NewTableModel item = productList.get(position);
holder.mSno.setText(item.getsNo());
holder.mProduct.setText(item.getProduct());
holder.mPrice.setText(String.valueOf(item.getPrice()));
return convertView;
}
}
MainActivity:
public class MainActivity extends AppCompatActivity {
private ArrayList<NewTableModel> productList;
private ListView orderView;
private NewTableAdapter orderAdapter;
private void insertNewRow(){ insertNewRow("",""); }
private void insertNewRow(String productVal, String priceVal){
String serialNoVal = String.valueOf(orderView.getCount() + 1);
NewTableModel item = new NewTableModel(serialNoVal, productVal, priceVal);
productList.add(item);
}
private void setupAdapter(){
productList = new ArrayList<NewTableModel>();
orderView = (ListView) findViewById(R.id.newTableContent);
orderAdapter = new NewTableAdapter(this, productList);
orderView.setAdapter(orderAdapter);
orderAdapter.notifyDataSetChanged();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setupAdapter();
insertNewRow();
}
}
My Listener:
setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER
&& noEmptyColumn())
insertNewRow();
return false;
}
});
Where should I place that listener ? and how would I check if any column is empty or not (define noEmptyColumn()) ?
You should place the listener where any of EditText values are changed. I would add a Button to any row, and set the listener at there. So in your ViewHolder:
saveButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
});
Another option could be setting a TextWatcher on EditText :
ed.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
boolean hasEmpty = false;
for (NewTableModel item: productList) {
if (item.getDesiredField().isEmpty()) {
hasEmpty = true;
break;
}
}
if (!hasEmpty) {
insertNewRow();
notifyDataSetChanged();
}
}
#Override
public void afterTextChanged(Editable editable) {
}
});
Just move both methods to your Adapter class. And note that the second solution is not efficient when there are too many rows.

Multiple TextWatcher added to same EditText in ExpandableListView's group view

From the conclusion of previous post I am not able to track how the TextWatcher is being added multiple times to EditText in the ExpandableListView. The ArrayList has only 2 elements.
The output should list only for 0 and 1 once but it was called twice.
Adapter:
public class ExpandableListAdapter extends BaseExpandableListAdapter {
private LayoutInflater inflater;
private Context context;
private ExpandableListView accordion;
private int lastExpandedGroupPosition;
ArrayList<ModelObject> mParent;
TextView textViewLabelGrandTotal;
float grandTotal = 0;
public ExpandableListAdapter( Context context, ArrayList<ModelObject> ModelObject, ExpandableListView accordion, TextView textViewLabelGrandTotal)
{
mParent = ModelObject;
inflater = LayoutInflater.from(context);
this.accordion = accordion;
this.context=context;
this.textViewLabelGrandTotal=textViewLabelGrandTotal;
}
#Override
//counts the number of group/parent items so the list knows how many times calls getGroupView() method
public int getGroupCount() {
return mParent.size();
}
#Override
//counts the number of children items so the list knows how many times calls getChildView() method
public int getChildrenCount(int i) {
return mParent.get(i).childCount;
}
#Override
//gets the title of each parent/group
public Object getGroup(int i) {
return mParent.get(i).INVOICE_ID;
}
#Override
//gets the name of each item
public Object getChild(int i, int i1) {
return mParent.get(i).children.get(i1);
}
#Override
public long getGroupId(int i) {
return i;
}
#Override
public long getChildId(int i, int i1) {
return i1;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
//in this method you must set the text to see the parent/group on the list
public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
if (view == null) {
view = inflater.inflate(R.layout.sfa_receipt_by_customer_new_receipt_due_invoice_list_item_parent, viewGroup,false);
}
// set category name as tag so view can be found view later
view.setTag(getGroup(i).toString());
CheckBox CheckBoxInv =(CheckBox)view.findViewById(R.id.CheckBoxInv);
TextView textViewLabelInvoice = (TextView) view.findViewById(R.id.textViewLabelInvoice);
TextView textViewLabelDate = (TextView) view.findViewById(R.id.textViewLabelDate);
TextView textViewDueAmt = (TextView) view.findViewById(R.id.textViewDueAmt);
TextView textViewRemainingAmt = (TextView) view.findViewById(R.id.textViewRemainingAmt);
final EditText editTextPaid = (EditText)view.findViewById(R.id.editTextPaid);
DecimalFormat df = new DecimalFormat("#.##");
textViewLabelInvoice.setText(mParent.get(i).INVOICE_NO);
textViewLabelDate.setText(mParent.get(i).INVOICE_DATE);
textViewDueAmt.setText(df.format(mParent.get(i).DUE));
textViewRemainingAmt.setText(df.format(mParent.get(i).REMAINING_AFTER_PAID));
CheckBoxInv.setChecked(mParent.get(i).checked);
CheckBoxInv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
System.out.println("===================== check change listerner ============================");
editTextPaid.setText(df.format(mParent.get(i).DUE)); // editTextPaid.setText("");
System.out.println("===================== check change listerner ============================");
if(c.isChecked() == false)
{
System.out.println("===================== uncheck change listerner ============================");
editTextPaid.setText("");
System.out.println("===================== uncheck change listerner ============================");
}
// notifyDataSetChanged();
}
});
//enable focus of edit text box
editTextPaid.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
System.out.println("ON TOUCH LISTERNER");
return false;
}
});
//disable focus of edittext box
editTextPaid.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
System.out.println("ON FOCUS CHANGE LISTENER");
}
});
//re calculate the remaining balance amount
editTextPaid.addTextChangedListener(new TextWatcher() {
{
System.out.println("TextWatcher Initialized..................!! " + i + " " + this);
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
System.out.println("ON TEXT CHANGE");
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
System.out.println("BEFORE TEXT CHANGE");
}
#Override
public void afterTextChanged(Editable arg0) {
System.out.println("AFTER TEXT CHANGE");
}
});
//return the entire view
return view;
}
#Override
//in this method you must set the text to see the children on the list
public View getChildView(int i, int i1, boolean b, View view, ViewGroup viewGroup) {
if (view == null)
{
view = inflater.inflate(R.layout.sfa_receipt_by_customer_new_receipt_due_invoice_list_item_child, viewGroup,false);
}
System.out.println("Inside getChildView()..................!!");
TextView textViewLabelReceipt = (TextView) view.findViewById(R.id.textViewLabelReceipt);
textViewLabelReceipt.setText((i1+1)+"."+mParent.get(i).children.get(i1).RECEIPT_NO);
TextView textViewLabelDate = (TextView) view.findViewById(R.id.textViewLabelDate);
textViewLabelDate.setText((i1+1)+"."+mParent.get(i).children.get(i1).RECEIPT_DATE);
TextView textViewRemainingAmt = (TextView) view.findViewById(R.id.textViewRemainingAmt);
textViewRemainingAmt.setText((i1+1)+"."+mParent.get(i).children.get(i1).REMAINING_AFTER_ADJUSTED_AMOUNT);
TextView textViewDueAmt = (TextView) view.findViewById(R.id.textViewDueAmt);
textViewDueAmt.setText((i1+1)+"."+mParent.get(i).children.get(i1).ADVANCE_BALANCE);
EditText editTextPaid =(EditText)view.findViewById(R.id.editTextPaid);
return view;
}
#Override
public boolean isChildSelectable(int i, int i1) {
return true;
}
#Override
/**
* automatically collapse last expanded group
*/
public void onGroupExpanded(int groupPosition) {
if(groupPosition != lastExpandedGroupPosition){
accordion.collapseGroup(lastExpandedGroupPosition);
}
super.onGroupExpanded(groupPosition);
lastExpandedGroupPosition = groupPosition;
}
}
OUTPUT:
07-30 06:59:28.219: I/System.out(9082): TextWatcher Initialized..................!! 0 com.example.ExpandableListAdapter$4#52bf1224
07-30 06:59:28.223: I/System.out(9082): TextWatcher Initialized..................!! 1 com.example.ExpandableListAdapter$4#52c09858
07-30 06:59:28.227: I/System.out(9082): TextWatcher Initialized..................!! 0 com.example.ExpandableListAdapter$4#52c37d10
07-30 06:59:28.239: I/System.out(9082): TextWatcher Initialized..................!! 1 com.example.ExpandableListAdapter$4#52c723ec
Solved it myself.
Placed all the view[CHECKBOX, EDITTEXT, TEXTVIEW] for the getGroupView() method within ViewHolder class [which is nothing but a class which contain views].
Saved it using settag() method of the "view" object which is a parameter of the getGroupView() method if the "view" parameter returned null.
Retrieved the views using getTag() and initialized the ViewHolder object from it if the "view" parameter is not null.

Get child view from ExpandableListView in FragmentActivity without childClick Event

I have several classes. First class extends from FragmentActivity, second class is adapter extends from BaseExpandableListAdapter. And Model Class.
First class:
public class CloseInformationTaskActivityList extends FragmentActivity implements ExpandableListView.OnChildClickListener {
private DAOFactory dao;
private ExpandListAdapter expAdapter;
private ExpandableListView expandList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle b = getIntent().getExtras();
//task with all information passed in intent by reference
PRTarea task = (PRTarea) b.getSerializable("Task");
dao = new DAOFactory(this.getApplicationContext());
List<PRParametros> parametrosList = dao.getParametrosDAO().getParamsByTaskId(task.getId());
if (parametrosList.size() > 0) {
setContentView(R.layout.activity_task_parameters_list);
expandList = (ExpandableListView) findViewById(R.id.paramsExpandableListView);
ArrayList<Group> expListItems = setParamsGroups(parametrosList);
expAdapter = new ExpandListAdapter(CloseInformationTaskActivityList.this, expListItems, this);
expandList.setOnChildClickListener(this);
expandList.setAdapter(expAdapter);
} else {
setContentView(R.layout.activity_no_param_error);
}
// Set up the action bar.
final ActionBar actionBar = getActionBar();
// Specify that the Home/Up button should not be enabled, since there is no hierarchical
// parent.
assert actionBar != null;
actionBar.setDisplayUseLogoEnabled(false);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setTitle(R.string.task_information_title);
actionBar.setIcon(R.drawable.ic_arrow_back_white_24dp);
}
private ArrayList<Group> setParamsGroups(List<PRParametros> parametrosList) {
ArrayList<Group> paramGroupList = new ArrayList<>();
ArrayList<Child> ch_list = null;
Group grupo;
String holdIdGroup = "0";
//secure check
if (parametrosList != null && parametrosList.size() > 0) {
for (int i = 0; i < parametrosList.size(); i++) {
PRParametros parametro = parametrosList.get(i);
String idGrupo = parametro.getIdGrupo();
if (!idGrupo.equals(holdIdGroup)) {
holdIdGroup = idGrupo;
grupo = new Group();
ch_list = new ArrayList<>();
grupo.setName(dao.getGruposParametrosDAO().getGrupoById(idGrupo).getDescripcion());
grupo.setItems(ch_list);
paramGroupList.add(grupo);
}
Child child = new Child();
child.setName(parametro.getNombre());
if(parametro.getIdTipo().equals("12")){
if(parametro.getValor() != null){
paramValue = dao.getListaParametrosDAO().getValueParamById(Integer.valueOf(parametro.getValor()));
}
}
child.setValue(paramValue);
child.setType(Integer.valueOf(parametro.getIdTipo()));
child.setParamId(Integer.valueOf(parametro.getId()));
if (ch_list != null) {
ch_list.add(child);
}
}
}
return paramGroupList;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
case R.id.btn_save_param:
saveParameters();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void saveParameters() {
Toast.makeText(getApplicationContext(),"Save parameters click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.save_parameters, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
Child child = (Child) parent.getExpandableListAdapter().getChild(groupPosition,childPosition);
int itemType = child.getType();
switch (itemType){
case 12:
onCreateDialogSingleChoice(child, v);
break;
case 9:
openDateDialog(child, v);
break;
}
return false;
}
/**
* Open popup with single choice, refresh model data of child
* and assign selected value to textView
*
* #param child model with data
* #param view to asign selected value
*/
public void onCreateDialogSingleChoice(final Child child, final View view) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
List<PRListaParametros> listaParametros = dao.getListaParametrosDAO().getListParamsById(child.getParamId());
List<String> values = new ArrayList<>();
for(int i = 0; i < listaParametros.size(); i++){
values.add(listaParametros.get(i).getDescripcion());
}
final String[] items = values.toArray(new String[listaParametros.size()]);
final TextView label = (TextView) ((RelativeLayout) view).getChildAt(1);
builder.setTitle(R.string.task_information_param_popup_title);
builder.setSingleChoiceItems(items, 75, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText(items[which]);
child.setValue(items[which]);
dialog.dismiss();
}
});
builder.setNegativeButton(R.string.task_information_param_popup_negative_button,new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
label.setText("");
}
});
builder.show();
}
}
Second class:
/**
* Adapter for expandable list with parameters
*/
public class ExpandListAdapter extends BaseExpandableListAdapter {
private Context mContext;
private ArrayList<Group> groups;
private LayoutInflater mInflater;
public ExpandListAdapter(Context mContext, ArrayList<Group> groups) {
this.mContext = mContext;
this.groups = groups;
mInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public Object getChild(int groupPosition, int childPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.get(childPosition);
}
#Override
public boolean areAllItemsEnabled() {
return super.areAllItemsEnabled();
}
#Override
public View getChildView(int groupPosition, final int childPosition,
final boolean isLastChild, View convertView, ViewGroup parent) {
final Child child = (Child) getChild(groupPosition, childPosition);
final ViewHolder holder;
int itemType = child.getType();
holder = new ViewHolder();
if (itemType >= 1 && itemType <= 7) {
convertView = mInflater.inflate(R.layout.layout_edit_text_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param);
holder.editText = (EditText) convertView.findViewById(R.id.txt_task_detail_info_param_input);
holder.editText.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) {
//refresh data in model
child.setValue(holder.editText.getText().toString());
}
});
}else if(itemType == 8){
convertView = mInflater.inflate(R.layout.layout_boolean_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_boolean_title);
holder.booleanSwitch = (Switch) convertView.findViewById(R.id.param_boolean_switch);
holder.booleanSwitch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String switchValue = "false";
if(holder.booleanSwitch.isChecked()){
switchValue = "true";
}
child.setValue(switchValue);
//mParamListener.onParameterViewClick(v, child);
}
});
}else {
convertView = mInflater.inflate(R.layout.layout_text_view_close_information, null);
holder.txtLabel = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_text_view);
holder.txtClickWithValue = (TextView) convertView.findViewById(R.id.txt_task_detail_info_param_click_text_view);
}
convertView.setTag(holder);
if (itemType >= 1 && itemType <= 7) {
holder.txtLabel.setText(child.getName());
holder.editText.setText(child.getValue());
switch (itemType){
case 1:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789"));
break;
case 2:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
break;
case 6:
holder.editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
holder.editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
if(!holder.editText.getText().toString().isEmpty()){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 4 no valido");
}
}
break;
case 7:
holder.editText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_CHARACTERS);
if(!holder.editText.getText().toString().equals("")){
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
holder.editText.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) {
if(!isValidIp(holder.editText.getText().toString())){
holder.editText.setError("IPv 6 no valido");
}
}
});
break;
}
}else if(itemType == 8) {
boolean value = Boolean.valueOf(child.getValue());
holder.txtLabel.setText(child.getName());
if(value){
holder.booleanSwitch.setTextOn(mContext.getResources().getString(R.string.task_information_param_boolean_switch_on));
holder.booleanSwitch.setChecked(true);
}else{
holder.booleanSwitch.setTextOff(mContext.getResources().getString(R.string.task_information_param_boolean_switch_off));
holder.booleanSwitch.setChecked(false);
}
}else {
holder.txtLabel.setText(child.getName());
holder.txtClickWithValue.setText(child.getValue());
}
return convertView;
}
#Override
public void registerDataSetObserver(DataSetObserver observer) {
super.registerDataSetObserver(observer);
//call notifyDataSetChanged() for refresh data model in view
}
public static class ViewHolder {
public TextView txtLabel;
public EditText editText;
public TextView txtClickWithValue;
public Switch booleanSwitch;
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Child> chList = groups.get(groupPosition).getItems();
return chList.size();
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Group group = (Group) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.activity_task_parameters_group, null);
}
TextView groupTitle = (TextView) convertView.findViewById(R.id.param_group_name);
groupTitle.setText(group.getName());
TextView groupCount = (TextView) convertView.findViewById(R.id.param_group_count);
int countParam = getChildrenCount(groupPosition);
if(countParam > 1){
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title));
}else{
groupCount.setText(getChildrenCount(groupPosition) + " " +
mContext.getResources().getString(R.string.task_information_param_group_count_title_single));
}
if (isExpanded) {
convertView.setBackgroundResource(R.color.group_param_expanded);
} else {
convertView.setBackgroundResource(0);
}
return convertView;
}
#Override
public int getChildType(int groupPosition, int childPosition) {
return super.getChildType(groupPosition, childPosition);
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
/**
* #param ip the ip
* #return check if the ip is valid ipv4 or ipv6
*/
private static boolean isValidIp(final String ip) {
return InetAddressUtils.isIPv4Address(ip) || InetAddressUtils.isIPv6Address(ip);
}
}
Model Class
/**
* Model of each parameters
*/
public class Child {
private String name;
private String value;
private int type;
private int paramId;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public int getParamId() {
return paramId;
}
public void setParamId(int paramId) {
this.paramId = paramId;
}
}
XML View of each child by type, possible type is EditText, TextView, Switch, popup list with single choice.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp">
<TextView
android:id="#+id/txt_task_detail_info_param"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="1"
android:minWidth="150dp"
android:focusable="false"
android:clickable="false"
android:padding="20dp"
android:textSize="14sp"
android:layout_toLeftOf="#+id/txt_task_detail_info_param_input"
android:layout_alignParentLeft="true" />
<EditText
android:id="#+id/txt_task_detail_info_param_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minWidth="150dp"
android:maxWidth="200dp"
android:ellipsize="end"
android:maxLines="1"
android:textSize="14sp"
android:layout_centerVertical="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Layout have action bar with save button:
|------------------Save button--|
| <ExpandableList> | |
| group1 | |
| child1: textView EditText | |
| child2: textView Switch | |
| group2 | |
| child1: textView TextView | |
|-------------------------------|
I am trying to get values of child view for save it in database, before i need check each field by type for valid data.
Currently i am checking the values in adapter and works well. Possibly not the right way...
But how to get value of each view by type only clicking save button in FragmentActivity in action bar??
I am trying onChildClick but click event by editText not working. Thanks!
SOLVED
Now I have resolved, but I think is not the right way for do it.
In model class Child i created new field with View.
private View view;
and assigned complete View by type (editText,TextView, etc) in adapter getChildView for example:
child.setView(holder.editText);
and finally use in FragmentActivity
private void checkParameters() {
boolean validated = true;
int groupCount = expandList.getExpandableListAdapter().getGroupCount();
for (int i = 0; i < groupCount; i++) {
int childCount = expandList.getExpandableListAdapter().getChildrenCount(i);
for (int j = 0; j < childCount; j++) {
Child child = (Child) expandList.getExpandableListAdapter().getChild(i, j);
//secure check
if (child.getView() != null) {
int itemType = child.getType();
//only editText
if (itemType >= 1 && itemType <= 7) {
EditText ed = (EditText) child.getView();
//do something
}
}
}
}
}
Anyone know how to do this more efficiently???

CheckBox in child of exapndablelistview (android)

Problem is with checkbox. When user click on child, app should show toast message on which child user clicked. It works fine if I click on textview of child, but when i click on checkbox, nothing heppend. Also when I click on child item, I want that my checkbox change state. Do you see something that I can't see. Here is my code for main activity
private ExpandableAdapter adapter;
private ExpandableListView expandableList;
private List<Pitanja> pitanjas = new ArrayList<Pitanja>();
private ArrayList<Pitanja> listaPitanja = new ArrayList<Pitanja>();
private List<Odgovor> odgovors = new ArrayList<Odgovor>();
public static HashMap<Integer, Integer> pitanjaa;
private Intent intent;
private ProgressDialog pDialog;
private TextView output;
private List<Ispit> ispitList;
private String pozicija;
private Button posalji;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ispit);
output = (TextView) findViewById(R.id.ispit_datum);
output.setMovementMethod(new ScrollingMovementMethod());
pitanjaa = new HashMap<Integer, Integer>();
posalji = (Button) findViewById(R.id.posaljiIspitButton);
posalji.setOnClickListener(this);
generateData();
initEx();
intent = getIntent();
RequestPackage p = new RequestPackage();
p.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/ispit.php");
p.setMethod("POST");
p.setParam("id_kolegij", intent.getStringExtra("id_predmeta"));
Log.i("Saljem podatke ", intent.getStringExtra("id_predmeta"));
MyTask task = new MyTask();
task.execute(p);
}
private void updateDisplay(){
Collections.shuffle(ispitList);
output.setText(String.valueOf(ispitList.get(0).getId()));
MyRequest task = new MyRequest();//this works fine
RequestPackage r = new RequestPackage();//works
r.setMethod("POST");//works
r.setUri("http://arka.foi.hr/WebDiP/2012_projekti/WebDiP2012_085/AIR/pitanja.php");//works
r.setParam("id_kolegij", output.getText().toString());//works
task.execute(r);
}
private void initEx(){
adapter = new ExpandableAdapter(IspitActivity.this, listaPitanja);
expandableList = (ExpandableListView) findViewById(R.id.expandableIspitListView);
expandableList.setAdapter(adapter);
for (int i=0;i<adapter.getGroupCount();i++){
expandableList.collapseGroup(i);
}
expandableList.setOnChildClickListener(new OnChildClickListener(){
#Override
public boolean onChildClick(ExpandableListView arg0, View arg1,
int arg2, int arg3, long arg4) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Klikno si na " + adapter.getChild(arg2, arg3).getText() + " " + adapter.getChild(arg2, arg3).getTocan_netocan(), Toast.LENGTH_SHORT).show();
if (Integer.parseInt(adapter.getChild(arg2, arg3).getTocan_netocan()) == 0)
pitanjaa.put(arg2, arg3);
Log.i("pitanja koja si odgovorio su", pitanjaa.toString());
adapter.getChild(arg2, arg3).setSelected(true);
return true;
}
});
}
private void generateData(){
Pitanja p;
for (int i=0;i<pitanjas.size();i++){
ArrayList<Odgovor> od = new ArrayList<Odgovor>();
for (int z=0;z<odgovors.size();z++){
if (odgovors.get(z).getId_pitanja().contains(String.valueOf(pitanjas.get(i).getId()))){
od.add(odgovors.get(z));
}
}
pozicija = pitanjas.get(i).getText();
p = new Pitanja(i, pozicija, od);
listaPitanja.add(p);
}
}
private class MyTask extends AsyncTask<RequestPackage, String, List<Ispit>>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(IspitActivity.this);
pDialog.setMessage("Dobavljam podatke...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Ispit> doInBackground(RequestPackage... params) {
String content = HttpManager.getData(params[0]);
ispitList = JSONParser.parseIspit(content.substring(1, content.length()-1));
Log.i("Parsirano izgleda sljedeci", content.substring(1, content.length()-1));
return ispitList;
}
#Override
protected void onPostExecute(List<Ispit> result) {
super.onPostExecute(result);
pDialog.dismiss();
updateDisplay();
}
}
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), PregledActivity.class);
startActivity(intent);
}
}
Here is my expandablelistview adapter
public class ExpandableAdapter extends BaseExpandableListAdapter{
LayoutInflater inflater;
private List<Pitanja> groups;
public ExpandableAdapter(Context context,List<Pitanja> groups) {
super();
this.groups=groups;
inflater= (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void addItem(Odgovor child,Pitanja group) {
if(!groups.contains(group)) {
groups.add(group);
}
int index=groups.indexOf(group);
ArrayList<Odgovor> ch=groups.get(index).getOdgovors();
ch.add(child);
groups.get(index).setOdgovors(ch);
}
public Odgovor getChild(int groupPosition, int childPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.get(childPosition);
}
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public int getChildrenCount(int groupPosition) {
ArrayList<Odgovor> ch=groups.get(groupPosition).getOdgovors();
return ch.size();
}
public View getChildView(int groupPosition, int childPosition, boolean isLastChild,
View convertView, ViewGroup parent) {
Odgovor child= (Odgovor) getChild(groupPosition,childPosition);
TextView childName=null;
CheckBox cb = null;
if(convertView==null) {
convertView=inflater.inflate(R.layout.child_item, null);
}
childName=(TextView) convertView.findViewById(R.id.textview_child_item);
childName.setText(child.getText());
cb = (CheckBox) convertView.findViewById(R.id.checkbox_child_item);
if (child.isSelected())
cb.setChecked(true);
return convertView;
}
public Pitanja getGroup(int groupPosition) {
return groups.get(groupPosition);
}
public int getGroupCount() {
return groups.size();
}
public long getGroupId(int groupPosition) {
return groupPosition;
}
public View getGroupView(final int groupPosition, boolean isExpanded, View convertView,
ViewGroup parent) {
TextView groupName = null;
Pitanja group=(Pitanja) getGroup(groupPosition);
if(convertView==null) {
convertView=inflater.inflate(R.layout.parent_item, null);
}
groupName=(TextView) convertView.findViewById(R.id.parent_item);
groupName.setText(group.getText());
return convertView;
}
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
public boolean hasStableIds() {
return true;
}
}
my child view
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<CheckBox
android:id="#+id/checkbox_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
<TextView
android:id="#+id/textview_child_item"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
If I changle focusable of my checkbox, it doesn't work too. Someone have idea
The CheckBox will consume the click event before passing it on to the ExpandableListView click event. You'll need to manually attached a click listener to the CheckBox in the getChildView() method if you want to see those click events.

Restore listview in dialog after search

I am have a small problem in my custom dialog.
When the user search for an item in the listview, the list shows the right items, but if the user for example wants to search again, the listview shows the results from the previous search.
The problem:
How do I restore the listview after the first search?
My activity with the custom dialog
edit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showDialog();
}
});
}
}
private void showDialog() {
dialog = new Dialog(this);
View view = getLayoutInflater().inflate(R.layout.material_list, null);
searchList = (ListView) view.findViewById(R.id.searchList);
dialog.setTitle("Välj ny artikel");
final MaterialAdapter adapter = new MaterialAdapter(
InformationActivity.this, materialList);
dialog.setContentView(view);
searchList.setAdapter(adapter);
searchList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Materials itemMat = materialList.get(position);
resultProduct = itemMat.materialName;
resultProductNo = itemMat.materialNo;
result = resultProduct + " " + resultProductNo;
Toast.makeText(getApplicationContext(), result,
Toast.LENGTH_SHORT).show();
}
});
search = (EditText) dialog.findViewById(R.id.search);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
cancel = (Button) dialog.findViewById(R.id.btnCancel);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
ok = (Button) dialog.findViewById(R.id.btnOK);
ok.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
product.setText(resultProduct);
productNo.setText(resultProductNo);
dialog.dismiss();
}
});
dialog.show();
}
}
My adapter
public class MaterialAdapter extends BaseAdapter {
LayoutInflater inflater;
Context context;
List<Materials> searchItemList = null;
ArrayList<Materials> materialList = new ArrayList<Materials>();
public MaterialAdapter(Context context, List<Materials> searchItemList) {
this.context = context;
inflater = LayoutInflater.from(context);
this.searchItemList = searchItemList;
this.materialList = new ArrayList<Materials>();
this.materialList.addAll(searchItemList);
}
#Override
public int getCount() {
return searchItemList.size();
}
#Override
public Object getItem(int position) {
return searchItemList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder viewHolder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.d, null);
viewHolder = new ViewHolder();
viewHolder.tvMaterialName = (TextView) convertView
.findViewById(R.id.tvMaterialName);
viewHolder.tvMaterialNo = (TextView) convertView
.findViewById(R.id.tvMaterialNo);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tvMaterialName.setText((searchItemList.get(position))
.getMaterialName());
viewHolder.tvMaterialNo.setText((searchItemList.get(position))
.getMaterialNo());
return convertView;
}
public class ViewHolder {
TextView tvMaterialName;
TextView tvMaterialNo;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
searchItemList.clear();
if (charText.length() == 0) {
searchItemList.addAll(materialList);
} else {
for (Materials wp : materialList) {
if (wp.getMaterialName().toLowerCase(Locale.getDefault())
.startsWith(charText)) {
searchItemList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Thanks for the help :)
Try to change search.getText() to s.toString()
public void onTextChanged(CharSequence s, int start, int before,
int count) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
to
public void onTextChanged(CharSequence s, int start, int before, int count) {
resultText = s.toString().toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
A secondary thing, make materialList = searchItemList; And searchItemList empty which will be filled with search items (first run will be same elements of materialList.)
P.S Your adapter should implement Filterable in this case (implements Filterable)
#Override
public void afterTextChanged(Editable s) {
resultText = search.getText().toString()
.toLowerCase(Locale.getDefault());
adapter.filter(resultText);
}
Try this and check whether it helps

Categories

Resources