Android AutocompleteTextView suggestion to be indexed to listview - android

I'm creating an activity wherein there are textview/autocompletetextview, listview and a button. My autocompletetextview works well, but I want to index what I input in the textview to the listview and when the it is highlighted, I'd click the button and go to the corresponding activity.
Here's so far what I've done:
String[] classes = {
"Acornsquash",
"Almonds",
"Apples", }
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature( Window.FEATURE_LEFT_ICON );
setContentView(R.layout.nutritional_list);
setFeatureDrawableResource( Window.FEATURE_LEFT_ICON, R.drawable.nutrition32 );
//ArrayAdapter<String> adapter = new ArrayAdapter<String>( this,
// android.R.layout.simple_dropdown_item_1line, classes );
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classes );
AutoCompleteTextView tv = ( AutoCompleteTextView ) findViewById ( R.id.txtSearcEngine );
tv.setThreshold( 3 );
tv.setAdapter( adapter );
tv.setTextColor( Color.BLACK );
lv = ( ListView ) findViewById(R.id.lvListSearch);
lv.setAdapter(new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes ) );
lv.setOnItemClickListener( this );
public void onItemClick( AdapterView<?> parent, View v, int position, long id ) {
lv.setSelection(position);
switch( position )
{
case 0:
Intent acorn = new Intent( Nutritional_List.this, AcornSquash.class );
startActivity( acorn );
break;
case 1:
Intent almonds = new Intent( Nutritional_List.this, Almonds.class );
startActivity( almonds );
break;
My problem is, I don't have a clue on how to index suggestion from autocompletetextview to listview. Any help? thanks.

Rewrite
I am posting two ways to accomplish what you want. I believe that first method is simpler to code and less confusing to use. The second method is the direct answer to your question.
Method 1
I find it curious that you are using an AutoCompleteTextView and a ListView when they both provide the same information. The AutoCompleteTextView has the advantage of filtering the selection based on the user's text, but you can remove the AutoCompleteTextView and Button by using adding simple EditText that filters the ListView itself.
EditText edit = (EditText) findViewById(R.id.edit);
edit.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
adapter.getFilter().filter(s);
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void afterTextChanged(Editable s) {}
});
Where adapter is a class variable like lv, tv, etc. and is the adapter passed to lv:
adapter = new ArrayAdapter<String>( this, android.R.layout.simple_list_item_1, classes );
lv.setAdapter(adapter);
Method 2
To do what you asked about initially, first let's change classes to a more powerful ArrayList<String>:
ArrayList<String> classesList = new ArrayList<String>(Arrays.asList(classes));
...
public void onCreate() {
...
// Update both of your adapters!
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.my_list_item, classesList );
create a new class variable as int tvIndex = -1. We'll use it when we click an item from the AutoCompleteTextView:
tv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = ((TextView) v).getText().toString();
tvIndex = classesList.indexOf(text);
lv.setSelection(tvIndex);
}
});
If the user pushes the Button to proceed:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(tvIndex > -1)
lv.performItemClick(lv.getChildAt(tvIndex), tvIndex, tvIndex);
}
});
Hope that helps!

Related

how to replace text in listview

I need to replace "gold" in Listview
AndroidListView1= "gold" > "goldennnnnnn" AndroidListView2= "gold" > "golderrrrrrrrr"
when i set it in edittext then its work!! but when i set it in List view then print only 1 item("goldennnnnnn")##
this.et3.setText(AndroidListView); (edittext work) but this.Listview.setText(AndroidListView1);not work
this is my code thanks in advance
ListView listView ;
EditText myTextBox,myOuttext,et3;
Button btn;
ClipboardManager myClipboard;
private Object adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myTextBox = (EditText) findViewById(R.id.editText1);
myOuttext = (EditText) findViewById(R.id.editText2);
et3=(EditText)findViewById(R.id.editText3);
btn=(Button)findViewById(R.id.button1);
myClipboard = (ClipboardManager)getSystemService(CLIPBOARD_SERVICE);
// Get ListView object from xml
listView = (ListView) findViewById(R.id.listView1);
// Defined Array values to show in ListView
String[] values = new String[]
{ "AndroidListView1",
"AndroidListView2",
"AndroidListView3",
"AndroidListView4",
"AndroidListView5",
"AndroidListView6",
"AndroidListView7",
"AndroidListView8",
"AndroidListView9",
"AndroidListView10",
"AndroidListView11",
"AndroidListView12",
"AndroidListView13",
"AndroidListView14",
"AndroidListView15",
"AndroidListView16",
"AndroidListView17",
};
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayList<?> yourlist = new ArrayList<Object>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
// Assign adapter to ListView
listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_list_item_1, values));
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
myTextBox.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
#SuppressLint("NewApi")
public void onTextChanged(CharSequence s, int start,
int before, int count) {
MainActivity.this.my1(s);
MainActivity.this.AndroidListView(s);
}
});
}
private String my1(CharSequence arg) {
String str = "";
str = arg.toString().replace(" ", " " ).replace("gold", "goldennnnnnn");
this.myOuttext.setText(str);
System.out.println(str);
return str;
}
private String AndroidListView(CharSequence arg) {
String AndroidListView = "";
AndroidListView= arg.toString().replace(" ", "").replace("gold", "golderrrrrrrrr");
this.et3.setText(AndroidListView);
System.out.println(AndroidListView);
return AndroidListView;
}
}
Try this code to change listView item at particular position:
ArrayList<?> yourlist = new ArrayList<Object>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
//listView.setAdapter(new ArrayAdapter<String>(MainActivity.this,
// android.R.layout.simple_list_item_1, values));
values[3] = "myNewItem";
adapter.notifyDataSetChanged();
Response of above code is:
EDIT: To search a particular item and to change that:
for(int i =0; i<values.length; i++){
if(values[i].equals("myNewItem")){
values[i] = "A_Newer_One";
}
}
adapter.notifyDataSetChanged();

