Arraylist - how to? - android

So I have this array List:
private ArrayList<String> output;
Which look like this normally once items are added looks like this:
["ready", "30 min", "5.2 mi", "stop"]
But sometimes the order can change on how the information comes in for example:
["30 min", "stop", "5.2 mi", "ready"]
What would be the best solution to get the number that is in front of mi and min since the ArrayList can change I can't use list.get(1) for example cause the index might be something different.
I have tried to use list.getIndexOf("mi"); but that didn't work, kept coming back as -1 which I would think cause it wasn't an exact match.

Use this .. to get no before "mi"
for(int i =0; i<list.size();i++)
{
if(list.get(i).contains("mi"))
{
String[] splitT =
list.get(i).split(" ");
System.out
.println("before mi is" + splitT[0]);}
}
Note splitT[0] is the answer what you want.. like this you can find for "min" too..

If I understood your question correctly, you want to get an element whith a certain pattern to further work with that information. In that case you could loop through the ArrayList and check for element whether or not it matches a certain regexp. Something like this:
for (String s : arraylist) {
if (s.matches("[0-9]+ mi(n)?")) //would match any number, followed by a whitespace and mi/min {
//do something
}
}

You can do something likes this.
for (String item:list){
if (item.contains("mi")&&!item.contains("min")){
Log.d("item",item.substring(0,3));
}
}
You can do similarly for "min".

You can use this code:
for (int i=0 ; i<output.size() ; i++){
if (output.get(i).endsWith("mi")) // index i contains "mi"
else if (output.get(i).endsWith("min")) //index i contains min not mi
}

Related

Search for number in array, Android

I'm searching for numbers in my app, but it does not work, where is the problem please ?!
numrat is int[] and fint is a number from fytyratint[]...
int fint = fytyratint[nrRendor];
int nse = Arrays.binarySearch(numrat, fint);
if (nse <0 ){
pS++;
tvS.setText("Sakt: "+ Integer.toString(pS));
}
else
{
pG++;
tvG.setText("Gabimet: " + Integer.toString(pG));
}
So nse must be negative if number does not exist in int[] numrat and must be positive if fint exists on int[] numrat..
This is what I read on internet..
but in my example it is always negative.. ??!!
If you want Arrays.binarySearch() to work you should sort your array like written here:
binarySearch() ...
Performs a binary search for value in the ascending sorted array
array. Searching in an unsorted array has an undefined result. It's
also undefined which element is found if there are multiple
occurrences of the same element.
You may do it like this:
Arrays.sort(numrat);
Arrays.binarySearch(numrat, fint);

Most efficient way of comparing long arrays of strings

