I have a List View that Displays songs in alphebetical order being populated by this method
public void updatelist(){
Cursor cursor = getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,null);
int j =0;
if(cursor.moveToFirst()){
do{
int ALBUM_ID = cursor.getInt((cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM_ID)));
int pathcolumn = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
String path1 = cursor.getString(pathcolumn);
String album_url = null;
Uri sArtworkUri = Uri.parse("content://media/external/audio/albumart");
Uri uri = ContentUris.withAppendedId(sArtworkUri, ALBUM_ID);
album_url = uri.toString();
ContentResolver res = this.getContentResolver();
// Album
String album_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.ALBUM));
String year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AudioColumns.YEAR));
// String year = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.AlbumColumns.NUMBER_OF_SONGS));
// artist
String artist_name = cursor.getString(cursor.getColumnIndex(MediaStore.Audio.ArtistColumns.ARTIST));
// display name
String DisplayName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
//title
String Title = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.TITLE));
songtitle.add(Title);
Collections.sort(songtitle);
artistname.add(songtitle.indexOf(Title), artist_name);
albumname.add(songtitle.indexOf(Title), album_name);
path.add(songtitle.indexOf(Title),path1);
albumartwork.add(songtitle.indexOf(Title),album_url);
j++;
}while(cursor.moveToNext());
}
Collections.sort(songtitle);
adapter = new ArrayAdapter<String>(this,R.layout.song,songtitle);
setListAdapter(adapter);
}
My Question is i want to insert Dividers whenever the first letter of the SongName Changes.
I have this method to get the first letter of the songname if it is different than the previous..
private void alphebetdividers(ArrayList<String> songtitle2) {
String newString = null;
// TODO Auto-generated method stub
ArrayList<Character> letters = new ArrayList<Character>();
int i = 0;
int j = 0;
while( j < songtitle.size()-1){
if(songtitle2.get(i).charAt(0) == songtitle2.get(i+1).charAt(0)){
Toast.makeText(getApplication(), songtitle2.get(i).charAt(0) + "== " + songtitle2.get(i+1).charAt(0), Toast.LENGTH_LONG).show();
}else{
// Display Char with TextView
String songName = songtitle2.get(i);
newString = songName.substring(0, 1);
}
j++;
i++;
}
How would i display this in the list view at the appropriate spots. Thank you and i will give u a good rating if u know the answer.
You probably want an Adapter that implements SectionIndexer, specifically AlphabetIndexer. See this or this.
You really should be using an Adapter... there are libraries that do all of this work for you, you shouldn't have to do it yourself in a massive loop!
Here is some sample code to help you get started... note that it is a little out-dated in that it makes use of some deprecated methods (such as managedQuery, etc.). If you wanted to be entirely 100% correct you would want to make use of the LoaderManager.LoaderCallbacks<Cursor interface introduced in the Honeycomb release, but it's a good start.
To sort the displayed views, you can make use of the sortOrder argument in the ContentProvider's query method.
Related
I am currently using a SearchView to take input and whenever the input changes i call searchVideo()
this is my searchVideo function :
public void searchVideo(String s)
{
videos.clear();
SQLiteDatabase sqLiteDatabase = getActivity().openOrCreateDatabase("CodifyData", MODE_PRIVATE, null);
String sql = "SELECT * FROM appdata_videos WHERE subcode='"+dbName+"' AND title LIKE '%"+s+"%'";
Cursor c = sqLiteDatabase.rawQuery(sql,null);
int idID = c.getColumnIndex("id");
int linkID = c.getColumnIndex("link");
int titleID = c.getColumnIndex("title");
while(c.moveToNext())
{
videos.add(new VideoDataModel(c.getString(idID), c.getString(titleID), c.getString(linkID)));
}
c.close();
videoAdapter.notifyDataSetChanged();
}
But when user inputs two words and those two works are contained by the title but not next to each other or in a way they are input by the user, the search fails, so what can i do to make this better, don't need a complicated solution but something simpler and easier to implement.
split your string by space to get array of words
and concat the values with query like that:
String[] splitedValues = str.split("\\s+");
String query="SELECT * FROM appdata_videos WHERE subcode='"+dbName+"' ";
for(int i=0;i<splitedValues .length;i++){
query+="AND title LIKE '%"+splitedValues[i]+"%' ";
}
hi
why load text from String array and set text to textview is very slow in big string array?
please help to me.
//get khotbe text from database and copy to khotbe activity
private void setkhotbetextarabicfarsi() {
this.sqliteDB = SQLiteDatabase.openOrCreateDatabase(this.getDatabasePath("aliname").getPath(), (SQLiteDatabase.CursorFactory) null);
Itemid = this.getIntent().getIntExtra("selectedFromListid", 1);
Cursor cursorLines = this.sqliteDB.rawQuery("SELECT * FROM khotbe where IDFehrest=" + this.Itemid , (String[]) null);
allrecs = cursorLines.getCount();
matn = new String[allrecs];
if (this.allrecs != 0) {
cursorLines.moveToFirst();
for (int i = 0; i < this.allrecs; ++i) {
String TextArabicOfKhotbe = cursorLines.getString(cursorLines.getColumnIndex("TextArabicOfKhotbe"));
int IDkhotbe = cursorLines.getInt(cursorLines.getColumnIndex("IDkhotbe"));
this.matn[i] = TextArabicOfKhotbe;
cursorLines.moveToNext();
}
}
and main code:
for(int var1 = 0; var1 < this.allrecs; ++var1) {
tvArabic = new JustifiedTextView(this);
tvArabic.setText(matn[var1]);
you are creating the textviews in loop that might making it slow.. try populating the array values using an adapter..
Also check the number of rows you are accessing from the DB. if they are huge in number, they would require more time to be fetched.
Use limit in that case.
Following This Retrieving a List of Contacts Tutorial in the android developers site, I managed to implement contacts search functionality. Here is my code so far
private void retrieveContactRecord(String phoneNo) {
try {
Log.e("Info", "Input: " + phoneNo);
Uri uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(phoneNo));
String[] projection = new String[]{ContactsContract.PhoneLookup._ID, ContactsContract.PhoneLookup.DISPLAY_NAME};
String sortOrder = ContactsContract.PhoneLookup.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
ContentResolver cr = getContentResolver();
if (cr != null) {
Cursor resultCur = cr.query(uri, projection, null, null, sortOrder);
if (resultCur != null) {
while (resultCur.moveToNext()) {
String contactId = resultCur.getString(resultCur.getColumnIndex(ContactsContract.PhoneLookup._ID));
String contactName = resultCur.getString(resultCur.getColumnIndexOrThrow(ContactsContract.PhoneLookup.DISPLAY_NAME));
Log.e("Info", "Contact Id : " + contactId);
Log.e("Info", "Contact Display Name : " + contactName);
break;
}
resultCur.close();
}
}
} catch (Exception sfg) {
Log.e("Error", "Error in loadContactRecord : " + sfg.toString());
}
}
Here is the catch, this code works pretty great, but I need to implement a smart search here. I want 26268 to match Amanu as well as 094 526 2684. I believe it is called T9 dictionary.
I tried looking at other projects for clue, but I couldn't find anything. Any pointers would be appreciated!
T9 search can be implemented using trie data structure. You can see an example here - Trie dict.
After implementing something similar you will be able to convert your search input into its possible T9 decoded variant and compare if it matches with name.
Dump all contacts to a HashSet
Set<String> contacts = new HashSet<String>();
Then search:
List<List<String>> results = new ArrayList<List<String>>();
// start the search, pass empty stack to represent words found so far
search(input, dictionary, new Stack<String>(), results);
Search method (from #WhiteFang34)
public static void search(String input, Set<String> contacts,
Stack<String> words, List<List<String>> results) {
for (int i = 0; i < input.length(); i++) {
// take the first i characters of the input and see if it is a word
String substring = input.substring(0, i + 1);
if (contacts.contains(substring)) {
// the beginning of the input matches a word, store on stack
words.push(substring);
if (i == input.length() - 1) {
// there's no input left, copy the words stack to results
results.add(new ArrayList<String>(words));
} else {
// there's more input left, search the remaining part
search(input.substring(i + 1), contacts, words, results);
}
// pop the matched word back off so we can move onto the next i
words.pop();
}
}
}
The ContentProvider for contacts doesn't support it. So what I did was to dump all of the contacts in a List then use a RegEx to match for the name.
public static String[] values = new String[]{" 0", "1", "ABC2", "DEF3", "GHI4", "JKL5", "MNO6", "PQRS7", "TUV8", "WXYZ9"};
/**
* Get the possible pattern
* You'll get something like ["2ABC","4GHI"] for input "14"
*/
public static List<String> possibleValues(String in) {
if (in.length() >= 1) {
List<String> p = possibleValues(in.substring(1));
String s = "" + in.charAt(0);
if (s.matches("[0-9]")) {
int n = Integer.parseInt(s);
p.add(0, values[n]);
} else {
// It is a character, use it as it is
p.add(s);
}
return p;
}
return new ArrayList<>();
}
.... Then compile the pattern. I used (?i) to make it case insensitive
List<String> values = Utils.possibleValues(query);
StringBuilder sb = new StringBuilder();
for (String value : values) {
sb.append("[");
sb.append(value);
sb.append("]");
if (values.get(values.size() - 1) != value) {
sb.append("\\s*");
}
}
Log.e("Utils", "Pattern = " + sb.toString());
Pattern queryPattern = Pattern.compile("(?i)(" + sb.toString() + ")");
You'll know what to do after this.
I have managed to extract the first letters on a sentence and store that into a variable.
String[] result = matches.toString().split("\\s+");
// The string we'll create
String abbrev = "";
// Loop over the results from the string splitting
for (int i = 0; i < result.length; i++){
// Grab the first character of this entry
char c = result[i].charAt(0);
// If its a number, add the whole number
if (c >= '0' && c <= '9'){
abbrev += result[i];
}
// If its not a number, just append the character
else{
abbrev += c;
}
}
I then store the values into a Final String Array;
List<String> list = Arrays.asList(abbrev);
final String[] cs12 = list.toArray(new String[list.size()]);
I then set the values into a alert dialog as follows:
builder2.setItems(cs12[0].toString().split(","), new DialogInterface.OnClickListener(){
My next task is when the user selects one of the items for it to go into the text view. However it doesn't let me do this.
public void onClick(DialogInterface dialog, int item) {
TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
speechText.setText(Arrays.toString(cs12));
// TextView speechText = (TextView)findViewById(R.id.autoCompleteTextView1);
// speechText.setText(matches.get(item).toString());
However for my other parts matches.get works fine but I cant seem to get cs12.get.
Any Ideas?
Thanks
Use cs12[0].toString().split(",")[item] to show selected item in TextView:
String[] strArr= cs12[0].toString().split(",");
speechText.setText(strArr[item]);
Ok this should be straight forward but i'm having difficulty with it. So far i've got this code.
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
// On selecting a spinner item
SpinnerFAQ = parent.getItemAtPosition(position).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "You selected: " + SpinnerFAQ,
Toast.LENGTH_LONG).show();
TextView tv = (TextView) findViewById(R.id.faq_answer);
ExerciseData question = new ExerciseData(this);
question.open();
String answer = question.getFaqAnswer();
question.close();
tv.setText(answer);
}
SpinnerFAQ is a global variable and it stores the value of the spinner as String.
public String getFaqAnswer() {
// TODO Auto-generated method stub
String[] columns = new String[] { FAQ_ROWID, FAQ_QUESTION, FAQ_ANSWER};
Cursor c = ourDatabase.query(DATABASE_TABLE2, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(FAQ_ROWID);
int iQuestion = c.getColumnIndex(FAQ_QUESTION);
int iAnswer = c.getColumnIndex(FAQ_ANSWER);
//c.getString(iRow) + " " +
for(c.moveToFirst(); !c.isAfterLast(); c.moveToNext())
{
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
{
result = result + c.getString(iAnswer) + "\n";
break;
}
}
return result;
}
This is based on code I've already used, but basically I want to check the Spinner against the Question in my Database and if they match I want to change the Text View to the answer. Right now the FAQ.SpinnerFAQ works fine, but c.getString(iQuestion) always shows up as the last value in the database. This code "result = result + c.getString(iAnswer) + "\n";" works fine without the if statement, so I don't really understand why there is a problem with "c.getString(iQuestion)". Any help would be greatly appreciated.
if(FAQ.SpinnerFAQ == c.getString(iQuestion))
Never compare Strings with == in Java, always use equals(). Please read: How do I compare strings in Java? and change every String comparison to:
if(FAQ.SpinnerFAQ.equals(c.getString(iQuestion)))