getSelectedItemPosition() of ListView returns -1

With this code, when System.out.println is executed after setSelection instruction, returns -1 and I don't know why.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.composition);
lv = (ListView) findViewById(android.R.id.list);
cabecera = (TextView) findViewById(R.id.cabecera);
information = (TextView) findViewById(R.id.paciente);
proceso = new ArrayList<>();
proceso.add("- Item1");
proceso.add("- Item2");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,proceso);
lv.setAdapter(adapter);
lv.post(new Runnable() {
#Override
public void run() {
lv.setSelected(true);
lv.setSelection(0);
adapter.notifyDataSetChanged();
System.out.println("Selected Item onCreate: "+lv.getSelectedItemPosition());
System.out.println("Get Count en onCreate: "+lv.getCount());
}
});
nextBundle = new Bundle();
nextBundle.putString("name",proceso.get(position));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
in = new Intent(getApplicationContext(),Check.class);
in.putExtras(nextBundle);
startActivity(in);
}
});
}
getCount() function applied to the ListView returns a correct value: 2
I have searched to find a solution but all that I have read and tested don't solve the problem.
UPDATE:
This code:
listPacientes = new ArrayList<>();
listPacientes.add("Elemento 1");
listPacientes.add("Elemento 2");
listPacientes.add("Elemento 3");
adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.customizedlistitem,list);
lv.setAdapter(adapter);
lv.setSelection(1);
System.out.println(lv.getSelectedItemPosition());
works on Main Activity. That "System.out" returns 1, but the same code in next Activities, returns -1, why? I can't understand it.
you are first selecting the cell and afterwards refreshing the ListView by calling adapter.notifyDataSetChanged(); - this way your selection is removed.
Use lv.getSelectedItemPosition() method inside onItemClick() method. you will get the proper value here

How to insert a filter in my EditText in a ListView to filter my Database

I have a ListView with an EditText to prompt a simple query making a select in my database, and i need to implements this query in my TextWatcher {... but I don't know how to do that any ideas ??
And I need to query two columns in one table...
public class ListaMateriais extends Activity {
private ListView listamateriais;
ArrayAdapter<String> adapMatchMaterial;
EditText inputSearch;
public EditText ETclient;
ArrayList<HashMap<String, String>> productList;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_material_match);
String products[] = { "Parafuso 3x4 092387",
"Cabeçote redpo 09873",
"alavanca de ignição 027625",
"Pistão de arranque 093298092",
"Eixo dianteiro 0343232",
"Cabeçote parafuseta 093232" };
listamateriais = (ListView) findViewById(R.id.list_match_material);
adapMatchMaterial = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
listamateriais.setAdapter(adapMatchMaterial);
listamateriais.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
String text= (String) arg0.getItemAtPosition(position);
Bundle bundle = new Bundle();
bundle.putString("TextMateriais", text);
Intent int_material = new Intent(ListaMateriais.this,Formulario_ItemNota.class);
int_material.putExtras(bundle);
startActivity(int_material);
finish();
}
});
inputSearch = (EditText) findViewById(R.id.materialSearch);
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
ListaMateriais.this.adapMatchMaterial.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
public void afterTextChanged(Editable arg0) {
}
});
}
Any helps will be truly appreciated... Thanks
you need to create a custom adpater that will extends Filter,
try this tutorial:
http://www.survivingwithandroid.com/2012/10/android-listview-custom-filter-and.html
Then in performFiltering, you can query the database to get the data and refresh you list.
ArrayList<String> mArrayList = new ArrayList<String>();
for(mCursor.moveToFirst(); !mCursor.isAfterLast(); mCursor.moveToNext()) {
// The Cursor is now set to the right position
mArrayList.add(mCursor.getString(COLUMN_INDEX_YOU_WANT));
}
Use AutoCompleteTextView
AutoCompleteTextView atxtSearch = (AutoCompleteTextView) findViewById(R.id.atxtSearchUser);
atxtSearch.setThreshold(3);
ArrayAdapter<String> adapMatchMaterial = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line,products); //products should be an array
atxtSearch.setAdapter(adapMatchMaterial );
Then When you type on this edit text, after typing 3 letters, it will automatically list the items

