android - cannot update listview on changing an EditText value - android

I have an activity that retrieves data from a database that contains information (name, capital, population, flag image) for many countries. The main layout has an EditText to take the capital name as the input and a ListView. On launching the activity, all the countries are retrieved and shown briefly in the ListView. Then on typing in the EditText I want the ListView to show the countries with the matching capital name. But what I see is a blank ListView. Besides if the EditText is empty, I want the ListView to show all the countries as it showed in the beginning.
The main layout file is as below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FFFFFF"
android:orientation="vertical" >
<com.google.android.gms.ads.AdView
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
ads:adSize="SMART_BANNER"
ads:adUnitId="#string/banner_ad_id"
android:visibility="gone" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#id/adView"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="5dp" >
<EditText
android:id="#+id/search_input_capital"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text"
android:layout_alignParentTop="true"
android:visibility="visible" >
<requestFocus />
</EditText>
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:cacheColorHint="#00000000"
android:divider="#android:color/transparent"
android:drawSelectorOnTop="false"
android:layout_below="#id/search_input_capital">
</ListView>
</RelativeLayout>
</RelativeLayout>
And the code for the activity ( CapitalActivity.java ) is:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}
Only the necessary code segment has been shown above. What should I do to achieve the target ?
EDIT1: I mostly omitted the EfficientAdapter implementation part in the code pasted above. However I am pasting that code too this time :
public class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private Context context;
public EfficientAdapter(Context context) {
mInflater = LayoutInflater.from(context);
this.context = context;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.country_container, null);
holder = new ViewHolder();
holder.nameView = (TextView) convertView.findViewById(R.id.nameView);
holder.continentView = (TextView) convertView.findViewById(R.id.continentView);
holder.imageView = (ImageView) convertView.findViewById(R.id.imageView);
holder.detailsView = (TextView) convertView.findViewById(R.id.detailsView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
OnClickListener ocl = new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(CapitalActivity.this, CountryLearningActivity.class);
intent.putExtra(Constants.KEY_COUNTRY, items);
intent.putExtra(Constants.KEY_INDEX, position);
startActivity(intent);
}
};
Country item = items.get(position);
holder.nameView.setText(item.getCountry());
if (type.equalsIgnoreCase(filters[0]) || type.equalsIgnoreCase(filters[1])
|| type.equalsIgnoreCase(filters[2])) {
holder.continentView.setText(item.getContinent());
} else if (type.equalsIgnoreCase(filters[3])) {
holder.continentView.setText(Html
.fromHtml("Area: " + formatter.format(Double.parseDouble(item.getArea())) + " km<sup>2</sup>"));
} else if (type.equalsIgnoreCase(filters[4])) {
holder.continentView.setText("Population : " + item.getPopulation());
}
holder.imageView.setImageResource(Utils.getResID(CapitalActivity.this, item.getFlag()));
holder.detailsView.setOnClickListener(ocl);
convertView.setOnClickListener(ocl);
return convertView;
}
class ViewHolder {
TextView nameView;
ImageView imageView;
TextView continentView;
TextView detailsView;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
}

just open teh same page from your current page for the below code
enter cod protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_capital);
private ArrayList<Country> items;
private ArrayList<Country> items_all;
private ArrayList<Country> items_new;
private EfficientAdapter adapter;
private ListView listView;
EditText searchInput=(EditText)findViewById(R.id.search_input_capital);
items = new ArrayList<Country>();
items_new = new ArrayList<Country>();
listView = (ListView) findViewById(R.id.listView);
listView.setDividerHeight(10);
adapter = new EfficientAdapter(CapitalActivity.this);
listView.setAdapter(adapter);
setListItems("");
searchInput.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
String searchCapital = new String(s.toString()).trim();
items_new.clear();
for(Country myCountry : items_all) {
if( myCountry.getCapital() != null &&
myCountry.getCapital().trim().toLowerCase().contains(searchCapital)) {
items_new.add(myCountry);
}
}
items.clear();
items = (ArrayList<Country>) items_new.clone();
if(searchCapital.trim().isEmpty()){
items = items_all;
}
adapter.notifyDataSetChanged();
}
});
private void setListItems(String searchKey) {
items_all= DatabaseAccessor.getCountryList(CapitalActivity.this, type, typeValue, searchKey);
items=items_all;
adapter.notifyDataSetChanged();
}e here

