0

I have a listview populated from database which consists of phrases(in english) and it's translation(in malay). The interface is like the image below.

https://i.stack.imgur.com/LJIqY.jpg

For starter, my goal is to search the listview by phrases. When a keyword is entered in the search EditText, I want the listview to be filtered accordingly. I already have the EditText ready there,

but I have no idea how to start. Reading a lot of tutorials made me confused. I'm not even sure that my approach is correct.

Here is activity ListGreetings.java`

ListView userList;
GreetingAdapter greetAdapter;
EditText inputSearch;
ArrayList<Frasa> frasaArray;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_list_greetings);

    //database activities
    DB db = new DB(this);

    try {
        db.create();
    } catch (IOException ioe) {
        throw new Error("Unable to create database");
    }

    if(db.open()) {
        //get Frasa data
        frasaArray = db.getFrasa("Greetings");


        /**
         * set item into adapter
         */
        greetAdapter = new GreetingAdapter(ListGreetings.this, R.layout.list_item_greet, frasaArray);
        userList = (ListView) findViewById(R.id.listGreetings);
        userList.setItemsCanFocus(false);
        userList.setAdapter(greetAdapter);
    }

    //inputSearch.setOnQueryTextListener(this);

        //Searching start here
        inputSearch = (EditText) findViewById(R.id.inputSearch);
        inputSearch.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void onTextChanged(CharSequence s, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                // When user changed the Text
            }
        });
}

GreetingAdapter.java

public class GreetingAdapter extends ArrayAdapter<Frasa> {
int layoutResourceId;
Context context;
Resources resources;
ArrayList<Frasa> data = new ArrayList<Frasa>();
MediaPlayer speak;

//recorder variables
MediaPlayer playRecorder = null;
MediaRecorder recorder = null;
String mFileName = null;
final String LOG_TAG = "malay4U_Record";
boolean mStartRecording = true;
boolean mStartPlaying = true;

public GreetingAdapter(Context context, int layoutResourceId, ArrayList<Frasa> data)
{
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.resources = this.context.getResources();
    this.data = data;
    this.mFileName =  Environment.getExternalStorageDirectory().getAbsolutePath();
    mFileName += "/audiorecordtest.3gp";

}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View row = convertView;
    UserHolder holder = null;

    if (row == null) {
        LayoutInflater inflater = ((Activity) context).getLayoutInflater();
        row = inflater.inflate(layoutResourceId, parent, false);
        holder = new UserHolder();
        holder.textPhrase = (TextView) row.findViewById(R.id.textViewPhrase);
        holder.textTranslate = (TextView) row.findViewById(R.id.textViewTranslate);
        holder.btnSpeak = (Button) row.findViewById(R.id.buttonSpeak);
        holder.btnRecord = (Button) row.findViewById(R.id.buttonRecord);
        holder.btnPlay = (Button) row.findViewById(R.id.buttonPlay);
        row.setTag(holder);
    } else {
        holder = (UserHolder) row.getTag();
    }
    final Frasa frasa = data.get(position);
    holder.textPhrase.setText(frasa.getPhrase());
    holder.textTranslate.setText(frasa.getTranslate());

    //button speak action
    holder.btnSpeak.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            String direct = frasa.getPronounce(); //audio file directory where in database stored as raw/filename

            int resID = resources.getIdentifier(direct, "String", "hairulhazri.malayforyou"); //convert string to resouce ID
            speak = MediaPlayer.create(context, resID);
            speak.start();
        }
    });

    //button Record action

    holder.btnRecord.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            onRecord(mStartRecording);
            if (mStartRecording) {
                Log.i("Record Button Clicked", "**********");
                Toast.makeText(context, "Recording....",
                        Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Recording finished.",
                        Toast.LENGTH_LONG).show();
            }
            mStartRecording = !mStartRecording;


        }
    });

    //button play record action
    holder.btnPlay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.i("Play Button Clicked", "*******");
            onPlay(mStartPlaying);

            mStartPlaying = !mStartPlaying;
        }
    });
    return row;

}

static class UserHolder {
    SearchView inputSearch;
    TextView textPhrase;
    TextView textTranslate;
    Button btnSpeak;
    Button btnRecord;
    Button btnPlay;
}

}

function getFrasa in database

public ArrayList<Frasa> getFrasa(String situation ) {

    //ArrayList of Frasa class objects
    ArrayList<Frasa> arrFrasa = null;
    String selectQuery = "SELECT * FROM Frasa WHERE situation = " +"'"+situation+"'";

    db = SQLiteDatabase.openDatabase( DB_PATH + DB_NAME , null, SQLiteDatabase.OPEN_READWRITE);
    Cursor curFrasa = db.rawQuery(selectQuery, null);

    if (curFrasa != null && curFrasa.moveToFirst()) {
        arrFrasa = new ArrayList<Frasa>();
        while (curFrasa.isAfterLast() == false) {
            //Frasa is a class with list of fields
            Frasa fra = new Frasa();
            fra.setId(curFrasa.getInt(curFrasa.getColumnIndex(Frasa.KEY_ID)));
            fra.setPhrase(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PHRASE)));
            fra.setTranslate(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_TRANSLATE)));
            fra.setPronounce(curFrasa.getString(curFrasa.getColumnIndex(Frasa.KEY_PRONOUNCE)));
            arrFrasa.add(fra);
            curFrasa.moveToNext();
        }
    }


    curFrasa.close();
    db.close();
    return arrFrasa;
}

Where do I apply the filtering? Inside ListGreetings or GreetingAdapter? And how?

Thank you in advance.

Anil Meenugu
  • 1,411
  • 1
  • 11
  • 16
HHS
  • 31
  • 1
  • 5
  • You should be doing filtering in GreetingsAdapter, it has a getFilter() method which is to be overridden, inorder to achieve ListView filtering – capt.swag Jun 24 '15 at 08:18
  • your data model is an sqlite db so use a `SimpleCursorAdapter`, **not** `ArrayAdapter` – pskink Jun 24 '15 at 08:18
  • Here's an example of using filtering in Adapter. https://github.com/4k3R/httpstatuscodes-android/blob/master/app/src/main/java/anjithsasindran/httpstatuscodes/MainAdapter.java#L64 – capt.swag Jun 24 '15 at 08:19
  • why do I have to use SimpleCursorAdapter instead of ArrayAdapter? Is it impossible to filter if I use ArrayAdapter? – HHS Jun 24 '15 at 08:25
  • because it is far easier to deal with it when your data is stored in sqlite db, your code will be much shorter, i have no idea why people here are using `ArrayAdapter` in such case... – pskink Jun 24 '15 at 08:30
  • [i tihink it will help you and u may do some changes][1] [1]: http://stackoverflow.com/questions/14118309/how-to-use-search-functionality-in-custom-list-view-in-android/14119383#14119383 – Android Devloper's Jun 24 '15 at 08:45
  • @GhedOneRaj his data come from sqlite db so `BaseAdapter` or `ArrayAdapter` is definitely a wrong solution – pskink Jun 24 '15 at 08:57
  • I see. So the best practice is to use SimpleCursorAdapter. I'll keep that in mind. But in this case ArrayAdapter is usable right? For now I'll just stick with it. – HHS Jun 24 '15 at 09:14
  • no, `ArrayAdapter` is not a good option in this case, prepare for a lot of problems if you want to keep `ArrayAdapter`, tell me why don't you want to use `SimpleCursorAdapter` ? good luck anyway... – pskink Jun 24 '15 at 09:17

0 Answers0