Using Spinner And List Views with setOnItemSelectedListener

I'm supposed to make a task , I have a spinner connected with a String array x , this array contains three values , so I want when clicking any choice of the spinner a specific list view will will give a specific three values and , this is my code :
public class Four extends ActionBarActivity {
String x [] = {"Jordan","Saudi Arabia", "Syria"};
String Jordan[] = {"Amman","Aqaba","Sarqa"};
String Saudi[] = {"Riyadh","Jeddah","Khobar"};
String Syria[] = {"Hems","Halab","Demashk"};
Spinner sp1 ;
ListView lv1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.four);
lv1 = (ListView)findViewById(R.id.listView1);
// Jordan List View
ArrayAdapter<String> jor = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Jordan);
lv1.setAdapter(jor);
// Saudi Arabia List View
ArrayAdapter<String> saud = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Saudi);
lv1.setAdapter(saud);
// Syria List View
ArrayAdapter<String> syr = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,Syria);
lv1.setAdapter(syr);
sp1 = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> a = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item , x);
sp1.setAdapter(a);
sp1.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
The thir parameter of onItemSelected() (int arg2 in your example, but I would suggest you rename them) is the position you selected in the Spinner. So you could implement that method like this:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
if (position == 0)
lv1.setAdapter(jor);
else if (position == 1)
lv1.setAdapter(saud);
else if (position == 1);
lv1.setAdapter(syr);
}
Remember that all the variables involved (lv1, jor, saud, syr) must be defined as final to be used inside the anonymous class, e.g.
final ArrayAdapter<String> jor = ...
final ArrayAdapter<String> saud = ...

How can I use OnListItemClickListener using this Search Filtering ListView

I'm having trouble using setOnItemClickListener in my listview. Everytime I try, it causes too many errors with fixes that makes the code worse than what I'm intending to do.
This is my code:
public class Search extends Activity{
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
// Listview Data
final String products[] = {"Fill in the Blocks", "The Music Bee", "Little Paragon",
"Subway Surfers", "Cytus", "Temple Run", "Clumsy Ninja", "Smash Hit"};
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
Search.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
}
}
I want to make the strings in the listview data clickable for my other activities but it won't work. I tried this code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String openClass = adapter.getItem[position];
if (openClass.equals("Fill in the Blocks")) {
Intent myIntent = new Intent(view.getContext(), Fill_in_the_Blocks.class);
startActivityForResult(myIntent, 0);
}
else if (openClass.equals("The Music Bee")) {
Intent myIntent1 = new Intent(view.getContext(), The_Music_Bee.class);
startActivityForResult(myIntent1, 0);
}
else if (openClass.equals("Little Paragon")) {
Intent myIntent2 = new Intent(view.getContext(), Little_Paragon.class);
startActivityForResult(myIntent2, 0);
}
}
The errors were as follows:
-In the lv.setOnItemClickListener, "The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})"
-In the (new OnItemClickListener(), "OnItemClickListener cannot be resolved to a type"
-In the public void onItemClick(AdapterView, "AdapterView cannot be resolved to a type"
-In the String openClass = adapter.getItem[position];, "getItem cannot be resolved or is not a field"
In the lv.setOnItemClickListener, "The method setOnItemClickListener(AdapterView.OnItemClickListener) in the type AdapterView is not applicable for the arguments (new OnItemClickListener(){})"
In the (new OnItemClickListener(), "OnItemClickListener cannot be resolved to a type"
In the public void onItemClick(AdapterView, "AdapterView cannot be resolved to a type"
The first 3 errors should disappear by replacing new OnItemClickListener() with
new AdapterView.OnItemClickListener()
and make sure you import:
import android.widget.AdapterView;
The final error:
In the String openClass = adapter.getItem[position];, "getItem cannot be resolved or is not a field"
You are meant to be calling the getItem method, rather than using array indexing.
replace the line:
String openClass = adapter.getItem[position];
with
String openClass = adapter.getItem(position);

Categories

Resources