Filtering SimpleCursorAdapter - android

This code is working properly by showing all the data in database but i have a problem in filtering. I try many code but nothing works , can someone help me out ? thanks
package com.example.dictionary;
import java.util.List;
import com.example.dictionary.R;
import android.os.Bundle;
import android.app.Activity;
import android.database.Cursor;
import android.support.v4.widget.SimpleCursorAdapter;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity{
Cursor cursor;
ListView listView;
SimpleCursorAdapter adapter;
Button back, clear;
List<String> items;
String get;
EditText et;
int textlength = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
Opening my database and getting all data
Historydb db = new Historydb(this);
db.open();
cursor = db.getword();
startManagingCursor(cursor);
cursor.moveToFirst();
adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1, cursor,
new String[] { "word" }, new int[] { android.R.id.text1 });
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
I set addtextchangelistener in my edittext.
et.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
// Abstract Method of TextWatcher Interface.
}
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
// Abstract Method of TextWatcher Interface.
}
public void onTextChanged(CharSequence s, int start, int before,int count) {
adapter.getFilter().filter(s);
}});
}
}

it is not working because adapter.getfilter().filter(cs); does not work directly for SimpleCursorAdapter.
you have to use adapter.setFilterQueryProvider first for SimpleCursorAdapter.
here is the complete description: ListView, SimpleCursorAdapter, an an EditText filter -- why won't it do anything?
and this: Using an EditText to filter a SimpleCursorAdapter-backed ListView

Try this....
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
((SimpleAdapter) YourActivity.this.adapter).getFilter().filter(cs);
}

Related

Android:Disable Button on app launch enable only when Edit text is filled

I want to Android:Disable Button on app launch enable only when Edit text is filled. help needed. thanks in advance. I am Android Beginner.
Tried using TextWatcher. app is running fine when i don't add this feature.
please suggest how i can implement the TextWatcher part. rest of the app is working fine.
here is the code:
package com.example.intentopennextscreen;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public TextView editText1;
public Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//editText1.addTextChangedListener(ebert);
}
/*TextWatcher ebert = 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) {
String message = editText1.getText().toString().trim();
submit.setEnabled(!message.isEmpty());
}
#Override
public void afterTextChanged(Editable s) {
}
}; */
/* Called when the user taps the Send button */
public void sendMessage(View view) {
/* Creating instance of Intent object */
Intent intent = new Intent(this, DisplayMessageActivity.class);
/* finding the user-input provided in the editText as an object */
EditText editText1 = (EditText) findViewById(R.id.editText1);
/*Finding Button Element*/
Button submit = (Button) findViewById(R.id.button);
/* converting the user-input of editText as String */
String message = editText1.getText().toString().trim();
/* sending the message to other activity as Key-Value Pair */
intent.putExtra("Value", message);
/* starting the intent */
startActivity(intent);
}
}
You can move the button manipulation inside afterTextChanged
#Override
public void afterTextChanged(Editable s) {
submit.setEnabled(!s.isEmpty());
}
Try this below code,
Add this in your onCreate() method
submit.setEnabled(false);
editText1.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 (editText1.getText().length() > 0) {
submit.setEnabled(true);
} else {
submit.setEnabled(false);
}
}
});

Hide an android ListView until search string is entered

I've followed this tutorial http://www.androidpeople.com/android-listview-searchbox-sort-items and I have the search working on the list. The only change I'd like to make is to have the list view hidden initially and the results only appearing when the user starts typing. Is there a way to do this?
EDIT: Added code.
package com.example.testapp;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String lv_arr[]= {"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.activity_main);
lv1=(ListView)findViewById(R.id.ListView);
ed=(EditText)findViewById(R.id.EditText01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
ed.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if(lv1.getVisibility() != View.VISIBLE)
lv1.setVisibility(View.VISIBLE);
}
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<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}
}
}
lv1.setAdapter(new ArrayAdapter<String> (MainActivity.this,android.R.layout.simple_list_item_1 , arr_sort));
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I would do it like this:
EditText etSearch = (EditText) getView().findViewById(R.id.etSearch);
etSearch.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable s) {
if(view.getVisibility() != View.Visible)
view.setVisiblity(View.Visible);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after){}
public void onTextChanged(CharSequence s, int start, int before, int count){}
});

How to use the seletedItem from the AutoCompleteTextView dropdown list?

