I'm having difficulties to making the SearchView of my Action Bar works in this code. Really do not know much what to do because I am new to developing for Android, java and everything else. So ... would like to help someone to be able to do at least one search engine of Android search the words of my ListView in a database of my app.
Thanks!
package br.com.jandeilson.myproject;
import br.com.jandeilson.myproject.R;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteCursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
public class ListarActivity extends Activity {
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listar_activity_actions, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_new:
startActivity(new Intent(this, Inserir.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listar);
}
public void onResume(){
super.onResume();
SQLiteDatabase db = openOrCreateDatabase("objetos.db", Context.MODE_PRIVATE, null);
// Tabela de objetos
StringBuilder sqlClientes = new StringBuilder();
sqlClientes.append("CREATE TABLE IF NOT EXISTS objetos (");
sqlClientes.append("_id INTEGER PRIMARY KEY, ");
sqlClientes.append("nomeobj VARCHAR(30)); ");
db.execSQL(sqlClientes.toString());
Cursor cursor = db.rawQuery("SELECT * FROM objetos", null);
String[] from = {"nomeobj"};
int[] to = {R.id.NomeObj};
android.widget.SimpleCursorAdapter ad = new android.widget.SimpleCursorAdapter(getBaseContext(),
R.layout.listar_model, cursor, from, to);
ListView ltwDados = (ListView)findViewById(R.id.ltwDados);
ltwDados.setAdapter(ad);
ltwDados.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView adapter, View view,
int position, long id) {
SQLiteCursor c = (SQLiteCursor) adapter.getAdapter().getItem(position);
Intent it = new Intent(getBaseContext(), Editar.class);
it.putExtra("id", c.getInt(0));
startActivity(it);
}
});
db.close();
}
}
Check this link - Search Overview
Sample in your sdk folder: sdk/samples/android-15/SearchableDictionary/
upd: something like this:
private void loadWords() throws IOException {
Log.d(TAG, "Loading words...");
ArrayList<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
for ( String str: list){
addWord( str, ""); // word, def.
}
Log.d(TAG, "DONE loading words.");
}
upd:
public class CustomAutoCompleteTextView extends AutoCompleteTextView {
//was the text just cleared?
boolean justCleared = false;
public Drawable imgClearIcon = getResources().getDrawable(android.R.drawable.ic_menu_close_clear_cancel);
public CustomAutoCompleteTextView(Context context) {
super(context);
init();
}
/* Required methods, not used in this implementation */
public CustomAutoCompleteTextView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
init();
}
/* Required methods, not used in this implementation */
public CustomAutoCompleteTextView(Context context, AttributeSet attrs)
{
super(context, attrs);
init();
}
void init()
{
// Set the bounds of the button
this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearIcon, null);
// button should be hidden on first draw
clrButtonHandler();
//if the clear button is pressed, clear it. Otherwise do nothing
this.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
CustomAutoCompleteTextView et = CustomAutoCompleteTextView.this;
if (et.getCompoundDrawables()[2] == null)
return false;
if (event.getAction() != MotionEvent.ACTION_UP)
return false;
if (event.getX() > et.getWidth() - et.getPaddingRight() - imgClearIcon.getIntrinsicWidth())
{
et.setText("");
CustomAutoCompleteTextView.this.clrButtonHandler();
justCleared = true;
}
return false;
}
});
}
void clrButtonHandler()
{
if (this == null || this.getText().toString().equals("") || this.getText().toString().length() == 0)
{
//Log.d("CLRBUTTON", "=cleared");
//remove clear button
this.setCompoundDrawables(null, null, null, null);
}
else
{
//Log.d("CLRBUTTON", "=not_clear");
//add clear button
this.setCompoundDrawablesWithIntrinsicBounds(null, null, imgClearIcon, null);
}
}
}
....
public class AutoCompleteTextAdapter extends ArrayAdapter<String> implements Filterable {
ArrayList<String> mSuggestions = null;
....
@Override
public Filter getFilter(){
Filter myFilter = new Filter() {
@Override
protected FilterResults performFiltering(CharSequence charSequence) {
FilterResults filterResults = new FilterResults();
if ( charSequence != null ){
// Now assign the values and count to the FilterResults object
if ( mSuggestions != null ){
filterResults.values = mSuggestions.toArray();
filterResults.count = mSuggestions.size();
}
Log.e(TAG, "performFiltering: finish;");
}
return filterResults;
}
@Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
Log.d(TAG, "publishResults: " + charSequence);
if ( filterResults != null && filterResults.count > 0 )
notifyDataSetChanged();
else
notifyDataSetInvalidated();
}
};
return myFilter;
}
public void updateList ( ArrayList<String> str ){
mSuggestions = str;
notifyDataSetChanged();
}
add this in your custom action bar layout:
<br.com.jandeilson.forgob.CustomAutoCompleteTextView
android:id="@+id/tv_actionbar_AutoComplete"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:ems="7"
android:imeOptions="actionSearch"
android:inputType="textAutoComplete|textAutoCorrect"
android:drawableRight="@android:drawable/ic_menu_close_clear_cancel"
android:hint="hint here"
android:textCursorDrawable="@null"
android:textColor="#FFFFFF">
</br.com.jandeilson.forgob.CustomAutoCompleteTextView>
write this into on resume:
ArrayList <String> list = new ArrayList<String>( ) ;
//List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
list.addAll(new ArrayList<String>(Arrays.asList(cursor.getColumnNames()))); // not getColumnNames() need use here;
adapter.updateList( list );