Android arraylist.get getting the wrong value using an index - android

I'm at my wit's end with this one! Here's some of my code:
ArrayList<Integer> score = new ArrayList<Integer>();
ArrayList<Integer> indices;
int total = 10;
for(int c = 0; c < total; ++c)
{
score.add(c);
}
indices = new ArrayList<Integer>(total);
for(int c = 0; c < total; ++c)
{
indices.add(c);
}
Collections.shuffle(indices);
rando1 = indices.get(0);
int currentScore;
currentScore = score.get(indices.get(rando1));
Toast.makeText(getApplicationContext(),
"score location should be: " + rando1, Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(),
"score location is: " + currentScore, Toast.LENGTH_SHORT).show();
The toasts were to help me see what's going on. For some reason, no matter what I try, the rando1 and the currentScore will almost always be different numbers.
This is baffling me because I use rando1 on a number of other arrays (string arrays), and it always gets the correct items from the other arrays.
My question is why doesn't this get the same index item (the integer at whatever index) from the integer array as it does from the other string arrays. I've tried isolating just this code. I've tried changing various things. I've done a lot of testing. And the searches don't turn up anything too specific (but I've tried what I found there as well).
Desired output of the toasts: "score location should be: 3", "score location is: 3"
Actual output: "score location should be: 3", "score location is: 5" (replace 5 with any other number, because there's never a set pattern between what it should be and what it is).

Use the following code to get a random element ArrayList.
Random r = new Random();
currentScore = score.get(r.nextInt(score.size()))
If you want to the output, as you have, then change the following line:
currentScore = score.get(rando1);

Related

Generate Unique Random Numbers with Range

I am beginner in android.
display random numbers of images, kids have to count number images
for answer generate 4 random choice, code is working fine
but sometimes app get hanged, can't optimize code.
Generate Answer
int[] answer = new int[4];
int count=0,random_integer;
while(count<=3){
random_integer = r.nextInt((imageCount+2) - (imageCount-2)) + (imageCount-2);
if(!exists(random_integer,answer)){
answer[count] = random_integer;
Log.d("answer","Array " + count + " = " + random_integer);
count++;
}
}
if(!exists(imageCount,answer)){
answer[r.nextInt(3 - 0) + 0] = imageCount;
}
Check Duplicate
public boolean exists(int number, int[] array) {
if (number == -1)
return true;
for (int i=0; i<array.length; i++) {
if (number == array[i])
return true;
}
return false;
}
Logcat
While generating 4 value it stopped
Thanks in advance
The answer array is initialized with zeroes. This means, a random_integer of 0 will not be accepted by the exists check.
In the case that imageCount is 2, the only four possible random answers are 0, 1, 2, 3. Since 0 is not accepted, the while loop will never terminate.
A similar problem appears if imageCount is smaller than 2.

Android: Count strings and drawables

I'm circulating some drawable images (fx. I have a few images named image_1, image_2 etc.) as header images in a fragment. The images are loaded randomly as I hardcode the number of images available for me, and generate a random index from 0 to this number.
mHeaderBackgroundImagesCount is a final:
private int getHeaderBackground() {
// Random index between 0 and mHeaderBackgroundImagesCount
Random rand = new Random();
int index = rand.nextInt(mHeaderBackgroundImagesCount) + 1;
return getResources()
.getIdentifier("image_" + index, "drawable", getPackageName());
}
As hard coding anything isn't normally the way to go in correct programming, I therefore like to dynamically find out how many 'image_X' drawables I have and set it to mHeaderBackgroundImagesCount.
I would like to do the same with strings from the strings.xml resource file as I'm also circulating some strings on every page load.
Solution Update
This update is inspired by Lalit Poptani's suggestion below. It includes syntax corrections and optimizations and have been tested to work.
private int countResources(String prefix, String type) {
long id = -1;
int count = -1;
while (id != 0) {
count++;
id = getResources().getIdentifier(prefix + (count + 1),
type, getPackageName());
}
return count;
}
System.out.println("Drawables counted: " + countResources("image_", "drawable"));
System.out.println("Strings counted: " + countResources("strTitle_", "string"));
Note: This method assumes that the resources counted start with index 1 and have no index holes like image_1 image_2 <hole> image_4 etc. because it will terminate on first occasion of id=0 thus resulting a faulty count.
If you are sure that your list of drawables will be in a sequence of image_1, image_2,... and so on then you can apply below logic,
int count = 0;
int RANDOM_COUNT = 10; //which is more than your drawable count
for (int i = 1; i < RANDOM_COUNT; i++){
int id = getResources().getIdentifier("ic_launcher_"+i,
"drawable", getPackageName());
if(id != 0){
count = + count;
}
else{
break;
}
}
Log.e(TAG, "This is your final count of drawable with image_x - "+ count);
You use this logic because of there will be no drawable with any name as image_x then id will be 0 and you can break the loop
I am not sure if it's possible to dynamically get the number of resources or drawables.
A way to circumvent this issue is to use string arrays as resources in strings.xml.
e.g.
<resources>
<string-array name="foo_array">
<item>abc1</item>
<item>abc2</item>
<item>abc3</item>
</string-array>
int count = getResources().getStringArray(R.array.foo_array).length;

Android - count the number of occurrences android

I have a code
String a = et1.getText().toString();
int ad = 0;
for(int i =0 ; i<a.length(); i++){
if(a.charAt(i)== 'a'){
ad++;
}
}
Toast.makeText(MainActivity.this,
ad, Toast.LENGTH_LONG).show();
I gettext ok but i can't counts character 'a' in string. Can you help me?
Thanks
Another,
if i have String b = et2.getText().toString(); , b is special character, and i want count b in a string. How i can do?
Because you are sending an int to Toast.makeText() so it's looking for a resource id rather than displaying the int as a string.
String a = "asjasuhuashu";
int ad = 0;
for(int i =0 ; i<a.length(); i++){
if(a.charAt(i)== 'a'){
ad++;
}
}
Toast.makeText(this,
ad + "", Toast.LENGTH_LONG).show();
Edited as per Selvin suggestion.
you are passing Integer ad in as toast parameter which consider integer as resource id, use
Toast.makeText(MainActivity.this,
String.valueOf(ad), Toast.LENGTH_LONG).show();
this is another way of calculating character count.
String s = "hghhaahghaa";
int count = s.length() - s.replaceAll("[aA]", "").length();
replace the character you want count of in above character 'a' and 'A' both will be counted.
if you want only character 'a' then replace "[aA]" with "[a]".

Array integer Android

ok so i create an array that has integers. The array displays five number from the min and max. How can i display all five numbers in a textview or edittext ? I tried:
nameofile.setText(al.get(x).toString());
but it only displays one?
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
String myString = TextUtils.join(", ", al);
lottonumbers.setText(myString);
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(0);
al.add(1);
al.add(5);
al.add(4);
al.add(3);
java.util.Collections.sort(al);//for sorting Integer values
String listString = "";
for (int s : al)
{
listString += s + " ";
}
nameofile.setText(listString);
You're currently only printing out one element (the one at index x). If you want to print them all in order, you can just join them using TextUtils.join().
Update: After seeing your edit, I think there's a better way to go about what you're trying to do. Instead of trying to pull the values one at a time, and update the list, why not just shuffle them, then use the above method?
Update 2: Okay, I think I finally understand your problem. Just a simple change, then.
ArrayList<Integer> al = new ArrayList<Integer>();
for (int i = minint; i <= maxint; i++)
al.add(i);
Random ran = new Random();
StringBuilder text = new StringBuilder(); // Create a builder
for (int i = 0; i < 5; i++) {
int x = al.remove(ran.nextInt(al.size()));
if (i > 0)
text.append(", "); // Add a comma if we're not at the start
text.append(x);
}
lottonumbers.setText(text);
al.get(x).toString() will only get the value at index "x". If you want to display all values, you need to combine all of the values from the array into a single string then use setText on that string.
You are only showing one number of your array in the TextView, you must to concat the numbers to see the others results like:
for(Integer integer : al) {
nameofile.setText(nameofile.getText() + " " + al.get(x).toString());
}
Then i think you can show all number in one String.

how to split a string of data into different list views?

Would I be able to split a string of data starting with <NewData> with several different objects inside such as <Schedule> ending in </Schedule> and then ending over all with a </NewData>. Split that into several list views each schedule in a different list view? quite difficult to explain so any thing I've missed just say...
Umm I'll only give you a hint,
String stuff = "<Schedule> save kittens </Schedule> " +
"<Schedule> and puppies </Schedule>" ;
String [] result = stuff.split("<Schedule>");
for(int i = 0; i < result.length; i++)
{
if(result[i].length() > 0)
Log.d("TODO", " - " + result[i].substring(0, result[i].indexOf("<")));
}

Categories

Resources