Friends, I am using AutoCompleteTextView. The Suggestion :
String[] recipes={ "Fish", "Chicken", "Mutton"};
How do I do this:
When I select one of the item from the dropdown list, it will go to another event?
For example, I type Fi, it will come out Fish from the dropdown list and then I select Fish, it will go to another Activity.
package net.learn2develop.Activities;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AdapterView;
import android.view.View;
import android.content.Intent;
public class AutoCompleteTextActivity extends Activity {
String[] recipes ={
"Nasi Lemak With Ikan Bilis",
"Steamed Cod Fish"
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, recipes);
AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.txtRecipes);
textView.setThreshold(3);
textView.setAdapter(adapter);
textView.setOnItemSelectedListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> av, View view, int index, long id){
Intent i=new Intent(this,Activity2.class);
i.putExtra("item",recipes[index]);
StartActivity(i);
}
});
}
}
You can use a class that implements TextWatcher and override following methods:
#Override
public void afterTextChanged(final Editable editable) {
// check if entered text is "fish" and if yes then start the new activity.
}
#Override
public void beforeTextChanged(final CharSequence string,
final int start, final int count, final int after) {
}
#Override
public void onTextChanged(final CharSequence string, final int start,
final int before, final int count) {
}
}
receipesBelow Snippet will help you.
autoCompleteTextView.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> av, View view,
int index, long id)
{
//index will give you item which you selected
Now start another activity here
Intent i=new Intent(context,SecondActivity.class);
i.putExtra("item",recipes[index]);
StartActivity(i);
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
// TODO Auto-generated method stub
}
})
SecondActivity.java
You can retrieve that value is onCreate like below
String selectedItem=getIntent().getStringExtra("item");
You should have used setOnItemClickListener instead of setOnItemSelectedListener.

addTextChangedListener with listview with subtext

