I am building a quiz app with questions in a string resource, as well as an answer. They are formatted by numbers like so:
<string name="ques1">What color is the sky?</string>
<string name="ques2">What sound does a cow make?</string>
The answers are also strings corresponding to the same number as the questions:
<string name="ans1">Blue</string>
<string name="ans2">Moo</string>
I have created a QA class for holding both a question and the answer, as well as the user's response from an EditText. At the "loading" of my app these classes are created and filled by reading from the strings resource.
I can programmatically enter these no problem, it is a lot of copy pasting but it will get the job done:
QA.setQuestion(getString(R.string.ques1));
QA.setAnswer(getString(R.string.ans1));
quizList.add(QA);
QA.setQuestion(getString(R.string.ques2));
QA.setAnswer(getString(R.string.ans2));
quizList.add(QA);
etc...
The problem is that I want to be able to add questions and answers to the xml at any time without having to add yet another repetition of the above method. What I want to do is essentially this:
String refBase = "R.string."
String ans = "ans";
String ques = "ques";
int numOfQues = 25; //only change when questions are added or removed
for (int i = 0; i < numOfQues; i++)
{
String referenceQ = refBase + ques + i;
String referenceA = refBase + ans + i;
QA.setQuestion(getString(referenceQ));
QA.setAnswer(getString(referenceA));
quizList.add(QA);
}
I cannot cast a string to an int like this obviously, but I am wondering if there is a way to implement a reference "builder", where I don't have to repeat many lines of code just to read another string with the same name but incremented number.
I understand that I can also just create an array.xml with one for questions and one for answers, making sure their position in each array corresponds. This would be easiest I think, but I guess I am wondering if it is possible to create references to string values through the code like my example?
You can use this method to get the question or answer String by its resource name:
String getQAString(boolean isQuestion, int index) {
String prefix = isQuestion? "ques" : "ans";
int resId = getResources().getIdentifier(prefix + index, "string", getPackageName());
return resId != 0? getString(resId) : "";
}
The loop to add questions and answers (assume they start from 1 and end at 25):
int numOfQues = 25;
for (int i = 1; i <= numOfQues; i++) {
String referenceQ = getQAString(true, i);
String referenceA = getQAString(false, i);
QA.setQuestion(referenceQ);
QA.setAnswer(referenceA);
quizList.add(QA);
}
Related
I am writing an app with Android Studio and I want to split a text into different values.
I have following text in result
*"Name: Peter;Age: 25; City: Chicago"*
I want to get:
*Name = Peter;
Age = 25;
City = Chicago;*
I used the search function and found these solutions: Android Split string but for my problem it seems to be too complicated.
The easiest way is to use split() method.
String s1="Name: Peter;Age: 25; City: Chicago";
String[] words=s1.split(";");
//using java foreach loop to print elements of string array
for(String w:words)
{
Log.i("Words: ", w);
}
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
For example, if I have this string: I love filiberto's!
I need android to edit it to: I love filiberto\'s!
However, each string is going to be different, and there will also be other characters that I have to escape from . How can I do this?
I was wondering how I could programmatically edit strings in android. I am displaying strings from my device to my website, and the apostrophes ruin the PHP output. so in order to fix this, I needed to add character breaks, ie: the backslash '\'.
This is what I have so far, thanks to ANJ for base code...:
if(title.contains("'")) {
int i;
int len = title.length();
char[] temp = new char[len + 1]; //plus one because gotta add new
int k = title.indexOf("'"); //location of apostrophe
for (i = 0; i < k; i++) { //all the letters before the apostrophe
temp[i] = title.charAt(i); //assign letters to array based on index
}
temp[k] = 'L'; // the L is for testing purposes
for (i = k+1; i == len; i++) { //all the letters after apostrophe, to end
temp[i] = title.charAt(i); //finish the original string, same array
}
title = temp.toString(); //output array to string (?)
Log.d("this is", title); //outputs gibberish
}
Which outputs random characters.. not even similar to my starting string. Does anyone know what could be causing this? For example, the string "Lol'ok" turns into >> "%5BC%4042ed0380"
I am assuming you are storing the string somewhere. Lets say the string is: str.
You can use a temporary array to add the '/'. For a single string:
int len = str.length();
char [] temp = new char[len+1]; //Temporary Array
int k = str.indexOf("'"), i; //Finding index of "'"
for(i=0; i<k-1; i++)
{
temp[i] = str.charAt(i); //Copying the string before '
}
temp[k] = '/'; //Placing "/" before '
for(i=k; j<len; j++)
{
temp[i+1] = str.charAt(i); //Copying rest of the string
}
String newstr = temp.toString(); //Converting array to string
You can use the same for multiple strings. Just make it as a function and call it whenever you want.
The String API has a number of API calls that could help, for example String.replaceAll. But...
apostrophes ruin the PHP output
Then fix the PHP code rather than require "clean" input. Best option would be to select a well supported transport format (say JSON or XML) and let the Json API on each end handle escape code.
I am brand new to Java and Android so I am sure this will be an easy question/answer. I know that to find out if a string is equal to another string you use the equal function. In my situation, I am scanning a QR Code where the result of the scan is Similar to "EMPLOYEE~~John Smith~~DIVISION~~Maintenance". I need to know how to do the following:
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
// Do Something
}
In the example Java Code, myJunk[0] never equals val1. What am I doing wrong?
i've tried this and it works , so try to display the contents variable , probably the problem is in the extras , try to display it in logCat :
String contents = "EMPLOYEE~~John Smith~~DIVISION~~Maintenance";
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
String val1 = myJunk[0];
Toast.makeText(this, "val1 = "+val1, Toast.LENGTH_LONG).show();
Toast.makeText(this, "val2 = "+myJunk[1], Toast.LENGTH_LONG).show();
// Now val1 Should be equal to "EMPLOYEE"
if (myJunk[0].equals(val1)){
Toast.makeText(this, "equals", Toast.LENGTH_LONG).show();
}
Your string is:
EMPLOYEE~~John Smith~~DIVISION~~Maintenance
So after spliting, myJunk[0] will contain EMPLOYEE (notice the space in front of the word EMPLOYEE).
So before comparing , you will need to trim your value
The method i usually use, is to print out my variables when in doubt. So if you are unsure of where the problem is, you could try something like this.
(It requires you to be able to see the output, in logcat for example)
String contents = intent.getStringExtra("SCAN_RESULT");
// I know that "contents" contains the string " EMPLOYEE~~John Smith~~DIVISION~~Maintenance"
System.out.println("contents is "+contents );
String[] myJunk = contents.split("~~");
// This should split everything up into an array named myJunk (right)?
System.out.println("Array size is "+myJunk.length);
String val1 = myJunk[0];
// Now val1 Should be equal to "EMPLOYEE"
for(int i=0; i < myJunk.length; i++) {
System.out.println("String "+i+ "in array is: "+myJunk[i]);
}
//Here i run through the array and print every element.
if (myJunk[0].equals(val1)){
// Do Something
}
It is a bit overkill, but this is mostly to show one way of getting all the information you need to find the problem :)
hi to all
i have a couple of text lines where they look like this
You are a friend:
name= [1]
From= [ 2011-02-28 07:00:52]
To= [2011-03-17 07:01:02]
Link= [http://www.example.com]
type= [good] for some
and i want to read only the text that is between the brackets "[]" i would like to know the best way to read it is it by using split(string) or using indexof(string) is better and if there is an example that would be great and also can someone please explane to me how does this code read the text that is between the brackets
thank you
String s = addressString;
int be = s.indexOf('[');
int e = s.indexOf(String[] fields = s.substring(s.indexOf('['), s.indexOf(']'));
i figured out the code i posted it should be like this
String s = addressString;
int be = s.indexOf('[');
int e = s.indexOf(']');
String fields = s.substring(be+1, e);
but now i have another problem which i have more than one line so when i change it to String[] fields it gives me an error so how can i make it to read more than one line i tried a for loop but stil it only reads number 1 that is in between the brackets ...!!!
thank you
You can do it like this:
String lines[] = {"You are a friend:",
"name= [1]",
"From= [ 2011-02-28 07:00:52]",
"To= [2011-03-17 07:01:02]",
"Link= [http://www.example.com]",
"type= [good] for some"};
for (int i = 0; i < lines.length; i++)
{// your previous code, but use lines[i] instead of s }
If the brackets are always at the beginning and end it's probably easier to do something like this:
String s = addressString;
String innerText = s.substring(1,s.length-1);
I need a help with setting a random image using setImageResource method.
In the drawable folder, I have a jpeg file named photo0.jpg, photo1.jpg...photo99.jpg.
And the following code works:
int p = R.drawable.photo1;
image.setImageResource(p);
The above will display photo1.jpg but I want to show a random image.
I tried the following but it doesn't work.
String a = "R.drawable.photo";
int n = (int) (Math.random()*100)
String b = Integer.toString(n);
String c = a+b;
int p = Integer.parseInt(c);//checkpoint
image.setImageResource(p);
It seems like the string "R.drawable.photoXX" isn't being changed to integer at the checkpoint.
Could someone please teach me a right code?
Thank you in advance.
Strings are pretty much evil when it comes to work like this due to the overhead costs. Since Android already provides you with integer id's I would recommend storing all of them to an int array and then using a random number for the index.
The code would look something like this:
int imageArr[] = new int[NUM_IMAGES];
imageArr[1] = R.drawable.photo;
//(load your array here with the resource ids)
int n = (int)Math.random()*NUM_IMAGES;
image.setImage(imageArr[n]);
Here we have a pretty straight forward implementation and bypass all the creation and destruction that occurs with the string concats.
maybe the error is here
int n = (int) (Math.random()*100)
put % not * Like this
int n = (int) (Math.random()%100)
to get all numbers under 100