Related

Get data from multiple spinners generated dynamically in linearLayout

I am trying to add a dynamic view inside my LinearLayout and trying to implement something like to catch every spinner value corresponding to time. Can anyone over here can guide me that how it can be done. I am trying it but it's not working as there can be infinite rows with spinners based on the click on the "ADD FILED" button. I need to collect value from each spinner and need to create an array then.
Here is my code :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
text1.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
String data = textOut.getText().toString();
Toast.makeText(this,""+data,Toast.LENGTH_LONG).show();
}
}
}
Dynamic view XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:orientation="horizontal">
<EditText
android:id="#+id/number_edit_text"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text2"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<EditText
android:id="#+id/number_edit_text3"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight=".2"
android:inputType="phone"/>
<Spinner
android:id="#+id/type_spinner"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight=".3"
android:entries="#array/types"
android:gravity="right" />
<Button
android:id="#+id/delete_button"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight=".1"
android:background="#android:drawable/ic_delete"
android:onClick="onDelete"/>
</LinearLayout>
Main XML :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:orientation="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:id="#+id/parent_linear_layout"
android:layout_height="wrap_content"
android:orientation="vertical" >
</LinearLayout>
<Button
android:id="#+id/add_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onAddField"
android:textColor="#FFF"
android:text="Add Field"
android:paddingLeft="5dp"/>
<Button
android:id="#+id/get_field_button"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="5dp"
android:background="#555"
android:layout_gravity="center"
android:onClick="onGetField"
android:textColor="#FFF"
android:text="Get Field"
android:paddingLeft="5dp"/>
</LinearLayout>
Please let me know your valuable suggestions on this. I have been stuck since the last day.
Here is the attached image and in the image you can see that the 3rd edit text is empty which I need to fill by using text watcher on 1st two edit-text like 2(first edit-text)-1(second edit-text) = 1 (on thrid edit-text).
Regards
Below is the second approach using Recyclerview:
MainActivity:
public class MainActivity extends AppCompatActivity {
int position=0;
List<Container_Add_model> main_modelList = new ArrayList<>();
RecyclerView recyclerView_container;
TextView Tv_add_container;
Container_Add_Adapter rvAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView_container = findViewById(R.id.recyclerView_container);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView_container.setLayoutManager(layoutManager);
Tv_add_container = findViewById(R.id.Tv_add_container);
rvAdapter = new Container_Add_Adapter(MainActivity.this, main_modelList,this, new Container_Add_Adapter.Onclick() {
#Override
public void onEvent(Container_Add_model model, int pos) {
}
});
recyclerView_container.setAdapter(rvAdapter);
Tv_add_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
rvAdapter.addClick();
}
});
}
Adapter Class :
public class Container_Add_Adapter extends RecyclerView.Adapter<Container_Add_Adapter.RvViewHolder> {
Activity context;
List<Container_Add_model> models;
Onclick onclick;
View view;
EditTextAdded editTextAdded;
private int container_number_pending, container_number_taken, container_number_given;
public Container_Add_Adapter(Activity context, List<Container_Add_model> models,EditTextAdded editTextAdded, Onclick onclick) {
this.context = context;
this.models = models;
this.editTextAdded = editTextAdded;
this.onclick = onclick;
}
#Override
public Container_Add_Adapter.RvViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
view = inflater.from(parent.getContext()).inflate(R.layout.container_item, parent, false);
RvViewHolder rvViewHolder = new RvViewHolder(view);
return rvViewHolder;
}
#Override
public void onBindViewHolder(final Container_Add_Adapter.RvViewHolder holder, final int position) {
final Container_Add_model model = models.get(position);
holder.Edttxt_given_container.setText(models.get(position).container_given+"");
holder.Edttxt_given_container.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
// models.get(position).container_given = Integer.valueOf(s.toString());
}
}
});
holder.Edttxt_taken_container.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() != 0) {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
int number = container_number_given + container_number_pending;
int input_num = Integer.parseInt(s.toString());
if (number >= input_num) {
container_number_taken = Integer.parseInt(holder.Edttxt_taken_container.getText().toString());
int final_num = number - container_number_taken;
holder.Edttxt_Pending_container.setText("" + final_num);
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
holder.Edttxt_taken_container.setText("");
}
} else {
if (!holder.Edttxt_given_container.getText().toString().isEmpty()) {
container_number_given = Integer.parseInt(holder.Edttxt_given_container.getText().toString());
if (container_number_given > 0) {
int finalnum = container_number_given + container_number_pending;
holder.Edttxt_Pending_container.setText("" + finalnum);
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
} else {
holder.Edttxt_Pending_container.setText("" + container_number_pending);
}
}
}
});
holder.Iv_delete_container.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
models.remove(position);
notifyItemChanged(position);
notifyItemRangeChanged (position, models.size());
}
});
}
public void addClick(){
Container_Add_model container_main_model = new Container_Add_model();
container_main_model.setContainer_given(0);
container_main_model.setContainer_pending(0);
container_main_model.setContainer_taken(0);
container_main_model.setContainer_id(models.size());
container_main_model.setContainer_name("");
models.add(container_main_model);
//notifyDataSetChanged(models);
notifyItemInserted(models.size() + 1);
}
#Override
public int getItemCount() {
return models.size();
}
public interface Onclick {
void onEvent(Container_Add_model model, int pos);
}
public class RvViewHolder extends RecyclerView.ViewHolder {
TextView Tv_container_type;
EditText Edttxt_given_container, Edttxt_taken_container, Edttxt_Pending_container;
LinearLayout llItem;
ImageView Iv_delete_container;
public RvViewHolder(View itemView) {
super(itemView);
Tv_container_type = itemView.findViewById(R.id.Tv_container_type);
Iv_delete_container = itemView.findViewById(R.id.Iv_delete_container);
Edttxt_given_container = itemView.findViewById(R.id.Edttxt_given_container);
Edttxt_Pending_container = itemView.findViewById(R.id.Edttxt_Pending_container);
Edttxt_taken_container = itemView.findViewById(R.id.Edttxt_taken_container);
}
}
}
Here is what you were missing :
public class MainActivity extends Activity {
private LinearLayout parentLinearLayout;
private ArrayList<> mList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
parentLinearLayout=(LinearLayout) findViewById(R.id.parent_linear_layout);
}
public void onAddField(View v) {
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View rowView=inflater.inflate(R.layout.container_item, null);
final EditText text1 = (EditText) rowView.findViewById(R.id.number_edit_text);
final EditText text2 = (EditText) rowView.findViewById(R.id.number_edit_text2);
final EditText text3 = (EditText) rowView.findViewById(R.id.number_edit_text3);
final Spinner mSpinner = (Spinner) rowView.findViewById(R.id.type_spinner);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
String selectedDiv = parent.getItemAtPosition(position).toString();
Toast.makeText(MainActivity.this, ""+selectedDiv, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent)
{
// can leave this empty
}
});
text1.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
text3.setText(text1.getText().toString());
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text2.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
int val = Integer.parseInt(text1.getText().toString());
int val2 = Integer.parseInt(text2.getText().toString());
if(val2>val)
{
}else{
int finalval=val-val2;
text3.setText(""+finalval);
}
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
text3.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
}
#Override
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start,
int before, int count) {
if (s.length() > 0) {
Toast.makeText(MainActivity.this,""+s.toString(),Toast.LENGTH_LONG).show();
}
}
});
parentLinearLayout.addView(rowView, parentLinearLayout.getChildCount());
}
public void onDelete(View v) {
parentLinearLayout.removeView((View) v.getParent());
}
public void onGetField(View v){
mList = new ArrayList<>();
int count = parentLinearLayout.getChildCount();
for (int i = 0; i < count; i++) {
final View row = parentLinearLayout.getChildAt(i);
EditText textOut = (EditText) row.findViewById(R.id.number_edit_text);
EditText textOut2 = (EditText) row.findViewById(R.id.number_edit_text2);
EditText textOut3 = (EditText) row.findViewById(R.id.number_edit_text3);
Spinner spinner = (Spinner)row.findViewById(R.id.type_spinner);
mList.add(new DataList( textOut.getText().toString(),
textOut2.getText().toString()
, textOut3.getText().toString(),spinner.getSelectedItem().toString()
));
}
}
}
Datalist Model :
public class DataList {
public String given;
public String taken;
public String pending;
public String spinnerItemSelected;
public DataList(String given, String taken, String pending, String spinnerItemSelected) {
this.given = given;
this.taken = taken;
this.pending = pending;
this.spinnerItemSelected = spinnerItemSelected;
}
}
Convert your String array to ArrayList and pass it to Adapter and use below code or change below code with your String[].
You need to implement Filterable to your Adapter class and Override getFilter()
public class ListFilterActivity extends ListActivity {
private List<String> list = new ArrayList<String>();
List<String> mOriginalValues;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final MyAdapter adapter = new MyAdapter(this, getModel());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
// Add Text Change Listener to EditText
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Call back the Adapter with current character to Filter
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
private List<String> getModel() {
list.add("Linux");
list.add("Windows7");
list.add("Suse");
list.add("Eclipse");
list.add("Ubuntu");
list.add("Solaris");
list.add("Android");
list.add("iPhone");
list.add("Windows XP");
return list;
}
}
// Adapter Class
public class MyAdapter extends BaseAdapter implements Filterable {
List<String> arrayList;
List<String> mOriginalValues; // Original Values
LayoutInflater inflater;
public MyAdapter(Context context, List<String> arrayList) {
this.arrayList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = inflater.inflate(R.layout.row, null);
holder.textView = (TextView) convertView
.findViewById(R.id.textview);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(arrayList.get(position));
return convertView;
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,FilterResults results) {
arrayList = (List<String>) results.values; // has the filtered values
notifyDataSetChanged(); // notifies the data with new filtered values
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults(); // Holds the results of a filtering operation in values
List<String> FilteredArrList = new ArrayList<String>();
if (mOriginalValues == null) {
mOriginalValues = new ArrayList<String>(arrayList); // saves the original data in mOriginalValues
}
/********
*
* If constraint(CharSequence that is received) is null returns the mOriginalValues(Original) values
* else does the Filtering and returns FilteredArrList(Filtered)
*
********/
if (constraint == null || constraint.length() == 0) {
// set the Original result to return
results.count = mOriginalValues.size();
results.values = mOriginalValues;
} else {
constraint = constraint.toString().toLowerCase();
for (int i = 0; i < mOriginalValues.size(); i++) {
String data = mOriginalValues.get(i);
if (data.toLowerCase().startsWith(constraint.toString())) {
FilteredArrList.add(data);
}
}
// set the Filtered result to return
results.count = FilteredArrList.size();
results.values = FilteredArrList;
}
return results;
}
};
return filter;
}
}