I want to search through the list and display the result in the list again
so I used addtextchangelistener, but can't find a way to make it work with listview with subtext
Here's my code:
package com.android;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import android.app.ListActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class MyListDemoActivity extends ListActivity {
/** Called when the activity is first created. */
TextView tv;
//** List<String> content;
EditText actv;
List<String> arr_sort;
//** ArrayAdapter<String> adapter;
SimpleAdapter simpleadapter;
ListView lv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String line = " ";
LineNumberReader linenoreader = null;
StringTokenizer stringtokanixer = null;
//** content = new ArrayList<String>();
List<Map<String,String>> data= new ArrayList<Map<String,String>>();
lv = (ListView) findViewById(android.R.id.list);
try {
InputStream istream = getResources().openRawResource(R.raw.grelist);
InputStreamReader streamreader = new InputStreamReader(istream);
linenoreader = new LineNumberReader(streamreader);
linenoreader.mark(15);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}// try catch ends here
Log.v("getting", "working");
for(int i=0;i<8;i++)
{
Map<String,String> datum= new HashMap<String,String>(2);
try {
line = linenoreader.readLine();
Log.v("item",line);
} catch (IOException e) {
e.printStackTrace();
}
Log.v("getting", line);
stringtokanixer = new StringTokenizer(line);
String st = stringtokanixer.nextToken();
String meaning="";
while (stringtokanixer.hasMoreTokens()) {
meaning +=" " +stringtokanixer.nextToken();
}// for ends
// map is used to add word and meaning
datum.put("word",st);
datum.put("meaning",meaning);
data.add(datum);
//List<String> is usedto add
//** content.add(st);
}
simpleadapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});
// setListAdapter(adapter);
lv.setAdapter(simpleadapter);
tv = (TextView) findViewById(R.id.textView1);
actv = (EditText) findViewById(R.id.editText1);
/*
actv.addTextChangedListener(new TextWatcher() {
int len = 0;
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
arr_sort = new ArrayList<String>();
len = actv.getText().length();
for (int i = 0; i < content.size(); i++) {
if (len <= content.get(i).length()) {
if (actv.getText()
.toString()
.trim()
.equalsIgnoreCase(
(String) content.get(i).subSequence(0,
len))) {
arr_sort.add(content.get(i));
Log.v("infor loop afterTextChanged", s.toString());
}
}
}
// adapter.notifyDataSetChanged();
adapter = new ArrayAdapter<String>(MyListDemoActivity.this,
android.R.layout.simple_list_item_1, arr_sort);
setListAdapter(adapter);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.v("beforetextchange","hello here");
}
#Override
public void afterTextChanged(Editable s) {
Log.v("aftertextchange","hello here");
}
}); // text watcher class ends here
*/
}// on create ends here
public void onListItemClick(ListView ls, View v, int position, long id) {
//tv.setText(content.get(position));
// tv.setText(content[position]) // in case of string
}// endsd here onListItemClick(
}
I have answered already in two of the StackOverflow questions itself you can them,
First is using getFilter() that android provides for Filtering using Filterable interface to the Adapter class. You can check it from here.
Second is using an external jar Lambdaj which is the best and efficient way of filtering a huge data from a List. You can check that also from here.
What I understood is:- Simply you want to filter the ListView. Right?
Let me know If I've misunderstood the question!!!
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<EditText android:id="#+id/search" android:layout_width="fill_parent" android:layout_height="wrap_content"
android:inputType="text" />
<ListView android:id="#+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent" />
</LinearLayout>
ListViewSearchActivity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListViewSearchActivity extends Activity implements TextWatcher {
private SimpleAdapter simpleAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText search = (EditText) findViewById(R.id.search);
search.addTextChangedListener(this);
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
for(int i=0;i<8;i++) {
Map<String,String> map = new HashMap<String, String>(2);
map.put("word", "word " + i);
map.put("meaning", "meaning " + (i + 10));
data.add(map);
}
ListView listView = (ListView) findViewById(R.id.list);
this.simpleAdapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[]{"word","meaning"}, new int[]{android.R.id.text1,android.R.id.text2});
listView.setAdapter(this.simpleAdapter);
}
#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) {
this.simpleAdapter.getFilter().filter(s.toString());
}
}
Here is how I'd change your code to make it work:
1. I would remove the arr_sort variable, and add an other ArrayList of Maps for holding the filtered values:
// List<String> arr_sort;
final ArrayList<Map<String, String>> data =
new ArrayList<Map<String, String>>();
final ArrayList<Map<String, String>> filteredData =
new ArrayList<Map<String, String>>();
I'd also make them final, since there is no point to assign completely new values to them while we can modify their content.
2. The simpleadapter should always display the filtered data, so it has to be modified:
filteredData.addAll(data); // fill up filteredData initially with the whole list
simpleadapter = new SimpleAdapter(this, filteredData,
android.R.layout.simple_list_item_2,
new String[] { "word", "meaning" },
new int[] {android.R.id.text1, android.R.id.text2 });
3. Next I'd move the filtering code from the onTextChanged method to the afterTextChanged method, to perform the filtering based on the whole text entered. Using Regexp is also less resource consuming than all the String manipulations (+ , substring...)
This way your TextWatcher implementation would look like:
actv.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{}
#Override
public void beforeTextChanged(CharSequence s,int start,int count,int after)
{}
#Override
public void afterTextChanged(Editable s)
{
Log.v("MLDA", "afterTextChanged");
// a temporary source list for better performance:
// if it's possible, use the smaller filtered list
final ArrayList<Map<String, String>> tmpSource =
new ArrayList<Map<String,String>>();
tmpSource.addAll(
(filterText.length() > 0 && s.toString().contains(filterText))
? filteredData : data);
filterText = s.toString();
// a temporary result list to fill with the filtered data
final ArrayList<Map<String, String>> tmpResult =
new ArrayList<Map<String,String>>();
if (filterText.length() == 0)
tmpResult.addAll(data); //if no filter, return the base data
else
{
final Pattern pattern =
Pattern.compile("(?i)" + Pattern.quote(s.toString()));
Matcher matcher;
for (final Map<String, String> map : tmpSource)
{
//first match against the "word":
matcher = pattern.matcher(map.get("word"));
if (!matcher.find())
{
//if no matches were found, try to match the "meaning"
matcher = pattern.matcher(map.get("meaning"));
if (!matcher.find())
continue; //if no match, move to the next map
}
tmpResult.add(map); //match found: add to new list
}
}
filteredData.clear();
filteredData.addAll(tmpResult);
simpleadapter.notifyDataSetChanged(); // update display
}
});
Working with temporary lists lets you build up the whole filtered data without gui updates (if removing / adding items to the filteredData list directly, the adapter would trigger update methods).
Also notice, that by examining whether the new filter text contains the old one, we can use the current filteredData list as source.
Similarly, if the filterText is an empty string, there's no point to perform any matches, we can simply return the base list.
ArrayList<String> tempList ;
edtText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
if (!edtText.getText().toString().equalsIgnoreCase("")){
tempList = new ArrayList<String>();
tempList.clear();
String text = filterText.getText().toString();
for(int i=0 ;i< listname.size();i++){
//if(globalconstant.mosq_list.get(globalconstant.hashformosq.get(globalconstant.tempList.get(i))).name.toUpperCase().toString().contains(text.toUpperCase())){
if(listname.get(i).toUpperCase().toString().contains(text.toUpperCase())){
tempList.add(listname.get(i));
}
}
used changed tempList
}else{
unchaged tempList
}
}
});
}

How to implement action listener in ListView?

Basically, I want to create a ListView with a bunch of items on it, and whenever the user click any item, it will open a new Activity according to which item he clicks. PLease, help me I would really appreciate it a lot.
Here is my my code:
package com.hipeople;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class char1 extends Activity {
/** Called when the activity is first created. */
private ListView lv1;
private EditText ed;
private String lv_arr[]={"Android","Cupcake","Donut","Eclairs","AndroidPeople","Froyo",};
private ArrayList<String> arr_sort= new ArrayList<String>();
int textlength=0;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
ed=(EditText)findViewById(R.id.EditText01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
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<lv_arr.length;i++)
{
if(textlength<=lv_arr[i].length())
{
if(ed.getText().toString().equalsIgnoreCase((String) lv_arr[i].subSequence(0, textlength)))
{
arr_sort.add(lv_arr[i]);
}
}
}
}
});
}
}
Try this,
lv1.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> arg0, View arg1,int arg2, long arg3)
{
String str = ((TextView) arg1).getText().toString();
Toast.makeText(getBaseContext(),str, Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(),your_new_Intent.class);
intent.putExtra("list_view_value", str);
startActivity(intent);
}
});

Categories

Resources