Comparing string array with string and posting my result to main.xlm - android

I am having trouble with understanding how to compare strings in Java for Android. I have written code to do this in JavaScript and Palm but am new to Java and am a little confused. Case in point, I am trying to modify the example on the Android Developers site for SpinnerActivity (http://developer.android.com/resources/samples/Spinner/src/com/android/example/spinner/SpinnerActivity.html). In my application I am looking at pipe sizes in the spinner not planets. When the user picks a pipe size I want to reference an array of pipe sizes and be able to pick other parameters associated with that pipe size like the outside diameter (OD) of the pipe. I have modified the above sample code and added and array for the pipe sizes and the OD sizes. I then try to compare what the user picked in the pipe sizes spinner with my pipe sizes array and use the number of the array that matches to pick the associated OD. There is something wrong with the way I am trying to make this comparision. I set both of these values as stings but they never seem to find one another.
HelloSpinner1.java section I have changed is:
public void onItemSelected(AdapterView<?> parent, View v, int pos, long row) {
HelloSpinner1.this.mPos = pos;
HelloSpinner1.this.mSelection = parent.getItemAtPosition(pos).toString();
/*
* Set the value of the text field in the UI
*/
TextView resultText = (TextView)findViewById(R.id.SpinnerResult);
resultText.setText(HelloSpinner1.this.mSelection);
String[] OD; // array of pipe ODs
OD = new String[30]; // allocates memory for 30 floating point numbers
OD[0] = "0.405";
OD[1] = "0.540";
OD[2] = "0.675";
OD[3] = "0.840";
OD[4] = "1.050";
OD[5] = "1.315";
OD[6] = "1.660";
OD[7] = "1.9";
OD[8] = "2.375";
OD[9] = "2.875";
OD[10] = "3.5";
OD[11] = "4";
OD[12] = "4.5";
OD[13] = "5.563";
OD[14] = "6.625";
OD[15] = "8.625";
OD[16] = "10.750";
OD[17] = "12.75";
OD[18] = "14";
OD[19] = "16";
OD[20] = "18";
OD[21] = "20";
OD[22] = "22";
OD[23] = "24";
OD[24] = "26";
OD[25] = "28";
OD[26] = "30";
OD[27] = "32";
OD[28] = "34";
OD[29] = "36";
String [] Size;
Size = new String [30];
Size[0] = "1/8";
Size[1] = "1/4";
Size[2] = "3/8";
Size[3] = "1/2";
Size[4] = "3/4";
Size[5] = "1";
Size[6] = "1-1/4";
Size[7] = "1-1/2";
Size[8] = "2";
Size[9] = "2-1/2";
Size[10] = "3";
Size[11] = "3-1/2";
Size[12] = "4";
Size[13] = "5";
Size[14] = "6";
Size[15] = "8";
Size[16] = "10";
Size[17] = "12";
Size[18] = "14";
Size[19] = "16";
Size[20] = "18";
Size[21] = "20";
Size[22] = "22";
Size[23] = "24";
Size[24] = "26";
Size[25] = "28";
Size[26] = "30";
Size[27] = "32";
Size[28] = "34";
Size[29] = "36";
String ODSize;
for (int i = 0; i <= 29; i++){
if (Size.equals("HelloSpinner1.this.mSelection")) {
ODSize = OD[i];
break;
}
}
}
The associated strings.xml rorm the android site with slight modifications is:
Pipe and Tube
1/8
1/4
3/8
3/4
1
1-1/4
1-1/2
2
2-1/2
3
3-1/2
4
5
6
8
10
12
14
16
18
20
22
24
26
28
30
32
34
36
Select a Pipe Size

Just a quick note, but I see two things here:
1) You have "HelloSpinner1.this.mSelection" in quotes. Inside .equals, that is comparing your variable Size directly to that string ... not the value stored in that object. For example, you're asking: "1/8" ?= "HelloSpinner1.this.mSelection" ... not, "1/8" ?= "1/4" in this case. That might be most of your problem here.
2) You could just use the position of the spinner inside your Listener method. That gives you the position of the selection on the spinner. If you aren't modifying those values, you would already know the index into your array. If you were modifying them, /then/ you could do a string comparison (or concurrently modify your array to keep them up to date).
You might also want to check what you're comparing against once you eliminate the quotes problem. A very simple way to do that would be to declare a String for each value, then run it in the debugger or log the output.
Lastly, as personal preference, I don't like to store long arrays which aren't going to change in the xml file. Just code that up as an array which doesn't have to be interpreted later. That'll give you the array access directly, and speed up execution some.

