addTextChangedListener with listview with subtext - android

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
}
}
});
}

Related

Filtering SimpleCursorAdapter

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);
}

What is the correct way implement switch case statement in Android?

It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = 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) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}

Filtering List View getting Null onTextChanged

I have an XML parser populating a list. That is working just fine. I am trying to add a filter via EditText to my app, but I get a NullPointerException in the onTextChange.
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
adapter.getFilter().filter(s);
}
My entire class looks like so:
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import com.androidquery.AQuery;
import com.androidquery.callback.AjaxStatus;
import com.androidquery.util.AQUtility;
import com.androidquery.util.XmlDom;
public class MainActivity extends ListActivity implements TextWatcher {
private AQuery aq;
ProgressDialog dialog;
String etValue;
EditText searchText;
TextView result;
String url = "http://domain.com/it.xml";
ListView lv;
String Name;
String barcode;
String productName;
String qtySold;
String inventory;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressDialog dialog = new ProgressDialog(this);
dialog.setIndeterminate(false);
dialog.setInverseBackgroundForced(false);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setTitle("Help on the Way...");
dialog.setMessage("Gathering Latest Inventory Info");
aq = new AQuery(this);
AQUtility.setDebug(true);
// load the file from the server
load_xml();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void load_xml() {
aq.progress(dialog).ajax(url, XmlDom.class, -1, this, "inventoryCb");
}
#SuppressWarnings({ "unchecked", "rawtypes" })
public void inventoryCb(String url, XmlDom xml, AjaxStatus status) {
// Log.i("CB", xml.toString());
List<XmlDom> sec = xml.tags("GroupFooter");
List<String> fv = new ArrayList<String>();
for (XmlDom entry : sec) {
List<XmlDom> ent = entry.tags("Field");
for (XmlDom field : ent) {
Name = field.attr("Name");
// Log.v("Field Name: ", Name);
if (Name.equals("Field19")) {
barcode = field.child("FormattedValue").text();
// Log.i("Barcode: ", barcode);
}
if (Name.equals("Field20")) {
productName = field.child("FormattedValue").text();
// Log.d("Product Name: ", productName);
}
if (Name.equals("Field21")) {
qtySold = field.child("FormattedValue").text();
// Log.e("Qty Sold: ", qtySold);
}
}
inventory = barcode + " | " + productName + " | " + qtySold;
fv.add(inventory);
Log.i("INVENTORY: ", inventory);
}
searchText = (EditText) findViewById(R.id.inputSearch);
searchText.addTextChangedListener(this);
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, fv));
}
#Override
public void afterTextChanged(Editable s) {
// 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 onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
adapter.getFilter().filter(s);
}
}
Why am I getting an NPE on my onTextChanged? Any thoughts or ideas? Am I doing this completely wrong?
Edit:
This ended up working: Create a method that returns array info and then call it in the adapter in the onCreate:
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, xmlr());
setListAdapter(adapter);
EditText filterEditText = (EditText) findViewById(R.id.filterText);
filterEditText.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
// LOAD XML from Local Resources Folder
public List<String> xmlr() {
InputStream is = getResources().openRawResource(R.raw.it);
XmlDom xml = null;
try {
xml = new XmlDom(is);
} catch (SAXException e) {
// TODO Auto-generated catch block
Log.e("SAXe: ", e.getMessage());
}
List<XmlDom> sec = xml.tags("GroupFooter");
fv = new ArrayList<String>();
for (XmlDom entry : sec) {
List<XmlDom> ent = entry.tags("Field");
for (XmlDom field : ent) {
Name = field.attr("Name");
// Log.v("Field Name: ", Name);
if (Name.equals("Field19")) {
barcode = field.child("FormattedValue").text();
// Log.i("Barcode: ", barcode);
}
if (Name.equals("Field20")) {
productName = field.child("FormattedValue").text();
// Log.d("Product Name: ", productName);
}
if (Name.equals("Field21")) {
qtySold = field.child("FormattedValue").text();
// Log.e("Qty Sold: ", qtySold);
}
}
inventory = barcode + " | " + productName + " | " + qtySold;
fv.add(inventory);
Log.i("INVENTORY: ", inventory);
}
return fv;
}
setListAdapter(new ArrayAdapter(this,
android.R.layout.simple_list_item_1, fv));
set it into OnCreate Method..

Android: help Text Watcher , List compare .logical error with afterTextChanged

