i have some problems extracting strings
i am making a multiple choice with 4 choices (e.g. as buttons), with the choices by referencing to the filename. The file (i.e. the question) is a png and the filename is Number-Q01AZ7BZ8CZ9DZ10ANZ8.png. These png are put under assets folder.
Set<String> regions = regionsMap.keySet(); // get Set of regions
// loop through each region
for (String region : regions)
{
if (regionsMap.get(region)) // if region is enabled
{
// get a list of all flag image files in this region
String[] paths = assets.list(region);
for (String path : paths)
fileNameList.add(path.replace(".png", ""));
} // end if
} // end for
String fileName = fileNameList.get(randomIndex);
if (!quizCountriesList.contains(fileName))
{
quizCountriesList.add(fileName); // add the file to the list
String nextImageName = quizCountriesList.remove(0);
correctAnswer = nextImageName; // update the correct answer
int AZ = correctAnswer.indexOf("AZ");
int BZ = correctAnswer.indexOf("BZ");
int CZ = correctAnswer.indexOf("CZ");
int DZ = correctAnswer.indexOf("DZ");
int ANZ = correctAnswer.indexOf("ANZ");
String choiceA = null;
String choiceB = null;
String choiceC = null;
String choiceD = null;
choiceA = correctAnswer.substring( (AZ+2), (BZ) );
choiceB = correctAnswer.substring( (BZ+2), (CZ) );
choiceC = correctAnswer.substring( (CZ+2), (DZ) );
choiceD = correctAnswer.substring( (DZ+2), (ANZ) );
The logcat is as follows:
11-09 21:14:08.495: E/AndroidRuntime(25905): FATAL EXCEPTION: main
11-09 21:14:08.495: E/AndroidRuntime(25905): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.trial.quizgame/com.trial.quizgame.QuizGame}: java.lang.StringIndexOutOfBoundsException: length=15; regionStart=1; regionLength=-2
11-09 21:14:08.495: E/AndroidRuntime(25905): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1967)
I have tried to set the buttons as .setText(correctAnswer) and it will correctly show as Number-Q01AZ7BZ8CZ9DZ10ANZ8, so the top part of getting the String for "correctAnswer" should be ok. The problem left at extracting strings, yet BZ must be at a position behind AZ, so as CZ behind BZ, etc:
From the logcat the regionLength is -2? How could I handle this?
I would like it to be for Q01, choice A=7, B=8, C=9, D=10 and ANZ=8
thanks in advance for your advice!
Your assumption on the strings value is wrong. This code, if AZ, BZ, CZ, DZ, ANZ is present, should run with no error.
Either run debugger as advised in comments, or use android logcat to provide some debugging context. android.utils.Log.d("APP", String.format("AZ=%d", AZ));
How you store your data is not a big deal. You can tune it for days... You could create xml files that contain the name of the image, and the four possible answers... You can use the underscore approach, you can stay with your current one. Til it is only used by you, it doesn't really matter. You should just keep it simple. More complex => more chance for bugs...
So I'd advise reading about debugging and logging instead of refining the way you store the information... Storing it in the filename, that's a smart idea, quick and efficient, an ideal hack...
Related
My program reads data from socket and now I want to display that data in a textbox. I splitted the data into seperate variables and here is my code:
final int aData = 0;
final int aData = 0;
final int cData = 0;
final String[] separated = data.split(":");
if ((separated.length == 3) && (data.contains(":")))
{
aData = Integer.parseInt(separated[0]);
bData = Integer.parseInt(separated[1]);
cData = Integer.parseInt(separated[2]);
}
handler.post(new Runnable() {
public void run() {
txtDebug.setText("a: "+aData + " b: "+bData + " c: " + cData);
}
});
it doesn't allow me to run the program and shows me following error:
"The final local variable aData cannot be assigned. It must be blank and not using a compound assignment". Any help to solve the problem would be highly appreciated.
You're assigning aData twice. I assume you meant to have aData, bData and cData but you have two lots of aData and one cData.
Besides that problem, you also assign 0 to each of these variables when you declare them. You then try to assign new values in the if block. You can only assign to a final variable once.
The final reserved work means that your variable might be initialized/assigned just once. Since you're assigning final int aData = 0;, it means it won't be able to assign it again. This has its benefits (for instance, if you're sure you just want your variable be assigned for once, you should declare it as final - even this will help a little to the compiler), but its for sure a behavior you're not looking for. Simply remove final from your variables.
Since you have used the keyword 'final' on the variables aData, bData and cData, they can no longer be reassigned new values elsewhere within the program. They take the value 0 and remain that way. Remove the modifier 'final' if you want to change them.
I am writing an android app which requires me to process a very large file(say 50MB). The file contains three entries-A userid, artistid and the number of times the user has listened to that artist. So now I write the code to find out who the most popular artist is based on the number of times the artist has been heard. I achieve this by hashmapping each of the artist id(key) and then the number of times he's been heard (value).
The code works fine as long as the file is below 20B (I run the app on Nexus S 4g, so the heap is 32MB), but I get an 'Out of memory' error for larger files. I realize the code is very badly written. Any suggestions as to how I could get through this problem!
while ((text = inRd.readLine()) != null) {
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens()) {
int userid = Integer.parseInt(st.nextToken());
artistid = Integer.parseInt(st.nextToken());
int no_times = Integer.parseInt(st.nextToken());
if (hm.containsKey(artistid)) {
Integer oldval = (Integer) hm.get(artistid);
Integer newval = no_times + oldval;
hm.remove(artistid);
hm.put(artistid, newval);
} else
hm.put(artistid, no_times);
}
}
A hashmapping is not the most efficient way to store things. Try a Vector or straight arrays.
Hope this Helps
Cliff
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 :)
I want to work dynamically therefore I want to bind text views dynamically I think an example would explain me the best
assuming I want to bind 7 image views i can do it like this :
Country = (EditText)findViewById(R.id.CountryEditText);
City = (EditText)findViewById(R.id.CityEditText);
LivinigCreture = (EditText)findViewById(R.id.LivingCretureE);
Nature =(EditText)findViewById(R.id.NatureEditText);
Inanimate = (EditText)findViewById(R.id.InanimateEditText);
KnowenPersonality = (EditText)findViewById(R.id.KnowenPersonalityEditText);
Occupation = (EditText)findViewById(R.id.OccupationEditText);
but lets change 7 with NUMOFFILEDS as a final where i want to do the previous ?
myImages = new ImageView [7];
for (int i = 0; i<7;i++,????)
myImages[i] = (ImageView)findViewById(R.id.initialImageView01);
notice : in my R file the R.id.initialImageView01 - R.id.initialImageView07 are not generate in a cont gap between them therefore I don't know how to make this architecture possible .
and if there's a way can someone show me an example how to work dynmiclly (like using jsp on android combined way or something ?)
id its possiable to do so constant times is it possible to build an the same xml constant num of times like jsp does
thank u pep:)
You can store the IDs themselves in an array at the beginning of your Activity; that way you'll only need to write them once and you can index them afterwards.
Something like:
int[] initialImageViewIds = {
R.id.CountryEditText,
R.id.CityEditText,
R.id.LivingCretureE,
R.id.NatureEditText,
R.id.InanimateEditText,
R.id.KnowenPersonalityEditText,
R.id.OccupationEditText
};
Then you can access them with:
myImages = new ImageView [7];
for (int i = 0; i<7;i++) {
myImages[i] = (ImageView)findViewById(initialImageViewIds[i]);
}
If that's not enough and you really want to get the IDs dynamically, I suppose you can use reflection on the R.id class, possibly with something like R.id.getClass().getFields() and iterate on the fields to check if their names interest you. Check reference for the Class class, too.
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