android app Search operation with broken words - android

Hi i am doing a search operation in the app using a specific keyword and listing the result in a list view activity. The result will be displayed with 50 characters before and after the searched keyword but when i take 50 characters it breaks the words and in the result half words or single letters are displayed in the beginning and after. How could i ignore and get complete words
Below is my code. please do help me on this. thanks in advance
int endindex = searchTextStartIndex + searchTextLength + 50;
if (searchTextStartIndex > 50) {
startindex = searchTextStartIndex - 50;
}
if (endindex > datalength) {
endindex = datalength;
}
searchdata = searchdata.substring(startindex, endindex);
} catch (Exception e)

Assuming a space as word seperator:
if (searchTextStartIndex > 50) {
startindex = searchdata.lastIndexOf( " ", (searchTextStartIndex - 50) );
}
if (startindex == -1) startindex = 0;
int endindex = searchdata.indexOf( " ", (searchTextStartIndex + searchTextLength + 50) );
if (endindex == -1 || endindex > datalength) {
endindex = datalength;
}
searchdata = searchdata.substring(startindex, endindex);

Related

TextWatcher - Increase value of last char by one

What I am trying to do is this: User enters text in an edittext. Example: "ab" then when he enters a character like '<' let's say, that would cause the last char typed before that to be increased by one. In this example, it'd do "ac" ('<' should be deleted too). On onTextChanged method, I use:
if (s.length() > 0 && s.toString().charAt(s.length() - 1) == '<') { //ab<
character = s.toString().charAt(s.length() - 2); //keep b
current_string = s.toString().substring(0, (s.length() - 2)); //a
et.setText(current_string); //set a
next_character_to_integer = (int) character + 1; //b is 98 ascii, need 99
integer_to_character = (char) next_character_to_integer; // 99 = char c
et.setText(s + String.valueOf(integer_to_character)); //set a+c
length = s.length();
et.setSelection(length); //move cursor after c
}
But this gives "abqc"!!! I might be close enough but still can't find the solution. Any ideas? Thanks a lot
Try this:
if (s.length() > 0 && s.toString().charAt(s.length() - 1) == '<') {
character = s.toString().charAt(s.length() - 2);
current_string = s.toString().substring(0, (s.length() - 2));
character += 1;
et.setText(current_string + character);
length = et.getText().toString().length();
et.setSelection(length);
}
This should work.
When you call:
et.setText(s + String.valueOf(integer_to_character)); //set a+c
you are using the original value of s which you have not updated. Change the line to:
et.setText(current_string + String.valueOf(integer_to_character)); //set a+c
and see what you get.

Android : Remove last paragraph tag generated by Html.toHtml

I'm editing content that may be html in an EditText. Just before saving the result, I use Html.toHtml to convert the input into a string to be sent to the server. However this method call seems to be generating paragraph tags which I dont need. Eg -
Test edited
seems to get converted to
<p dir="ltr">Test edited</p>
I would like to strip out the last paragraph tag before saving the content. If there are other paragraph tags, I would like to keep those. I have this regex that matches all p tags
"(<p.*>)(.*)(</p>)";
but I'm not sure how to match just the last paragraph and remove just the tags for it.
public static void handleOneParagraph(SpannableStringBuilder text) {
int start = 0;
int end = text.length();
String chars1 = "<p";
if (end < 2)
return;
while (start < end ) {
String seq = text.toString().substring(start, start + 2);
if (seq.equalsIgnoreCase(chars1))
break;
start++;
}
if (text.toString().substring(start, start + 2).equalsIgnoreCase(chars1) ) {
int start2 = start + 1;
String chars2 = ">";
while (start2 < end && !text.subSequence(start2, start2+1).toString().equalsIgnoreCase(chars2) ) {
start2++;
}
if (start2 >= end)
return;
text.replace(start, start2+1, "");
end = text.length();
start = end;
String chars3 = "</p>";
while (start > start2 + 4) {
String last_p = text.subSequence(start - 4, start).toString();
if (last_p.equalsIgnoreCase(chars3) ) {
text.replace(start - 4, start, "");
break;
}
start--;
}
}
}
And now, you can use it like this...
SpannableStringBuilder cleaned_text = new SpannableStringBuilder(Html.toHtml(your_text));
handleOneParagraph(cleaned_text);