facing problem in searching and displaying the list using text watcher.
it is a simple search operation in the List.
firstly the data is retrieved from the .txt line by line.
first word of string is stored in the list content and now i want to perform search operation on this content list and display the result in listview
here is the code
enter code here
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.List;
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.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.TextView;
public class MyListDemoActivity extends ListActivity {
/** Called when the activity is first created. */
TextView tv;
// final String[] values=new String[]{"android","Windows",
// "ios","BlackBerry","Java",".Net","WebOS", "Ubuntu", "Windows7"};
//String[] content;
List<String> content ;
AutoCompleteTextView actv;
List<String> arr_sort;
ArrayAdapter<String> adapter;
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>();
lv=(ListView)findViewById(android.R.id.list);
try {
InputStream istream = getResources().openRawResource(R.raw.hihihi);
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 < 6; i++) {
try {
line = linenoreader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("getting", line);
stringtokanixer = new StringTokenizer(line);
String st=stringtokanixer.nextToken();
content.add(st);
}// for ends here
adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,content);
// setListAdapter(adapter);
lv.setAdapter(adapter);
tv= (TextView)findViewById(R.id.textView1);
actv=(AutoCompleteTextView)findViewById(R.id.autoCompleteTextView1);
actv.addTextChangedListener(new TextWatcher() {
int len=0;
#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
len=actv.getText().length();
for(int i=0;i<content.size();i++)
{
if(len<=content.get(i).length())
{
if(actv.getText().toString().equalsIgnoreCase((String) content.get(i).subSequence(0, len)))
{
arr_sort.add(content.get(i));
}
}
}
adapter=new ArrayAdapter<String>(MyListDemoActivity.this,android.R.layout.simple_list_item_1,arr_sort);
setListAdapter(adapter);
}
}); // 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(
}
here is the main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=" " >
</AutoCompleteTextView>
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:drawSelectorOnTop="false"
>
</ListView>
</LinearLayout>
here is txt file
joke happy
hota happy okgame
ok happy okgame
asitis happy
okgame happy
oktested happy happy
i guess there is logical error in afterTextChanged but cant figure it out.
You don't need to recreate adapter. And you should trim strings whan compare tham. Small fixes (it works :)):
public class MyListDemoActivity extends ListActivity {
/**
* Called when the activity is first created.
*/
TextView tv;
// final String[] values=new String[]{"android","Windows",
// "ios","BlackBerry","Java",".Net","WebOS", "Ubuntu", "Windows7"};
//String[] content;
List<String> content;
AutoCompleteTextView actv;
List<String> arr_sort = new ArrayList<String>();
ArrayAdapter<String> adapter;
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>();
lv = (ListView) findViewById(android.R.id.list);
try {
InputStream istream = getResources().openRawResource(R.raw.hihihi);
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 < 6; i++) {
try {
line = linenoreader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Log.v("getting", line);
stringtokanixer = new StringTokenizer(line);
String st = stringtokanixer.nextToken();
content.add(st);
}// for ends here
arr_sort.addAll(content);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arr_sort);
// setListAdapter(adapter);
lv.setAdapter(adapter);
tv = (TextView) findViewById(R.id.textView1);
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
actv.addTextChangedListener(new TextWatcher() {
int len = 0;
#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
arr_sort.clear();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
len = actv.getText().toString().trim().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));
}
}
}
adapter.notifyDataSetChanged();
}
}); // 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(
}
solved
im working on icecream sandwitch...
it worked with this code...
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);
}

Android dynamic auto-complete - minor fix - code attached

I am trying to implement a dynamic autocomplete widget in android. I am done with the major functionalities and the autocompletion implemented is for youtube video search.
When I start typing a letter or two, the auto-completion is not working. But when I type three letters or more it works prfect. It also works when I type two letters and hit a backspace. I do not know what is wrong with the code.
I have uploaded the code here
Experts, kindly guide me. I would be obliged if you can point out where I have gone wrong with the code.
Any help in this regard is well appreciated.
Looking forward,
Regards,
Rony
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
public class YoutubeAutoComplete extends Activity {
Youtube yt = new Youtube();
CustomAutoComplete myAutoComplete;
ArrayAdapter<String> adapter;
private JSONArray js;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myAutoComplete = (CustomAutoComplete) findViewById(R.id.autocomplete);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
myAutoComplete.addTextChangedListener(textWatcher);
myAutoComplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
TextWatcher textWatcher = new TextWatcher() {
public void onTextChanged(final CharSequence s, int start, int before,
int count) {
Thread t = new Thread() {
public void run() {
try {
js = yt.GetSuggestions(s.toString()).getJSONArray(1);
messageHandler.sendEmptyMessage(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
};
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
adapter.clear();
for (int i = 0; i < js.length(); i++) {
try {
adapter.add(js.getJSONArray(i).getString(0));
System.out.println(js.getJSONArray(i).getString(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
}
Take a look at completionThreshold AKA the number of characters the user must type before getting completion suggestions.
http://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:completionThreshold

Categories

Resources