Related

Jsoup.parse takes 10x more time on 19+ android devices

For some reason using Jsoup.parse takes 10x more time on kitkat devices than on older devices, at first I thought it was related to ART runtime, but changing back to dalvik didn't help
Here is the code I'm using:
downloadedHtml = NetworkHelper.downloadString("https://en.m.wikipedia.org/wiki/Dusseldorf");
AppLog.i("Downloaded data, Jsoup is parsing the html");
hDoc = Jsoup.parse(downloadedHtml);
Element htmlElement = hDoc.select("html").first();
String langCode = htmlElement.attributes().get("lang");
ArticleInfo articleInfo = new ArticleInfo(getWikiLanguage(langCode), langCode, href);
article = new Article(articleInfo, href);
String title = hDoc.getElementById("section_0").text();
article.set_title(title);
Document documentNode = hDoc.ownerDocument();
Elements contents = documentNode.getElementsByClass("content");
if (contents == null || contents.isEmpty())
throw new IllegalArgumentException("content");
Element content = contents.first();
Elements imgElements = content.select("img");
Element htmlNode;
for (int i = 0; i < imgElements.size(); i++)
{
htmlNode = imgElements.get(i);
if (!htmlNode.hasAttr("src"))
continue;
String src = htmlNode.attr("src");
if (src.startsWith("//"))
htmlNode.attr("src", String.format("http:%s", src));
//else
//throw new UnsupportedOperationException();
}
//get section headings
Elements headlines = documentNode.getElementsByClass("mw-headline");
if (headlines != null)
{
Element headline;
for (int i = 0; i < headlines.size(); i++)
{
headline = headlines.get(i);
String headline_link = headline.id();
String headline_title = headline.text();
SectionHeadline sectionHeadline = new SectionHeadline(headline_title, headline_link);
article.get_sectionHeadlines().add(sectionHeadline);
}
}
article.set_html(content.outerHtml());
//get languages
//language list
Element languageSection = content.getElementById("mw-mf-language-section");
if (languageSection != null)
{
Elements languageLinks = languageSection.select("li");
Element languageLink;
for (int i = 0; i < languageLinks.size(); i++)
{
languageLink = languageLinks.get(i);
Element link = null;
Elements ls = languageLink.select("a");
if (ls == null || ls.size() == 0)
continue;
link = ls.first();
if (!link.hasAttr("href"))
continue;
String linkHref = link.attr("href");
if (linkHref != null && link.text() != null)
{
String languageCode = link.attr("lang");
if (linkHref.startsWith("//"))
linkHref = String.format("http:%s", linkHref);
ArticleInfo languageInfo = new ArticleInfo(getWikiLanguage(languageCode), languageCode, linkHref);
if (languageInfo.get_language() == "Unknown")
continue;
article.get_languages().add(languageInfo);
}
}
}
Any ideas what the problem may be?
The code in the question selects a portion of the document, saves it to a variable, selects a portion of that variable, saves it to a new variable, and so on. Another possible implementation is to use the selector syntax more heavily to select only the elements which are needed, and not save these intermediate steps in new objects.
The code below executed on my machine in 2 seconds. A similar excerpt from above executed in about 4 seconds. Subsequent timings were much closer, differing by approximately 50ms, so take that with a grain of salt.
I don't know if there is a performance issue in kitkat. You may find it helpful to add timers to your kitkat and dalvik versions to isolate if and where performance bottlenecks are present.
Here's my code:
long start = System.currentTimeMillis();
Document hDoc = Jsoup.
connect("https://en.m.wikipedia.org/wiki/Dusseldorf").
userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.57 Safari/537.17").
get();
//select the first html element, then take the value of the lang attribute
String langCode = hDoc.select("html:eq(0)").attr("lang");
String title = hDoc.getElementById("section_0").text();
Document documentNode = hDoc.ownerDocument();
//select all the image elements having the attribute src which are
//descended from the first element with the content class
Elements imgElementsHavingSrcAttr = documentNode.select("*.content:eq(0) img[src]");
Element htmlNode;
//for each img element
for (Element img : imgElementsHavingSrcAttr)
{
htmlNode = img;
String src = img.attr("src");
if (src.startsWith("//"))
{
htmlNode.attr("src", String.format("http:%s", src));
}
}
System.out.println("Function took " + (System.currentTimeMillis()-start) + "ms");