Android loop through string to color specific words

I have a string that has specific words I want to color. Those words are the one's that start with #.
if(title.contains("#")){
SpannableString WordtoSpan = new SpannableString(title);
int idx = title.indexOf("#");
if (idx >= 0) {
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
Matcher matcher = pattern.matcher(title);
int wordEnd = matcher.find(idx)? matcher.start() : -1;
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE),
idx,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
}
holder.txtTitle.setText(WordtoSpan);
} else {
holder.txtTitle.setText(title);
}
Now lets take for example this string
Bold part is for example the colored words.
I love cheese #burgers, and with #ketchup.
^ This is my current thing with my code. What I want is to color every # word, not just first one.
ex. It'll be like
I love cheese #burgers, and with #ketchup.
I think I need to loop? But couldn't get it clearly and working x.x
Update:
Latest try. List becomes blank.
SpannableString WordtoSpan = new SpannableString(title);
int end = 0;
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
Matcher matcher = pattern.matcher(title);
int i = title.indexOf("#");
for (i = 0; i < title.length(); i++) {
if (i >= 0) {
int wordEnd = matcher.find(i)? matcher.start() : -1;
if (wordEnd < 0) {
wordEnd = title.length();
}
WordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE),
i,
wordEnd,
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
i = end;
}
holder.txtTitle.setText(WordtoSpan);
}
I had provided this answer earlier here - https://stackoverflow.com/a/20179879/3025732
String text = "I love chicken #burger , cuz they are #delicious";
//get the text from TextView
Pattern HASHTAG_PATTERN = Pattern.compile("#(\\w+|\\W+)");
Matcher mat = HASHTAG_PATTERN.matcher(text);
while (mat.find()) {
String tag = mat.group(0);
//String tag will contain the hashtag
//do operations with the hashtag (change color)
}
[EDIT]
I've modified the code and done it according to what you need:
SpannableString hashText = new SpannableString(text.getText().toString());
Matcher matcher = Pattern.compile("#([A-Za-z0-9_-]+)").matcher(hashText);
while (matcher.find())
{
hashText.setSpan(new ForegroundColorSpan(Color.BLUE), matcher.start(), matcher.end(), 0);
}
text.setText(hashText);
Here's a screenshot of it:
I'm surprised that no one has mentioned this:
// String you want to perform on
String toChange = "I love cheese #burgers, and with #ketchup.";
// Matches all characters, numbers, underscores and dashes followed by '#'
// Does not match '#' followed by space or any other non word characters
toChange = toChange.replaceAll("(#[A-Za-z0-9_-]+)",
"<font color='#0000ff'>" + "$0" + "</font>");
// Encloses the matched characters with html font tags
// Html#fromHtml(String) returns a Spanned object
holder.txtTitle.setText(Html.fromHtml(toChange));
#0000ff ==>> Color.BLUE
Screenshot:
You need to loop through your matches. There is a previous post you can have a look at here:
Finding Multiple Integers Inside A String Using Regex
Check following example :
String title = "Your #complete sentence #testing #test.";
printUsingNormal(title);
printUsingRegex(title);
private static void printUsingRegex(String title) {
Pattern pattern = Pattern.compile("[ ,\\.\\n]");
int start = 0;
int end = 0;
Matcher matcher = pattern.matcher(title);
while (end >= 0 && end < title.length()) {
start = title.indexOf('#', start);
if (start > 0) {
end = matcher.find(start) ? matcher.start() : -1;
if (end > 0) {
System.out.println("Word : " + title.substring(start, end)
+ " Start : " + start + " End : " + end);
start = end;
}
} else {
break;
}
}
}
private static void printUsingNormal(String title) {
int start = 0;
for (int i = 0; i < title.length(); i++) {
char c = title.charAt(i);
if (c == '#') {
start = i; // Got the starting hash
int end = title.indexOf(' ', i + 1); // Finding the next space.
if (end > 0) {
System.out.println("Word : " + title.substring(start, end)
+ " Start : " + start + " End : " + end);
i = end;
} else {
end=title.length()-1;
System.out.println("Word : " + title.substring(start, end)
+ " Start : " + start + " End : " + end);
i = end;
}
}
}
}
Use while(), this is the snippet for setting the background color of text searched in android native messenger, you can try the same in your code.