Focus with order editTexts in listview

My app is barcodeReader which user read to barcodeID set it Textview and he can enter the number of product in editText.I implement in listview which include textview and editText. When user scan to barcodeNumber, i set to it on textView and but i want after set to text automatically focus the edit text in order .How can i do that?
Edit!!
I already add to request focus on but always focus on 1. editText and when 2. Barcode scanned 1.editText value again take "0";
This is my listView;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:ellipsize="end"
android:padding="5dp"
android:singleLine="true" />
<EditText
android:id="#+id/Quantity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:ellipsize="end"
android:padding="5dp"
android:singleLine="true"
android:inputType="number">
<requestFocus />
</EditText>
</LinearLayout>
This is my adapter;
public class ListViewAdapter extends BaseAdapter {
public ArrayList<Model> productList;
Activity activity;
public ListViewAdapter(Activity activity, ArrayList<Model> 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;
}
private class ViewHolder {
TextView ID;
EditText Quantity;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView = inflater.inflate(R.layout.listview_row, null);
holder = new ViewHolder();
holder.ID = (TextView) convertView.findViewById(R.id.ID);
holder.Quantity = (EditText) convertView.findViewById(R.id.Quantity);;
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Model item = productList.get(position);
holder.ID.setText(item.getID().toString());
holder.Quantity(String.valueOf(item.getQuantity()));
return convertView;
}
}
And here is the Activity;
public class BarcodeReaderActivity extends AppCompatActivity {
Button btnBarcodeReader;
EditText Quantity;
private ArrayList<Model> mlist;
Model item;
ListViewAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcodereader);
mlist= new ArrayList<Model>();
ListView lview = (ListView) findViewById(R.id.listview);
adapter = new ListViewAdapter(this, mlist);
QuantityRowID = findViewById(R.id.Quantity);
lview.setAdapter(adapter);
btnBarcodeReader = (Button)findViewById(R.id.btnBarcodeReader);
adapter.notifyDataSetChanged();
final Activity activity = this;
btnBarcodeReader.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scan");
integrator.setCameraId(0);
integrator.setBeepEnabled(false);
integrator.setBarcodeImageEnabled(false);
integrator.initiateScan();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
Log.d("MainActivity", "Scanned");
//Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
populateList(result.getContents());
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
QuantityRowID.requestFocus();
int val = Integer.parseInt( QuantityRowID.getText().toString() );
item.Quantity=val;
QuantityRowID.setText(val);
adapter.notifyDataSetChanged();
}
}
public void populateList(String ID){
item = new Model(ID,0);
mlist.add(item);
adapter.notifyDataSetChanged();
}
}
Just simply set request focus on your EditText after setting all view like
//your other view like textview and imageview if you have
Quantity.requestFocus();
Try this code..
edittextbox.requestFocus();
and xml code..
<EditText ...>
<requestFocus />
</EditText>
In your Adapter getView() method write this
holder.ID.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) {
holder.Quantity.requestFocus();
}
});
This is a workaround, it will forcefully show the keyboard to targeted editText.
InputMethodManager keyboard = (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
Try this:
public void populateList(String ID){
item = new Model(ID,0);
mlist.add(item);
adapter.notifyDataSetChanged();
ListView listView = (ListView) findViewById(R.id.listview);
listView.smoothScrollToPosition(mlist.size() - 1);
LinearLayout childView = (LinearLayout)listView.getChildAt(listView.getLastVisiblePosition() - listView.getFirstVisiblePosition());
EditText quantity = (EditText)childView.findViewById(R.id.Quantity);
quantity.requestFocus();
}
Hope it helps!!

How to select only part of a listview based on different requirements by the user?

I am trying to develop an android mobile application whereby i am required to display part of a listviews which has at least 100 items.
Now i,being the admin of a college,i has listed 100 subjects to be taught.(all to be listed in a listview.All of the subjects have a point and in order for a strudent to apply for this course he/she need to have exact of higher points.An indicative sample is below:
English:24
Spanish:16
MAths:28
Science:26
French:16
Management:22
Law:30
Asian Language:10
Now the student needs to enter his/her point and based(EXACT OR LOWER POINT)on that, he/she get the list of subjects he/she is eligible to apply for.
E.g Enter your points:24
the output in the listview should give the following:
French:16
Management:22
English:24
Asian Language:10
I tried this but am stuck and could not complete the codes:
Course.java
public class Course {
private String name;
private int points;
public Course(String name, int points) {
this.name = name;
this.points = points;
}
public String getName() {
return name;
}
public int getPoints() {
return points;
}
#Override
public String toString() {
return getName();
}
}
Course[] courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
Button searchButton = (Button) findViewById(R.id.btn_search);
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
List<Course> courseList = new ArrayList<Course>(Arrays.asList(courses));
// initialize the adapter with courseList... //
// this code inside the Button's onClick
int points = Integer.parseInt(editText.getText().toString());
for (Course c : courses) {
if (c.getPoints() <= points) {
adapter.add(c);
}
}
course.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<EditText
android:layout_width="0dp"
android:layout_weight="1"
android:maxLines="1"
android:inputType="number"
android:layout_height="wrap_content"
android:hint="Enter your points:"
android:id="#+id/editText"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/btn_search"/>
</LinearLayout>
<ListView
android:id="#+id/courseNames"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
My solution as below -
MainActivity
public class MainActivity extends AppCompatActivity {
ListView myList;
EditText edtSearch;
Button btnSearch;
listAdapter adapter;
ArrayList<Course> alSearchCourses;
Course[] courses;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myList = (ListView) findViewById(R.id.myList);
edtSearch = (EditText) findViewById(R.id.edtSearch);
btnSearch = (Button) findViewById(R.id.btnSearch);
courses = new Course[]{
new Course("Medicine", 30),
new Course("Physics", 28),
new Course("Math", 24),
new Course("English", 20)
};
adapter = new listAdapter(this, courses);
myList.setAdapter(adapter);
edtSearch.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) {
if (count == 0) {
adapter = new listAdapter(MainActivity.this, courses);
myList.setAdapter(adapter);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alSearchCourses = new ArrayList<>();
int points = Integer.parseInt(edtSearch.getText().toString());
for (int i = 0; i < courses.length; i++) {
Course c2 = courses[i];
if (c2.getPoints() <= points) {
alSearchCourses.add(c2);
}
}
Course searchCourses [] = new Course[alSearchCourses.size()];
searchCourses = alSearchCourses.toArray(searchCourses);
adapter = new listAdapter(MainActivity.this, searchCourses);
myList.setAdapter(adapter);
}
});
}
}
listAdapter
public class listAdapter extends BaseAdapter {
Context context;
Course[] courses;
LayoutInflater inflater;
public listAdapter(Context context, Course[] courses) {
this.context = context;
this.courses = courses;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return courses.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = inflater.inflate(R.layout.list_item_layout, null);
}
TextView txtCourse = (TextView) convertView.findViewById(R.id.txtCourse);
txtCourse.setText(courses[position].getName() + "-" + courses[position].getPoints());
return convertView;
}
}
Hope it helps :)

