Amit Mittal
Amit Mittal

Reputation: 85

arrays in android programming

I am new in android programming. Here is my question

I tried to declare an array before onCreate() method like

int[] userselected;

Note that i want to use this array to store ids of buttons user had pressed. Then i tried to find no. of elements in this array with

int noOfElements = userselected.length;

which game me an error. Then I changed declaration to

int[] userselected = {};

it worked, but when i tried to put an id in this array with code

userselected[1] = R.id.textview1;

it again gave me an error. I also tried declaring array as

int[] userselected = new int[4];

but then, when i tried to find how many elements have already been stored, userselected.length

always gave number 4.

Please tell me, how can i get what i want

Upvotes: 0

Views: 3034

Answers (5)

Manoj Kumar
Manoj Kumar

Reputation: 1521

declare it as a integer array then Add this to your code

Integer a=0;
for (int i=0;i>userselected.length;i++)
{
   if(userselected[i]!=null)
    {
      a++;
    }
}

then a will give you the count you need:) cheers:)

Upvotes: 0

twigg
twigg

Reputation: 146

an array is fixed size. so when you declare this array

int[] userselected = new int[4]

you are creating an array with a fixed size of 4. The array index is zero based so its from [0] to [3]. I recommend you use an ArrayList object like the top answer states

when you do this:

int[] userselected = {};

it is the same as this:

int[] userselected = new int[0]; // empty

and you got an error from this:

int[] userselected;

because you have not allocated any space in memory

Upvotes: 1

iTurki
iTurki

Reputation: 16398

You need to use ArrayList. It will give you a more flexible structure giving your case.

ArrayList<Integer> userselected  = new  ArrayList<Integer>();
userselected.add(R.id.textview1); //To add id.
int noOfElement = userselected.size(); //to get size

Upvotes: 5

aelbaz
aelbaz

Reputation: 356

I think this page can help: http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php

In the array declaration you do, you say that its size is 4 elements, therefore the length method will always return 4.

regards

Upvotes: 0

soren.qvist
soren.qvist

Reputation: 7416

Java primitive arrays, such as int[], are constant in length and cannot contain more than their initial length. If you need an array that can change in size, you need to use fx. a List implementation. I would suggest you read up on basic Java before you start developing Android, it would save you a lot of time in the long run.

Upvotes: 0

Related Questions