Displaying values to a TextView

hi i have problem in displaying a value into my TextView..
For example i will input 1,2,3,4 then i like to display the output in this manner in my TextView..How can i do that? please help me, thank you in advance
1 appeared 1 times
2 appeared 1 times
3 appeared 1 times
4 appeared 1 times
here's my code:
String []values = ( sum.getText().toString().split(","));
double[] convertedValues = new double[values.length];
Arrays.sort(convertedValues);
int i=0;
int c=0;
while(i<values.length-1){
while(values[i]==values[i+1]){
c++;
i++;
}
table.setText(values[i] + " appeared " + c + " times");
c=1;
i++;
if(i==values.length-1)
table.setText(values[i] + " appeared " + c + " times");
Make your textView to support multipleLines and after that create in code a StringBuffer and append to it the results, something like
resultString.append(result).append(" appeared").append(c).append(" times\n");
after that you set text for textView like:
textView.setText(resultString.toString());
Here is the idea :
// this is test string, you can read it from your textView
String []values = ( "2, 1, 3, 5, 1, 2".toString().split(","));
int [] intValues = new int[values.length];
// convert string values to int
for (int i = 0; i < values.length; ++i) {
intValues[i] = Integer.parseInt(values[i].trim());
}
// sort integer array
Arrays.sort(intValues);
StringBuilder output = new StringBuilder();
// iterate and count occurrences
int count = 1;
// you don't need internal loop, one loop is enough
for (int i = 0; i < intValues.length; ++i) {
if (i == intValues.length - 1 || intValues[i] != intValues[i + 1]) {
// we found end of "equal" sequence
output.append(intValues[i] + " appeared " + count + " times\n");
count = 1; // reset count
} else {
count++; // continue till we count all equal values
}
}
System.out.println(output.toString()); // prints what you extected
table.setText(output.toString()); // display output

setSelectionRange workaround doesn't work for android 4.0.3

I am trying to mask the phone number as the user types. I have used the javascript code below with jquery and the setTimeout workaround successfully on android 2.x devices, but I have not found a workaround for that works for android 4.0.3.
if (navigator.userAgent.toLowerCase().indexOf("android") >= 0) {
$.fn.usphone = function() {
this.keyup(function(e) {
// do not process del, backspace, escape, arrow left and arrow right characters
var k = e.which;
if (k == 8 || k == 46 || k == 27 || k == 37 || k == 39)
return;
// remove invalid characters
var value = "";
for (var i = 0; i < this.value.length; i++) {
var ch = this.value[i];
if (ch >= "0" && ch <= "9")
value += ch;
}
// remove extra characters
if (value.length > 10)
value = value.substring(0, 10);
// insert formatting characters
if (value.length >= 3)
value = "(" + value.substring(0, 3) + ")" + value.substring(3);
if (value.length > 5)
value = value.substring(0, 5) + " " + value.substring(5);
if (value.length > 9)
value = value.substring(0, 9) + "-" + value.substring(9);
// set new value
var $this = this;
var length = value.length;
setTimeout(function() {
$this.value = value;
$this.setSelectionRange(length, length);
}, 0);
});
};
$('#contact_edit_page, #contact_new_page, #callback_create, #callback_edit, #new_phonecall_contact_page, #new_phonecall').live('pagecreate', function() {
$('[type^="tel"]').usphone();
});
}
I just met the same problem. My solution is as follows,
.input {
-webkit-user-modify: read-write;
}
It works in android 4.0.3 in my HTC.

Categories

Resources