custom MultiAutoCompleteTextView with drop down

I have a class:
public class MultiObjectSelectorView extends LinearLayout {
private List<String> items;
private List<String> default_items;
private List<String> display_items;
private EditText text_feild;
private ListView drop_down;
public MultiObjectSelectorView(Context context, AttributeSet attrs) {
super(context, attrs);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.multiobjectselectorlayout, this, true);
drop_down = (ListView) findViewById(R.id.drop_down);
text_feild = (EditText) findViewById(R.id.MyTextView);
display_items = new ArrayList<String>();
final ListAdapter adapter = new ListAdapter(context,display_items);
drop_down.setAdapter(adapter);
text_feild.addTextChangedListener(new TextWatcher() {
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before,int count) {
if(!s.toString().equals("")){
display_items = new ArrayList<String>();
String str = s.toString();
for(int i = 0;i<items.size();i++){
String[] splited = items.get(i).split("\\s+");
int isFound = 0;
for(int x = 0;x<splited.length;x++){
if(splited[x].startsWith(str)){
isFound = 1;
x = splited.length;
}
}
if(isFound == 1){
display_items.add(items.get(i));
}
}
}else{
display_items = new ArrayList<String>();
}
adapter.setListData(display_items);
adapter.notifyDataSetChanged();
}
public void afterTextChanged(Editable s) {
}
});
drop_down.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
}
public void SetList(String[] list){
items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
default_items = items;
}
public void SetList(String[] list,String[] list2){
items = new ArrayList<String>();
default_items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
for(int i = 0;i<list2.length;i++){
default_items.add(list2[i]);
}
}
public void SetList(String[] list,String[] list2,String[] list3){
items = new ArrayList<String>();
default_items = new ArrayList<String>();
for(int i = 0;i<list.length;i++){
items.add(list[i]);
}
for(int i = 0;i<list2.length;i++){
default_items.add(list2[i]);
}
for(int i = 0;i<list3.length;i++){
items.add(list3[i]);
}
}
private class ListAdapter extends ArrayAdapter<String> {
private final Context context;
private List<String> values;
public ListAdapter(Context context, List<String> values) {
super(context, R.layout.dropdownlayout, values);
this.context = context;
this.values = values;
}
public void setListData(List<String> values2){
values = values2;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.dropdownlayout, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.drop_down_text_view);
textView.setText(values.get(position));
return rowView;
}
#Override
public int getCount() {
return values.size();
}
#Override
public String getItem(int position) {
return values.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
}
The reason I don't use a MultiAutoCompleteTextView is that (1). I wanted the items in a drop down, (2). the drop downs not going to be used as an auto complete list it gives custom suggestions in a drop down view(they don't do anything yet, but eventually they'll add what is clicked on into a list).
The problem is that the listview, when expanded pushes down everything below the custom viewgroup. I would like it to overlay everything else.
also the layout file:
sion="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="#+id/MyTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/deit_restr_text"
android:ems="10" >
</EditText>
<ListView
android:id="#+id/drop_down"
android:layout_width="match_parent"
android:layout_height="fill_parent" >
</ListView>
</LinearLayout>

