0

How can I modify this code so it can highlight the search result in the listView?

Here's the full code of my project.

public class MainActivity extends Activity implements OnItemClickListener, TextWatcher {
    private ListView daftarLagu;
    private String[] tampungLaguLirik = null;
    protected static String strSearchLyric = null;  

    // Test Highlight
    private String mSearchText;

     //deklarasi keperluan untuk database
    private SQLiteDatabase db = null;  
    private Cursor LaguCursor = null;  
    private DatabaseSong datalagu = null;  

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        datalagu = new DatabaseSong(this);  
        db = datalagu.openDataBase();
        db = datalagu.getReadableDatabase();
        datalagu.onCreate(db);

      //buat object dari dataLagu  

        setContentView(R.layout.activity_search);

        daftarLagu = (ListView)findViewById(R.id.listIndexLagu);

        //buat listener dari list view pada aplikasi pencarian tanaman obat
        daftarLagu.setOnItemClickListener(this);

      //Tombol Ganti Jenis Pencarian
        TextView text = (TextView) findViewById(R.id.pencarian);
        text.setText("PENCARIAN LIRIK LAGU");

        Button nomorBtn = (Button) findViewById(R.id.btnSwitchPencarian);
        nomorBtn.setText("CARI NOMOR, JUDUL, PENGARANG");

        nomorBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
                db.close();
                //startActivity(new Intent(MainActivity.this, SearchActivity.class));
            }
        });

      //Tombol Cari Lagu
        EditText textCari = (EditText)findViewById(R.id.editTextcari);
        textCari.setHint("Masukan Potongan Lirik Lagu");
        textCari.addTextChangedListener(this);
    }

  //buat overread method dari set on item click listener
     public void onItemClick(AdapterView<?> arg0, View arg1, int posisi, long arg3) {

         Toast.makeText(MainActivity.this, "ini pas saya click", Toast.LENGTH_SHORT).show();

            //Toast.makeText(SearchLyricActivity.this, ""+tampungLaguLirik[posisi], Toast.LENGTH_SHORT).show();
            //panggil method yang dibuat untuk handler tampilkan gambar dari data tanaman
            cariTampilView(""+tampungLaguLirik[posisi]);
            posisi = 0;
     }


        //fungsi
         public void cariTampilView(String cari){
             LaguCursor = null;
             //memilih lagu dari daftar
             LaguCursor = db.rawQuery("SELECT lirik, nomor||'. '||judul "  
                              + "FROM tbl_Lagusion WHERE (UPPER('\n\n___ '||nomor||'. '||judul)||'\n\n'||lirik) = '"+ cari +"' ", null);  
                if (LaguCursor.moveToFirst()) {  
                    strSearchLyric = null;
                    strSearchLyric = LaguCursor.getString(0); 
                    Toast.makeText(MainActivity.this, LaguCursor.getString(1).toString(), Toast.LENGTH_SHORT).show();

                    //for (; !LaguCursor.isAfterLast(); LaguCursor.moveToNext()) {  
                    //  strSearchLyric = LaguCursor.getString(0);               
                    //    }  
                }  

                if (strSearchLyric.equals("")) {      
                    strSearchLyric = "Terjemahan Not Found";  
                    Toast.makeText(MainActivity.this, "Pencarian tidak ditemukan........!", Toast.LENGTH_SHORT).show();

                }else{
                    //hasil yang didapat dan di tampilkan ke frame_view
                    Toast.makeText(MainActivity.this, "Sadisssssss\n"+LaguCursor.getString(0).toString(), Toast.LENGTH_SHORT).show();
                    //Intent x = new Intent(MainActivity.this, LyricViewer.class);
                    //startActivity(x);
                }
         }

    void tampilLagu(){
        strSearchLyric = null;
        EditText text=(EditText)findViewById(R.id.editTextcari);
        text.setTextColor(Color.parseColor("#0066FF"));
        String value = text.getText().toString();
        int length = text.length();
        value = value.trim();
        value = value.replaceAll("'","’");
        //value = value.replaceAll(",","");

        if (length == 0){
            value = null;
        }

        int Hitung =0;
        //Untuk menampilkan daftar lagu pada Index Lagu
        LaguCursor = db.rawQuery("SELECT (UPPER('\n\n___ '||nomor||'. '||judul)||'\n\n'||lirik) FROM tbl_Lagusion WHERE lirik LIKE '%"+value+"%' ", null);  

            tampungLaguLirik = new String[LaguCursor.getCount()];
            LaguCursor.moveToFirst();
            Toast.makeText(MainActivity.this, "klot "+LaguCursor.getCount(), Toast.LENGTH_SHORT).show();

            for (int cc=0; cc < LaguCursor.getCount(); cc++)
            {
                Hitung = Hitung +1;
                LaguCursor.moveToPosition(cc);
                tampungLaguLirik[cc] = LaguCursor.getString(0).toString();
            }



            if(Hitung == 0){
                daftarLagu = (ListView)findViewById(R.id.listIndexLagu);
                daftarLagu.setFastScrollEnabled(true);
                daftarLagu.setBackgroundColor(Color.TRANSPARENT);
                daftarLagu.setAnimationCacheEnabled(true);
                daftarLagu.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, tampungLaguLirik));
                daftarLagu.setSelected(true);

                //daftarLagu..setTypeface(null, Typeface.BOLD);
                //pesanPengguna("Lagu Tidak Ditemukan!");
            }else{
                daftarLagu = (ListView)findViewById(R.id.listIndexLagu);
                daftarLagu.setFastScrollEnabled(true);
                daftarLagu.setBackgroundColor(Color.TRANSPARENT);
                daftarLagu.setAnimationCacheEnabled(true);
                daftarLagu.setAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1, tampungLaguLirik));
                daftarLagu.setSelected(true);
            }


        }


     private String getItem(int position) {
        // TODO Auto-generated method stub
        return null;
    }

    public void onBackPressed() {
         strSearchLyric = null;
         db.close();
          finish();//memanggil method exit()
     }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub
            tampilLagu();
        }

        @Override
        public boolean dispatchTouchEvent(MotionEvent event) {

            View v = getCurrentFocus();
            boolean ret = super.dispatchTouchEvent(event);

            if (v instanceof EditText) {
                View w = getCurrentFocus();
                int scrcoords[] = new int[2];
                w.getLocationOnScreen(scrcoords);
                float x = event.getRawX() + w.getLeft() - scrcoords[0];
                float y = event.getRawY() + w.getTop() - scrcoords[1];
               // Toast.makeText(MainActivity.this, "klot", Toast.LENGTH_SHORT).show();
               // Log.d("Activity", "Touch event "+event.getRawX()+","+event.getRawY()+" "+x+","+y+" rect "+w.getLeft()+","+w.getTop()+","+w.getRight()+","+w.getBottom()+" coords "+scrcoords[0]+","+scrcoords[1]);
                if (event.getAction() == MotionEvent.ACTION_UP && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w.getBottom()) ) { 
                //  Toast.makeText(MainActivity.this, "klot klot", Toast.LENGTH_SHORT).show();
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
                }
            }
        return ret;
        }

        @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
        }
}

