Click here to Skip to main content
15,889,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
can anyone help me to modify this code so I can get a Highlighted search result in ListView. I'm still a beginner in this so I don't know anymore how to do it. the search result is already displayed but i need to make it to highlight a spesific character or word.
can anyone out there help me please, i'm really stuck.
and I'm still using Eclipse IDE, cuz actually this is my old project that i made before google changing the official IDE for android to Android Studio. and this project never complete since then.

What I have tried:

Java
package com.artstudio.testhighlight;

import java.util.Locale;

import com.artstudio.testhighlight.DatabaseSong;

import android.os.Bundle;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.content.Context;
import android.content.res.ColorStateList;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextWatcher;
import android.text.style.TextAppearanceSpan;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.database.Cursor;    
import android.database.sqlite.SQLiteDatabase;

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
		}
}
Posted
Updated 9-Sep-17 13:29pm
Comments
David Crow 9-Sep-17 10:58am    
Have you considered asking this type of question in the actual Android forum here at CP? This section is really meant for quick/short answers.
Richard MacCutchan 9-Sep-17 11:33am    
It is impossible to guess where your problem is in all that code.

1 solution

Not a solution to your question, but another problem you have.
Java
LaguCursor = db.rawQuery("SELECT (UPPER('\n\n___ '||nomor||'. '||judul)||'\n\n'||lirik) FROM tbl_Lagusion WHERE lirik LIKE '%"+value+"%' ", null);

Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
 
Share this answer
 
v3
Comments
David Crow 10-Sep-17 15:55pm    
This should have been a comment rather than a solution.
Patrice T 10-Sep-17 17:15pm    
Thanks for the comment, at least you tell your opinion, most downvoters don't have such courage.
I disagree with you, I think 'SQL injection' is a real problem and advising about it is worth a solution even if it is not the OP question.
David Crow 11-Sep-17 8:19am    
1) I did not "downvote" anything.
2) Not once did I say, or even imply, that SQL injection was not a problem. The OP had a problem with searching in a ListView. You commented about something entirely different, yet marked your comment as the solution. THAT'S what I was in disagreement with.
Patrice T 11-Sep-17 8:46am    
'I did not "downvote" anything.'
I didn't said you did.
'You commented about something entirely different, yet marked your comment as the solution. THAT'S what I was in disagreement with.'
I take note of it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900