Looking for best match solution on searching function on listview

i wanted to add a search function to my customize list view. i actually search through internet for few hours, but i unable to follow all those complicated tutorial or demo, so i decided to post my problem here. Hope somebody can actually help me to solve this. here is my code
ListView lv;
EditText inputSearch;
CustomListView testingAdapter;
//at oncreate method
lv = (ListView) findViewById(R.id.lvEditSavingList);
inputSearch = (EditText) findViewById(R.id.inputSearch);
loadListViewData();
private void loadListViewData() {
// TODO Auto-generated method stub
UnderControlDb db = new UnderControlDb(getApplicationContext());
String[] info = db.MySavingShowData();
int counter = info.length;
Integer[] imageID = new Integer[counter];
for(int i=0;i<counter;i++){
imageID[i] = R.drawable.edit_notes_list;
}
testingAdapter = new CustomListView(MySaving.this, info, imageID);
lv.setAdapter(testingAdapter);
}
then this is my customize class
public class CustomListView extends ArrayAdapter<String>{
private final Activity context;
private final String[] data;
private final Integer[] imageId;
public CustomListView(Activity context,String[] data, Integer[] imageId) {
super(context, R.layout.my_saving_list, data);
this.context = context;
this.data = data;
this.imageId = imageId;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.my_saving_list, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvSavingListView);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgS);
txtTitle.setText(data[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
and my xml code
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TableRow>
<TextView
android:id="#+id/tvSavingListView"
android:layout_width="wrap_content"
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textSize="16sp"
android:layout_height="30dp" />
<ImageView
android:id="#+id/imgS"
android:layout_width="25dp"
android:layout_height="25dp"/>
</TableRow>
</TableLayout>
I've wrote a small sample in order to show you how you can search data from your listView.
Find below the code, and do not hesitate to ask me any question for more clarification.
public class TestSearch extends Activity {
ListView lv;
EditText inputSearch;
CustomListView testingAdapter;
public class listContent{
public String info;
public int imageInfo;
public listContent(String info, int imageInfo) {
this.info = info;
this.imageInfo = imageInfo;
}
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public int getImageInfo() {
return imageInfo;
}
public void setImageInfo(int imageInfo) {
this.imageInfo = imageInfo;
}
}
ArrayList<listContent> itemsContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_search);
itemsContent = new ArrayList<listContent>();
CustomListView testingAdapter;
lv = (ListView) findViewById(R.id.lvEditSavingList);
inputSearch = (EditText) findViewById(R.id.inputSearch);
inputSearch.addTextChangedListener(textWatcher);
loadListViewData();
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
String text = inputSearch.getText().toString().toLowerCase(Locale.getDefault());
testingAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
};
private void loadListViewData() {
// TODO Auto-generated method stub
itemsContent.add(new listContent("text", R.drawable.ic_launcher));
itemsContent.add(new listContent("hello", R.drawable.ic_launcher));
itemsContent.add(new listContent("dear", R.drawable.ic_launcher));
itemsContent.add(new listContent("test", R.drawable.ic_launcher));
itemsContent.add(new listContent("lol", R.drawable.ic_launcher));
testingAdapter = new CustomListView(TestSearch.this, itemsContent);
lv.setAdapter(testingAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.test_search, menu);
return true;
}
public class CustomListView extends BaseAdapter{
private final Context mContext;
private ArrayList<listContent> items;
ArrayList<listContent> filtereditems;
public CustomListView(Context context, ArrayList<listContent> items) {
this.mContext= context;
this.items = items;
this.filtereditems = new ArrayList<listContent>();
this.filtereditems.addAll(items);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View rowView= inflater.inflate(R.layout.my_saving_list, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvSavingListView);
ImageView imageView = (ImageView) rowView.findViewById(R.id.imgS);
txtTitle.setText(items.get(position).getInfo());
imageView.setImageResource(items.get(position).getImageInfo());
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(filtereditems);
}
else
{
for (listContent wp : filtereditems)
{
if(wp.getInfo().startsWith(charText))
{
items.add(wp);
}
}
}
notifyDataSetChanged();
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int arg0) {
return items.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
}
}

Categories

Resources