I really have no idea, I already search the answers related to this, but I just don't know how to implement all the logic or code to my code. I'm still using Eclipse. This is a project that I made before the official IDE change to Android Studio.

please give me an example base on my code.

I Already tried to use spannable but it doesn't work here's the code I add a method but still doesn't work, what did i missed?

    private Spannable highlightSearchKey(String title) {
            Spannable  highlight;
            Pattern    pattern;
            Matcher    matcher;
            int        word_index;
            String     title_str;

            word_index = tampungLaguLirik.length;
            title_str  = Html.fromHtml(title).toString();
            highlight  = (Spannable) Html.fromHtml(title);
            Toast.makeText(MainActivity.this, "Word Index "+word_index+" terus "+title_str+" Span "+highlight, Toast.LENGTH_SHORT).show();
            for (int index = 0; index < word_index; index++) {
                pattern = Pattern.compile("(?i)" + tampungLaguLirik[index]);
                matcher = pattern.matcher(title_str);
                while (matcher.find()) {
                    highlight.setSpan(
                        new BackgroundColorSpan(0x44444444), 
                        matcher.start(), 
                        matcher.end(), 
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
            }
            return highlight;
        }

and call this method here:

//Untuk menampilkan daftar lagu pada Index Lagu
        LaguCursor = db.rawQuery("SELECT (UPPER('\n\n___ '||nomor||'. '||judul)||'\n\n'||lirik) FROM tbl_Lagusion WHERE lirik LIKE '%"+value+"%' ", null);  

            tampungLaguLirik = new String[LaguCursor.getCount()];
            LaguCursor.moveToFirst();
            Toast.makeText(MainActivity.this, "klot "+LaguCursor.getCount(), Toast.LENGTH_SHORT).show();

            for (int cc=0; cc < LaguCursor.getCount(); cc++)
            {
                Hitung = Hitung +1;
                LaguCursor.moveToPosition(cc);
                tampungLaguLirik[cc] = LaguCursor.getString(0).toString();
                highlightSearchKey(value);
            }

but still I cannot highlight the same character that i type in editText field.

  • may be this link will help to you-> https://stackoverflow.com/questions/33417887/how-do-i-highlight-the-searched-text-in-my-search-filter – ND1010_ Sep 08 '17 at 08:14
  • ahhahaha i got same link while search about the same LOL – ND1010_ Sep 08 '17 at 08:14
  • find: https://stackoverflow.com/questions/25137400/how-to-highlight-the-filtered-text-while-using-searchview-widget-in-android – ND1010_ Sep 08 '17 at 08:15
  • can please look at the code, i have no idea to do it in my code. this is my first program that i made. so basicly i don't really understad all the function or the method. i'm really stuck and don't have any idea no more. – Mozart Sabatino Lumowa Sep 09 '17 at 13:01
  • Welcome to Stack Overflow! Please do not vandalise your posts. Once you have submitted a post, you have licensed the content to the Stack Overflow community at large (under the CC-by-SA license). If you would like to disassociate this post from your account, see [What is the proper route for a disassociation request](https://meta.stackoverflow.com/questions/323395)? – Jed Fox Sep 09 '17 at 20:36

0 Answers0