I'm using the speech recognizer to get a voice input from the user, it returns an array of 5 strings which I pass to this method
public int analyzeTag(ArrayList<String> voiceResults,Editor editor, Context context){
for (String match : voiceResults) {
Log.d(TAG, match);
if (match.equalsIgnoreCase(context.getResources().getString(R.string.first_tag))){
editor.append(context.getResources().getString(R.string.first_tag));
return 1;
}
else if (match.equalsIgnoreCase(context.getResources().getString(R.string.second_tag))){
editor.append(context.getResources().getString(R.string.second_tag));
return 1;
}
//etc....(huge list of tags)
//Some tags might also have acceptable variations, example:
else if (match.equalsIgnoreCase("img") || match.equalsIgnoreCase("image")
{
editor.append("img"); //the string to append is always taken from the first variation
}
}
return 0;
}
This method compares the results with a list of tags, the tag list will be pretty big with hundreds of tags so I would like to find the most efficient way to do this operation.
I need help with:
1.Is my way of comparing results the most efficient? Is there a better way? (from the user experience perspective, I don't want users waiting a long time to get a result).
The voice input will be a big part of my app so this method will be called quite often
2.I have a long list of tags, obviously the if(), elseIf() route is gonna be quite repetitive, is there a way to iterate this? Considering the fact that some tags might have variations (even more than 1)and that the variation 1 ("img") will be the same for everyone, but other variations will be locale/language sensitive example: "image" for english users "immagini" for italian users etc.
Text appended to the editor will be always taken from the first variation
How about puting tags in a StringArray and then iterate though the array ?
String[] tags = context.getResources().getStringArray(R.array.tags);
for (String match : voiceResults) {
for (int index = 0; index < tags.length; index++ ) {
if (match.equalsIgnoreCase(tags[index]) {
editor.append(tags[index]);
}
}
}
Here's the doc on StringArray

Separating the words after the last integer in a large String

I've seen many people do similar to this in order to get the last word of a String:
String test = "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);
I would like to do similar but get the last few words after the last int, it can't be hard coded as the number could be anything and the amount of words after the last int could also be unlimited. I'm wondering whether there is a simple way to do this as I want to avoid using Patterns and Matchers again due to using them earlier on in this method to receive a similar effect.
Thanks in advance.
I would like to get the last few words after the last int.... as the number could be anything and the amount of words after the last int could also be unlimited.
Here's a possible suggestion. Using Array#split
String str = "This is 1 and 2 and 3 some more words .... foo bar baz";
String[] parts = str.split("\\d+(?!.*\\d)\\s+");
And now parts[1] holds all words after the last number in the string.
some more words .... foo bar baz
What about this one:
String test = "a string with a large number 1312398741 and some words";
String[] parts = test.split();
for (int i = 1; i < parts.length; i++)
{
try
{
Integer.parseInt(parts[i])
}
catch (Exception e)
{
// this part is not a number, so lets go on...
continue;
}
// when parsing succeeds, the number was reached and continue has
// not been called. Everything behind 'i' is what you are looking for
// DO YOUR STUFF with parts[i+1] to parts[parts.length] here
}

Parse a string and get certain values

I have a string like this:
_id:2 thread_id:189 address:0292 m_size:null person:0 date:1372494272447 date_sent:0 protocol:0 read:1 status:-1 type:1 reply_path_present:0 subject:null body:Ok. Reply message. service_center:051108 locked:0 sim_id:0 error_code:0 seen:1 _id:1 thread_id:189 address:292 m_size:null person:0 date:1372493695831 date_sent:0 protocol:null read:1 status:-1 type:2 reply_path_present:null subject:null body:Test message service_center:null locked:0 sim_id:0 error_code:0 seen:0
I want to retrieve only parts of this string, for example the address:0292 and the body:xyz from the entire string. I want all instances of these two from a very large String (above is just a sample). Let's assume its more than 20000 characters.
How can I achieve this?
Looks like every address is followed by m_size, so use the string.split() function, to split over the keyword address then select the string.substring() (from each string in the resulting array) until reaching the keyword m_size. And repeat the entire thing for the keywords body and service_center. I can't think of any other way.
You are right, it doesn't seem pretty. But it works :)
String[] splitString = string.split(" ");
for (int i = 0; i < splitString.length; i++) {
if (splitString[i].startsWith("body") || splitString[i].startsWith("address"))
Log.i(TAG, "Found: " + splitString[i]);
// Do whatever you need to do
}

Removing newline from string

Here's my issue:
I have a database and it is full of episodes of a tv show. One column denotes the episode number. I want to display the episodes in a list like this:
Episode 1
Episode 2
Episode 3
etc.
I'm using my own adapter class that extends SimpleCursorAdapter to do this...
Since I had formatting errors I am using Android.R.layout.simple_list_item_1 and Android.R.id.text1
Basically the only reason I have a custom adapter is so I can do something like this:
textView.setText("Episode " + cursor.getString("column_for_episode_number");
The problem is, I get a list that looks like this:
Episode
1
Episode
2
Episode
3
When I try something like this(which worked in a different portion of my code):
String text = "Episode " + cursor.getString("blah");
text = text.replaceAll("\\n","");
I get the exact same list output :(
Why don't I use create a custom view with two textboxes next to each other? It is hard for me to get that to look pretty :/
text.replaceAll(System.getProperty("line.separator"), "");
There is a mistake in your code. Use "\n" instead of "\\n"
String myString = "a string\n with new line"
myString = myString.replaceAll("\n","");
Log.d("myString",myString);
Check if there is new line at the beginning before you replace and do the same test again:
for(int i=0; cursor.getString("blah").length()-1; i++)
{
if(cursor.getString("blah").charAt(i)=='\\n') <-- use the constant for the line separator
{
Log.i("NEW LINE?", "YES, WE HAVE");
}
}
Or use the .contains("\n"); method:
Check the xml for the width of the textview as well.
Why are you using getString() when you are fetching an integer? Use getInt() and then use Integer.toString(theint) when you are setting the values in a textview.
This could help you:
response = response.replaceAll("\\s+","");
It sounds like you are hitting wrapping issues rather than newline issues. Change this:
String text = "Episode " + cursor.getString("blah");
To this:
String text = "Episode" + cursor.getString("blah");
And see if that changes the output. Post your layout xml please?
this worked for my (on android 4.4):
(where body is a string with a newline entered from an EditText view on handset)
for (int i=0; i<body.length(); i++) {
if (body.charAt(i) == '\n' || body.charAt(i) == '\t') {
body = body.substring(0, i) + " " + body.substring(i+1, body.length());
}
}
have you tried
cursor.getString("blah").trim()

Categories

Resources