In my app, I have a bunch of images in my drawable folder which I select at random and display using imageView. I've been told about ArrayList's which can add/remove objects from the list...in order to prevent image repeats, some sample code I used below:
// create an array list
ArrayList imageHolder = new ArrayList();
int remaining = 10;
public void initArrayList(){
// add elements to the array list
imageHolder.add((int)R.drawable.child0);
imageHolder.add((int)R.drawable.child1);
imageHolder.add((int)R.drawable.child2);
imageHolder.add((int)R.drawable.child3);
imageHolder.add((int)R.drawable.child4);
imageHolder.add((int)R.drawable.child5);
imageHolder.add((int)R.drawable.child6);
imageHolder.add((int)R.drawable.child7);
imageHolder.add((int)R.drawable.child8);
imageHolder.add((int)R.drawable.child9);
}
//get random number within the current range
int randInt = new Random().nextInt((remaining-1));
//update the imageView config
ImageView image = (ImageView) findViewById(R.id.shuffleImageView);
image.setImageResource(imageHolder.get(randInt));
Eclipse reports that image.setImageResource cannot use an object argument, which is what is provided by arrayList. The actual argument should be int. Any clue how to get around this??
Thanks in advance!
Use List<Integer> imageHolder = new ArrayList<Integer>();
ArrayList contains Objects, always, never primitive types. When you set ints into it, they are autoboxed to Integer objects, when you get them back, you get Integer objects as well. A short fix will be:
image.setImageResource((int)imageHolder.get(randInt));
Be careful though, unboxing a null pointer will cause a NullPointerException, So make sure your randInt is in the range of the arraylist.
EDIT:
I totally missed that, but You initialize your ArrayList like that:
ArrayList imageHolder = new ArrayList();
Which creates ArrayList of Objects. instead, initialize the ArrayList like the following to create ArrayList of integers:
List<Integer> imageHolder = new ArrayList<Integer>();
Related
I have copied some code from a project and want to reuse a small part of it in my private app.
The class contains a Sparse Array
public class GolfResult {
String hcpAfter;
String hcpBefore;
SparseArray roundResults;
public GolfResult() {
hcpAfter = "";
hcpBefore = "";
roundResults = new SparseArray();
}
}
I have created an ArrayList for roundResults that is filled with the necessary data.
Then I am trying to fill the instance with content.
GolfResult golferRes = new GolfResult();
SparseArray<RoundResults> hu= new SparseArray<>();
hu = roundresults; // *
golferRes.setHcpAfter("33");
golferRes.setHcpBefore("kk");
golferRes.setRoundResults(hu);
But the problem is that hu = roudresults is not possible, because of the error message:
required: Android.util.SparseArray found: java.util.Array List
Any help will be welcome.
After receiving two helpful answers I got a step further, but now I am facing the problem that my SparseArray hu is empty {}.
The content of hu should be the class roundresults that has the following structure:
public class RoundResults {
boolean actualRound;
private List<HoleResult> holeResults;
Integer roundId;
Integer roundNumber;
String unfinishedReason;
The arrayList roundresults has the size of 1 and has data in the objects.
unfinishedReason =""
holeResults = ArrayLIST size= 18
roundID = "1"
roundNumber = "1"
actualRound = true
hu ={}
mValues = All elements are null
mSize = 0
Does anybody have an idea why?
SparseArray is different than ArrayList, from the documentation:
SparseArrays map integers to Objects. Unlike a normal array of
Objects, there can be gaps in the indices. It is intended to be more
memory efficient than using a HashMap to map Integers to Objects, both
because it avoids auto-boxing keys and its data structure doesn't rely
on an extra entry object for each mapping.
It's using a key value pair principle where the key is an integer and the value which the key mapping is the object. You need to use put [(int key, E value)](https://developer.android.com/reference/android/util/SparseArray.html#put(int, E)) where the E is your object. Remember that:
Adds a mapping from the specified key to the specified value,
replacing the previous mapping from the specified key if there was
one.
So you need to use a loop to add each object in your ArrayList as #valentino-s says:
SparseArray<RoundResults> hu= new SparseArray<>();
for( int i = 0; i < roundresults.size(); i++) {
// i as the key for the object.
hu.put(i, roundresults.get(i));
}
If I understand well your problem, maybe you can try with this:
for ( int i=0; i<roundresults.size(); i++ ) {
hu.put(i,roundresults.get(i));
}
After some trial and error I found a solution for the empty hu:
Instead of put I used append and it is working now.
hu.append(i, roundresults.get(i));
Time for a beer.
now i've got simple setter and getter of string array. I want to use setter to put some retrevied json info + same text to array. When i use belowe code:
met.setPlacepic(new String[]{"http://dfsdfsdfsf/" + json.getString("source")});
it looks like setter put only one string to array, despite there is many more data.
Declaration is simple
public String[] placepic
and the setter is also simple:
public void setPlacepic(String[] placepic) {
this.placepic = placepic;
}
Anybody knows reason of this?
If the number of strings is fixed (you know exactly how many element you would have in the array), then you could use String Arrays:
String[] placepic = new String[20]; //20 strings
//Then, in your loop:
placepic[i] = yourData;
If you do NOT know how many strings in your data, You should use List:
List<String> placepicList= new ArrayList<String>();
//Then, in your loop:
placepicList.add(yourData);
//Then after the loop, you get the array
String[] placepic = placepicList.toArray(new String[placepicList.size()]);
I have a code adding multiple EditText. How can i store them into a array. This number 10 is just example, the number may bigger than that. How can i store it after click a button
for(int i=0; i<10; i++) {
String store[] = new String[10];
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
}
In your example the store variable isn't actually being used, did you intend do use it for storing the EditTexts?
Instead of using an array of String, just use an array of EditText and store a reference to them:
EditText store[] = new EditText[10];
for(int i=0; i<10; i++) {
EditText addAnsMCQ = new EditText(this);
AnswerRG.addView(addAnsMCQ, 1);
addAnsMCQ.setWidth(200);
addAnsMCQ.setId(1000);
store[i] = addAnsMCQ; //store a reference in the array to the EditText created
}
Then outside of the for loop, you can access the reference to each EditText, e.g.
store[0].setWidth(300);
You need to keep/get a reference to each of your EditText's then you can look up its value with .getText().toString() which you can store in whatever manner you like.
However if as you say
This number 10 is just example, the number may bigger than that.
If the number is going to be larger you should be using an Adapter and a ListView or something to hold your View objects. That will make it easier to get everything on to the screen. And will give you the benefit of view recycling.
I want to download a bunch of images and would like to store it as drawable in an array. So I tried declaring a drawable array.But it returns me nullPointer exception when I access that array.
My question is, how to declare an array type as drawable ?
an array of drawables would be declared like:
int numDrawables = 10;
Drawable[] drawableArray = new Drawable[numDrawables];
to fill the array:
for(int i = 0; i < numDrawables; i++){
// get a drawable from somewhere
Drawable drawable = new Drawable();
drawableArray[i] = drawable;
}
to access the array:
Drawable aDrawable = drawableArray[0];
This is basic java, If you are getting null pointer exceptions, you are doing something wrong.
you can use an hashMap , and put the keys as urls for example , and to value is the drawable that you download :
HashMap<String,Drawable> myDrawables = new HashMap<String,Drawable>();
//before you download the images, you can test if your drawable is already downloaded,
// with looking for his url in the Hashmap ,
.....
myDrawables.put(urlOfYourDrawable, yourDrawable);
If you want to store list of elements(any type) dynamically use the classes in the collection. why because Array size is static.
Example:
ArrayList<Generic> list=new ArrayList<Generic>();
list.add(Generic);
What I'm doing is wanting to start off my ListView with 0 rows, download a list from the Internet, then populate the ListView with the downloaded contents. Seems easy enough, but arrays are proving to be an issue.
What's happening is that I'm declaring my array in the only way ListView seems to want it
static String[] CONTENTS = new String[]{};
so that it populates with no rows. After downloading the contents through a thread, I then go to fill the array with what I've downloaded. The problem is that it doesn't want to fill the array; if I initiate the array with one empty string, it will only let me fill it with exactly one row (so if I give it an array with more than one object, it doesn't do anything). How can I expand on the array the ListView is taking data from, so I can fill it with more than the number of objects I've declared it with?
The closest I've been able to come was through the code
private String[] expand(String[] array, int size) {
String[] temp = new String[size];
System.arraycopy(array, 0, temp, 0, array.length);
for(int j = array.length; j < size; j++)
temp[j] = "";
return temp;
}
to expand the array and giving it the number of objects downloaded, but that still doesn't seem to work.
Thanks in advance!
Don't use arrays, use some implementation of List. (ArrayList will do the work). Collections are far superior than old-school arrays.
//List
list = new ArrayList();
//BaseAdapter
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, list);
//ListView
listView = (ListView) findViewByID(R.id.listview);
listView.setAdapter(adapter);
And when you add/remove elements to/from the list, you must invoke
adapter.notifyDataSetChanged();
How can I expand on the array ...
I assume you are using an ArrayAdapter. Instead of using a fixed-size array, use a dynamically-resizable ArrayList to back it using one of the ArrayAdapter constructors that take a List argument.