Android - moving char array value to same char array

how am I going to move the value of a char array to the same char array? Here's a code:
Assuming ctr_r1=1 ,
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++)
{
letters[ctr_x] = letters[ctr_x];
}
sb.append(letters);
char[] lettersr1 = sb.toString().toCharArray();
sb1.append(lettersr1);
append the "letters", then convert it to string, then convert it to char array then make it as "lettersr1" value.
what im trying to accomplish is given the word EUCHARIST, i need to take the word HARIST out and place it on another array and call it region 1 (Porter2 stemming algorithm).
The code "ctr_X = (ctr_r1 + 2)" starts with H until T. The problem is I cannot pass the value directly that's why i'm trying to update the existing char array then append it.
I tried doing this:
char[] lettersr1 = null;
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++)
{
lettersr1[ctr_x] = letters[ctr_x];
}
sb.append(lettersr1);
but my app crashes when i do that. Any help please. Thanks!
I don't understand what you're trying to do, but I can comment on your code:
letters[ctr_x] = letters[ctr_x];
This is a noop: it sets an array element value to the value it already has.
char[] lettersr1 = null;
for(int ctr_x = (ctr_r1 + 2) ; ctr_x < letters.length - 2 ; ctr_x++) {
lettersr1[ctr_x] = letters[ctr_x];
This obviously causes a NullPointerException, since you're trying to access an array which is null. You must initialize the array before being able to modify it:
char[] lettersr1 = new char[someLength];
Additional note: you should choose better names for your variables. The names should tell what the variable represents, and they should respect the Java naming conventions (no underscores in variable names, camelCase). ctr_x, ctr_r1 and lettersr1 don't mean anything.
EDIT:
I'm still not sure what you want to do, and why you don't simply use substring(), but here's how to transform EUCHARIST to HARIST:
char[] eucharist = "EUCHARIST".toCharArray();
char[] harist = new char[6];
System.arraycopy(eucharist, 3, harist, 0, 6);
String haristAsString = new String(harist);
System.out.println(haristAsString);
// or
char[] harist2 = new char[6];
for (int i = 0; i < 6; i++) {
harist2[i] = eucharist[i + 3];
}
String harist2AsString = new String(harist2);
System.out.println(harist2AsString);
// or
String harist3AsString = "EUCHARIST".substring(3);
char[] harist3 = harist3AsString.toCharArray();
System.out.println(harist3AsString);
May be so:
String str = "EUCHARIST";
str = str.substring(3);
and after toCharArray() or smth another

\n (Newline) deleting Android

There was some XML parsed text that looked like this:
06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href="..."> ... <br>15:45 Something..
and there was a lot of it..
Well, I have done this:
String mim =ses.replaceAll("(?s)\\<.*?\\>", " \n");
there was no other way to show text nicely.
Now, after few showings, and some time, I need that same text separated into alone strings like this:
06:00 Vesti
... or
07:15 Something Else
I've tried something like this, but it does not work:
char[] rast = description.toCharArray();
int brojac = 0;
for(int q=0; q<description.length(); q++){
if(rast[q]=='\\' && rast[q+1]=='n' ) brojac++;
}
String[] niz = new String[brojac];
int bf1=0;
int bf2=0;
int bf3=0;
int oo=0;
for(int q=0; q<description.length(); q++){
if(rast[q]=='\\'&& rast[q+1]=='n'){
bf3=bf1;
bf1=q;
String lol = description.substring(bf3, bf1);
niz[oo]=lol;
oo++;
}
}
I know that in description.substring(bf3,bf1) are not set as they should be but I think that this:
if(rast[q]=='\\' && rast[q+1]=='n)
does not work that way.. is there any other solution?
Note. there is no other way to get that resource. , It must be through this.
Calling Html.fromHtml(String) will properly translate the <br> into \n.
String html = "06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href=\"...\"> ... <br>15:45 Something..";
String str = Html.fromHtml(html).toString();
String[] arr = str.split("\n");
Then, just split it on a line basis - no need for regexps (which you shouldn't be using to parse HTML in the first case).
Edit: Turning everything into a bunch of Dates
// Used to find the HH:mm, in case the input is wonky
Pattern p = Pattern.compile("([0-2][0-9]:[0-5][0-9])");
SimpleDateFormat fmt = new SimpleDateFormat("HH:mm");
SortedMap<Date, String> programs = new TreeMap<Date, String>();
for (String row : arr) {
Matcher m = p.matcher(row);
if (m.find()) {
// We found a time in this row
ParsePosition pp = new ParsePosition(m.start(0));
Date when = fmt.parse(row, pp);
String title = row.substring(pp.getIndex()).trim();
programs.put(when, title);
}
}
// Now programs contain the sorted list of programs. Unfortunately, since
// SimpleDateFormat is stupid, they're all placed back in 1970 :-D.
// This would give you an ordered printout of all programs *AFTER* 08:00
Date filter = fmt.parse("08:00");
SortedMap<Date, String> after0800 = programs.tailMap(filter);
// Since this is a SortedMap, after0800.values() will return the program names in order.
// You can also iterate over each entry like so:
for (Map.Entry<Date,String> program : after0800.entrySet()) {
// You can use the SimpleDateFormat to pretty-print the HH:mm again.
System.out.println("When:" + fmt.format(program.getKey()));
System.out.println("Title:" + program.getValue());
}
Use regex:
List<String> results = new ArrayList<String>();
Pattern pattern = Pattern.compile("(\d+:\d+ \w+)<?");
Matcher matcher = pattern.matcher("06:00 Vesti<br>07:15 Something Else<br>09:10 Movie<a href="..."> ... <br>15:45 Something..");
while(matcher.find()) {
results.add(matcher.group(0));
}
results will end up as a list of strings:
results = List[
"06:00 Vesti",
"07:15 Something Else",
"09:10 Movie",
"15:45 Something.."]
See Rexgex Java Tutorial for an idea of how javas regex library works.

Array access producing unwanted result

I am getting an unusual result when attempting to place a value in an array.
I have an array table[] of a simple class result{ int score, long time, string ID}
Intention is to have a sort of leader board.
My code happily finds the correct place to insert a new score if it is in the top 10.
int ix = 0;
int jx = 10; //
while ( ix < jx )
{
if (points > sTable[ix].points)
{
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
}
ix++;
}
Problem is that when I try to insert the score using sTable[ix].score = score;
The value gets written to sTable[ix].score and also sTable[ix +1].score.
It is repeatable, it occurs at any value of ix, I have single stepped through the code and as far as I can tell the command only executes once.
Has anyone seen this before?
That because you copied the object reference to the next element in the array. You should copy the values, or create a new object:
Option A:
// score is higher move records down
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx].time = sTable[jx -1].time;
sTable[jx].score = sTable[jx -1].score;
}
//now add new score
sTable[ix].score = score; // all good until here
sTable[ix].time = time;
Option B:
for (jx = mNumRecords - 1; jx >ix ; jx--)
{
sTable[jx] = sTable[jx -1];
}
sTable[ix] = new Result(score, time, ""); // Or however you construct the object

Array Being Overwritten with Last Index in Loop

I'm working on code that takes two arrays with strings (the strings are just sentences) and allocates them to classes which are held in another array (The Sentence class array shown below in the code).
So here's my problem. When popList() is called, the for loop runs through twice and works fine, putting the first index of addStrings and addTranslation into the first class in the array. However, when the loop indexes up and runs temp.sentence = addStrings[1] again, it OVERRIDES the first class's .sentence also. Then when temp.translations = addTranslations[1] runs again it OVERRIDES the first class's .translation.
So by the end of the loop, all of the arrays are filled with the same thing: the last index of addStrings and addTranslation. Every time it loops it overwrites all the indices before it with the index it's supposed to be putting in.
Anyone know what the problem is here? Thanks!
public class Sentence {
public String sentence;
public String translation;
Sentence() {
sentence = " ";
translation = " ";
}
}
private void popStrings() {
addStrings[0] = "我是你的朋友。"; addTranslations[0] = "I am your friend.";
addStrings[1] = "你可以帮助我吗?"; addTranslations[1] = "Could you help me?";
addStrings[2] = "我不想吃啊!"; addTranslations[2] = "I don't want to eat!";
}
//Fill Sentence array with string and translation arrays
private void popList() {
int i = 0;
Sentence temp = new Sentence();
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
}
You need to create new Sentence() inside the loop:
for(i = 0; i < addStrings.length && i < addTranslations.length ; i++) {
Sentence temp = new Sentence();
temp.sentence = addStrings[i];
temp.translation = addTranslations[i];
sentences[i] = temp;
}
Otherwise you set sentence and translation continuously in the same object.

Categories

Resources