I would like to enable search functionality to AutoCompleteTextView. My requirement is like this: when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the AutoCompleteTextView, if again, I cleared the AutoCompleteTextView and tried to type "co", then it should show the drop-down list "copy","come","cow".... I want to enable this feature to my AutoCompleteTextView view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
AutoCompleteTextView acTV;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
acTV = (AutoCompleteTextView)findViewById(R.id.acTV);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
acTV.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=acTV.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(acTV.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0,textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}}
And this is my custom ListView Adapter:
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;}
public int getCount() {
// TODO Auto-generated method stub
return title.length;}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;}
public View getView(int position, View convertView, ViewGroup parent){
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;}}
Related
First, please bear with me as I am just a beginner in learning Android.
What I want is that when the user adds an item from another activity, the details will be shown from my listview in the MainActivity (I am using a regular expression for my search results). And when the user tries to search an item, I want the search results to show.
From my code below, only the added items are shown and the search results will not display.
Here is a snippet of my code from MainActivity.java
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.notifyDataSetChanged();
}//end if
}
//update the listview
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
Student.java
public class Student {
Uri uriImage;
String studlname, studfname, studcourse;
//constructor
public Student(Uri uriImage, String studlname, String studfname, String studcourse) {
super();
this.uriImage = uriImage;
this.studlname = studlname;
this.studfname = studfname;
this.studcourse = studcourse;
}
//getters and setters
public Uri getUriImage() {
return uriImage;
}
public void setUriImage(Uri uriImage) {
this.uriImage = uriImage;
}
public String getStudlname() {
return studlname;
}
public void setStudlname(String studlname) {
this.studlname = studlname;
}
public String getStudfname() {
return studfname;
}
public void setStudfname(String studfname) {
this.studfname = studfname;
}
public String getStudcourse() {
return studcourse;
}
public void setStudcourse(String studcourse) {
this.studcourse = studcourse;
}
}
Update your code as below
ArrayList<Student> studentArrayList = new ArrayList<>();
ArrayList<Student> findlist = new ArrayList<>();
CustomAdapter adapter, anotheradapter;
private Uri imageUri;
ListView lv;
AlertDialog.Builder show_builder;
AlertDialog dialog;
LinearLayout layout;
ImageView imageView;
TextView stud_lname, stud_fname, stud_course;
AdapterView.AdapterContextMenuInfo info;
//
EditText txtsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
anotheradapter = new CustomAdapter(this, findlist);//adapter for finding the list
adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
adapter.notifyDataSetChanged();
lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
//
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
anotheradapter.refreshList(findlist)
}//end if
}
//update the listview
anotheradapter.refreshList(findlist)
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
Add refresh List method in adapter
public class CustomAdapter extends BaseAdapter {
Context context;
//data container
ArrayList<Student> list;
LayoutInflater inflater;
//contructor
public CustomAdapter(Context context, ArrayList<Student> list) {
this.context = context;
this.list = list;
this.inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
public void refreshList(ArrayList<Student> list){
this.list = list;
notifyDataSetChanged()
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.custom_layout, parent, false);
holder.iv = (ImageView) convertView.findViewById(R.id.imageView);
holder.lname = (TextView) convertView.findViewById(R.id.textLastname);
holder.fname= (TextView) convertView.findViewById(R.id.textFirstname);
holder.course = (TextView) convertView.findViewById(R.id.textCourse);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
//inflate
holder.iv.setImageURI(list.get(position).getUriImage());
holder.lname.setText(list.get(position).getStudlname());
holder.fname.setText(list.get(position).getStudfname());
holder.course.setText(list.get(position).getStudcourse());
return convertView;
}
//creating a static class
static class ViewHolder{
ImageView iv;
TextView lname, fname,course;
}
}
You need to update your adapter initialization as below.
Update in the onCreate() method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.student_listview);
txtsearch = (EditText) findViewById(R.id.textsearch);
// initialize the findlist to show all student list by default
findlist.addAll(studentArrayList);
anotheradapter = new CustomAdapter(this, findlist);
// ----- Remove these lines - as you don't need multiple adapters
//adapter = new CustomAdapter(this, studentArrayList);//adapter for displaying the added student
//adapter.notifyDataSetChanged();
//lv.setAdapter(adapter);
lv.setAdapter(anotheradapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
show_builder = new AlertDialog.Builder(this);
txtsearch.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) {
findlist.clear();
//using regular expressions
String s1 = s.toString();
Pattern pattern = Pattern.compile(s1);
for(int i=0; i<studentArrayList.size(); i++){
Matcher matcher = pattern.matcher(studentArrayList.get(i).getStudlname());
if(matcher.find()){
findlist.add(studentArrayList.get(i));
// Remove the below line as you don't need to update the list multipletimes
//anotheradapter.notifyDataSetChanged();
}
}
// Add these lines to show the list of all student when the searchbox is empty. This will reset the findList to initial state.
if (txtsearch.getText().length() == 0 && findlist.isEmpty()) {
findlist.addAll(studentArrayList);
}
anotheradapter.notifyDataSetChanged();
}
#Override
public void afterTextChanged(Editable s) {
}
});
}
I'm trying to build an Attendance Manager app for students and am using a custom ListView to display subject names and minimum attendance when tapped on.
These are the Issues I'm facing::
1) I want my first list item to be an "Add a subject item" and on tapping on that it goes to AddSubjectActivity and stores everything via SharedPreferences.
2)Once the submit button is pressed in the AddSubjectActivity i want the next list item to say "Tap to add a subject" and so on.
3) Basically ,suppose the ListView has 5 items, tapping on each item takes me to the AddSubject Activity, but information corresponding to the respective list Item being tapped is displayed in it.
This is my Code:
Class CustomAdapter
public class CustomAdapter extends BaseAdapter{
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(SecondActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = ( LayoutInflater )context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Holder holder=new Holder();
SecondActivity second=new SecondActivity();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView);
holder.img=(ImageView) rowView.findViewById(R.id.statsImageView);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
context.startActivity(new Intent(context, AddSubject.class));
}
});
return rowView;
}
}
SecondActivity: The Activity that contains the ListView
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle=getIntent().getExtras();
String fullNameFinal = bundle.getString("fullName");
String courseFinal = bundle.getString("course");
int avgAttendanceFinal= bundle.getInt("avgAttendance");
boolean logInStatusFinal = bundle.getBoolean("logInStatus");
nameTextView=(TextView)findViewById(R.id.nameTextView);
courseTextView=(TextView)findViewById(R.id.courseTextView);
nameTextView.setText(fullNameFinal);
courseTextView.setText(courseFinal);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
ListView lv;
Context context;
ArrayList prgmName;
int [] prgmImages={R.drawable.listblockgold,R.drawable.listblockindigo,R.drawable.listblocklime,R.drawable.listblockorange,R.drawable.listblockpink,R.drawable.listblockred,R.drawable.listblocksilver,R.drawable.listblocktan,R.drawable.listblockteal};
String [] prgmNameList={"Maths","P.Comm.","IOT","Operating Systems","Web Programming","DSP","PHP","Jquery","JavaScript"};
context=this;
lv=(ListView) findViewById(R.id.testListView);
lv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages));
`AddSubject Activity`
public class AddSubject extends AppCompatActivity {
//Buttons
Button missedMinus;
Button missedPlus;
//ButtonsEnd
//TextViews
TextView safeBunksNumber;
TextView missedLectures;
TextView totalLecturesTextView ;
TextView percentageTextView;
//TextViewsEnd
EditText missedLecturesTextView;
ProgressBar progressBar;
static String s= Integer.toString(10);
public void missedMinusClick(View view)
{
totalLecturesTextView=(TextView)findViewById(R.id.totalLecturesTextView);
int totalLectures= Integer.parseInt(totalLecturesTextView.getText().toString());
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures-1));
safeBunksNumber=(TextView)findViewById(R.id.safeBunksNumber);
int safeBunksNumber;
}
public void missedPlusClick(View view2)
{
missedLecturesTextView=(EditText)findViewById(R.id.missedLecturesTextView);
int missedLectures= Integer.parseInt(missedLecturesTextView.getText().toString());
missedLecturesTextView.setText(Integer.toString(missedLectures+1));
}
public void submitOnClick1(View view3)
{
EditText subName = (EditText)findViewById(R.id.subName);
EditText totalLecturesTextView = (EditText)findViewById(R.id.totalLecturesTextView);
EditText missedLecturesTextView =(EditText)findViewById(R.id.missedLecturesTextView);
String subjectName = subName.getText().toString();
int totalLectures = Integer.parseInt(totalLecturesTextView.getText().toString());
int missedLectures = Integer.parseInt(missedLecturesTextView.getText().toString());
SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.yashrandive.attendancemanager", Context.MODE_PRIVATE);
sharedPreferences.edit().putString("subName",subjectName);
sharedPreferences.edit().putInt("totalLectures",totalLectures);
sharedPreferences.edit().putInt("missedLectures",missedLectures);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_subject);
}
}
Now i want to make filter but i really don't know how to do it. I've read some tutorials and tried but it still does not work. Please help me!
i want to implement the search functionality.
code of class apdater:
public class PlaceAdapter extends BaseAdapter {
private static ArrayList<Place> searchArrayList;
private LayoutInflater mInflater;
public PlaceAdapter(Context context, ArrayList<Place> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.row, null);
holder = new ViewHolder();
holder.txtName = (TextView) convertView
.findViewById(R.id.label_place);
holder.txtAddress = (TextView) convertView
.findViewById(R.id.label_address);
holder.txtPhone = (TextView) convertView
.findViewById(R.id.label_distance);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txtName.setText(searchArrayList.get(position).getName());
holder.txtAddress.setText(searchArrayList.get(position).getAddress());
holder.txtPhone.setText(searchArrayList.get(position).getPhone());
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView txtAddress;
TextView txtPhone;
}
}
code of class activity
public class ServiceDetail extends Activity {
private String DB_NAME = "Danang Travel.sqlite";
private PlaceAdapter adapter = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.servicedetail);
final ArrayList<Place> searchResults = GetSearchResults();
final EditText filterEditText = (EditText) findViewById(R.id.filter_text);
final ListView lvPlace = (ListView) findViewById(R.id.listView1);
adapter = new PlaceAdapter(this, searchResults);
lvPlace.setAdapter(adapter);
lvPlace.setTextFilterEnabled(true);
// Set Focus*****************************************
lvPlace.setFocusableInTouchMode(true);
lvPlace.requestFocus();
lvPlace.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View arg0, boolean arg1) {
// TODO Auto-generated method stub
// arg0.setBackgroundColor(arg1 ? Color.GRAY : Color.BLACK);
// lvPlace.setItemsCanFocus(true);
}
});
// lvPlace.setClickable(true);
/******************************************************/
// filter search
filterEditText.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
//ServiceDetail.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lvPlace.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Object o = lvPlace.getItemAtPosition(position);
Place fullObject = (Place) o;
Toast toast = Toast.makeText(ServiceDetail.this,
"You have chosen: " + " " + fullObject.getName(),
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
}
});
}
private ArrayList<Place> GetSearchResults() {
ArrayList<Place> results = new ArrayList<Place>();
SQLiteDatabase DB = null;
Intent t = getIntent();
Bundle extra = t.getExtras();
String temp = extra.getString("k");
try {
DB = this.openOrCreateDatabase(DB_NAME, MODE_PRIVATE, null);
Cursor c = DB.rawQuery(
"SELECT Name,Address,TypeID FROM ServiceDetail Where SerID = '"
+ temp + "' ORDER BY Name", null);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
Place k = new Place();
// The Cursor is now set to the right position
String n = c.getString(c.getColumnIndex("Name"));
String a = c.getString(c.getColumnIndex("Address"));
String p = c.getString(c.getColumnIndex("TypeID"));
k.setName(n);
k.setAddress(a);
k.setPhone(p);
results.add(k);
}
} catch (SQLiteException se) {
Log.e(getClass().getSimpleName(),
"Could not create or Open the database");
} finally {
DB.close();
}
return results;
}
}
Now i want to make filter but i really don't know how to do it. I've read some tutorials and tried but it still does not work. Please help me!
Here you go :)
//Firstly here is your edittext on which you want to filter
EditTextfilterText = (EditText) findViewById(R.id.search_box);
filterText.clearComposingText();
//Give the edittext the watcher as a text listener
filterText.addTextChangedListener(filterTextWatcher);
//This will listen to key events such as you entering something inside the edit text
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
//Called after text changed
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
//Called each time you enter something into the edittext to filter your list or whatever
public void onTextChanged(CharSequence s, int start, int before,
int count) {
//Adapter creating code
//......
//Filter calling code
adapter.getFilter().filter(s, new FilterListener() {
#Override
public void onFilterComplete(int count) {
//Just for fun do something here once filtering is done
}
});
}
}
};
Now inside your custom adapter you would have the following:
public Filter getFilter() {
filter = new DrugListFilter();
return filter;
}
private class MyFilterName extends Filter{
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults retval = new FilterResults();
ArrayList<something> filt = new ArrayList<something>();
//... Some code to filter your current Adapter data by the constaint
//Pass the results to retval
retval.count = filt.size();
retval.values = filt;
}
//return retval
return retval;
}
//This is called once performFiltering is done
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
filteredItems.clear();
//This is your array of filtered items
filteredItems.addAll((ArrayList)results.values);
doneFilter = true;
//Notify the dataset that it needs to update
notifyDataSetChanged();
}
}
I Have 2D Array and this 2D Array has Strings. I would like to know How to Display the Strings in ListView?how to scroll both vertically and horizontally?
String[][] board = new String[][] {{"1","10","100"},{"hi0","1hello","test"},{"test31","test32","test43"}};
It seem to be you are asking basic things, How to use ListView. please check it you will get all about ListView.
Android ListView and ListActivity
It is to display two-d array in list view.Here's my source code in which i have implemented 2-d array in list view
My Adapter class:-
public class MyArrayAdapter extends ArrayAdapter<List>{
QuickActionDemo quickActionDemo;
public Activity context;
public List<List> list;
int CAMERA_PIC_REQUEST=10;
private int selectedPos = -1;
int clickPosition,rowPosition;
Camera camera;
private static final String TAG = "CameraDemo";
public MyArrayAdapter(Activity context,List<List> list) {
super(context,R.layout.attach_pic,list);
this.context = context;
this.list = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position+1;
}
static class ViewHolder {
public TextView tv1,tv2,tv3;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = null;
final ViewHolder holder = new ViewHolder();
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
rowView = inflator.inflate(R.layout.attach_pic, null);
holder.tv1 = (TextView) rowView.findViewById(R.id.defectpic);
holder.tv2 = (TextView) rowView.findViewById(R.id.no_of_uploded_pics);
holder.tv3 = (TextView) rowView.findViewById(R.id.camera);
holder.tv3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Intent in = new Intent(getContext(),QuickActionDemo.class);
// context.startActivityForResult(in,0);
}
});
rowView.setTag(holder);
List itemVal1 = (List)getItem(position);
String st1 = (String)itemVal1.get(0);
holder.tv1.setText(st1);
List itemVal2 = (List)getItem(position);
String st2 = (String)itemVal2.get(1);
holder.tv2.setText(st2);
} else {
rowView = convertView;
((ViewHolder) rowView.getTag()).tv1.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv2.setTag(list.get(position));
((ViewHolder) rowView.getTag()).tv3.setTag(list.get(position));
}
return rowView;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return list.size();
}
}
Here's my activity class:-
public class MyActivity extends ListActivity {
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
// requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); // to hide the virtual keyboard
setContentView(R.layout.defect_pic_listview);
try{
ArrayAdapter<List> adapter = new MyArrayAdapter(this,makeList());
setListAdapter(adapter);
}
}
private List<List> makeList(){
List<List> all = new ArrayList();
String[] newArray1 = {"Defect Picture1", "2"};
List<String> newListObject1 = Arrays.asList(newArray1);
String[] newArray2 = {"Defect Picture2","1"};
List<String> newListObject2 = Arrays.asList(newArray2);
String[] newArray3 = {"Defect Picture3","4"};
List<String> newListObject3 = Arrays.asList(newArray3);
String[] newArray4 = {"Defect Picture4","1"};
List<String> newListObject4 = Arrays.asList(newArray4);
String[] newArray5 = {"Defect Picture5","3"};
List<String> newListObject5 = Arrays.asList(newArray5);
all.add(newListObject1);
all.add(newListObject2);
all.add(newListObject3);
all.add(newListObject4);
all.add(newListObject5);
return all;
}
}
Creating a model as an inner class always works well.
Good way to store any number of items.
public class ActivityClass extends Activity {
...
ArrayList<ValuesModel> listViewValues = new ArrayList<ValuesModel>();
listViewValues.add(new ValuesModel("row title", "row details"));
ListViewAdapter listAdapter = new ListViewAdapter(this, listViewValues);
((ListView) findViewById(android.R.id.list)).setAdapter(listAdapter);
...
public class ValuesModel {
private String rowTitle;
private String rowDetails;
public ValuesModel(String rowTitle, String rowDetails) {
this.rowTitle = rowTitle;
this.rowDetails = rowDetails;
}
public String getRowTitle() {
return rowTitle;
}
public String getRowDetails() {
return rowDetails();
}
}
Then inside of your list adapter,
public class ListViewAdapter extends ArrayAdapter<ActivityClass.ValuesModel> {
private ArrayList<ActivityClass.ValuesModel> mValues;
...
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
//here whenever you need to retrieve your values, just say:
// mValues.get(position).getRowTitle();
// mValues.get(position).getRowDetails();
//if you use a viewholder pattern, you can do this:
viewHolder.rowTitle = (TextView) convertView.findViewById(R.id.row_title_textview);
viewHolder.rowTitle.setText(mValues.get(position).getRowTitle());
...
}
}
I would like to enable search functionality to EditText. My requirement is like this:
when someone types with some letter, suppose the user types 'a', then it should show all the words which starts with 'a' should be shown as a drop down list. For example, if I first typed "copy" in the EditText, if again, I cleared the EditText and tried to type "co", then it should show the drop-down list "copy","come","cow"....
I want to enable this feature to my EditText view. It worked when I had a ListView with only a textview inside, but now that I have two textview in my ListView it doesn't work.
This is my activity:
public class sedactivity extends Activity {
ListView lview;
ListViewAdapter lviewAdapter;
EditText ed;
private static final String first[] = {
"America",
"Busta",
"Cactus",
"Fire",
"Garden",
"Hollywood",
"King",};
private static final String second[] = {
"Uniti",
"Chiusa",
"Verde",
"Fiamme",
"Aperto",
"Boulevard",
"Kong",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ed = (EditText)findViewById(R.id.EditText1);
lview = (ListView) findViewById(R.id.listView2);
lviewAdapter = new ListViewAdapter(this, first, second);
System.out.println("adapter => "+lviewAdapter.getCount());
lview.setAdapter(lviewAdapter);
lview.setTextFilterEnabled(true);
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
textlength=ed.getText().length();
arr_sort.clear();
for(int i=0;i<first.length;i++)
{
if(textlength<=first[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) first[i].subSequence(0, textlength)))
{
arr_sort.add(first[i]);
}
}
}
}});}
}
And this is my ListView Adapter
public class ListViewAdapter extends BaseAdapter{
Activity context;
String title[];
String description[];
public ListViewAdapter(Activity context, String[] title, String[] description) {
super();
this.context = context;
this.title = title;
this.description = description;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
}
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
if (convertView == null)
{
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView.findViewById(R.id.textView2);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
return convertView;
}
}
I think an AutoCompleteTextView might be more suitable to implement this feature.
Check out this example to create your own Listener to check the values inside Edittext on key press event - How to implement your own Listener
Instead of extending BaseAdapter you extend ArrayAdapter. It implements the Filterable interface for you. In TextWatcher call getFilter().filter(text); method.
public void afterTextChanged(Editable s) {
listview.getAdapter().getFilter().filter(s);
}