How do you loop through view id's? - android

For my android app I need to make an array of View ID's.
The array will hold 81 values so it's quite lengthy to add them one by one.
This is how it looks now:
cells[0] = R.id.Square00;
cells[1] = R.id.Square01;
cells[2] = R.id.Square02;
cells[3] = R.id.Square03;
cells[4] = R.id.Square04;
cells[5] = R.id.Square05;
//All the way to 80.
Is there a shorter/more efficient way of doing this?

Thankfully, there is. Use getIdentifier():
Resources r = getResources();
String name = getPackageName();
int[] cells = new int[81];
for(int i = 0; i < 81; i++) {
if(i < 10)
cells[i] = r.getIdentifier("Squares0" + i, "id", name);
else
cells[i] = r.getIdentifier("Squares" + i, "id", name);
}

Sam's answer is better but i think i should share an alternative
int [] ids = new int [] {R.id.btn1, R.id.btn2, ...};
Button [] arrayButton = new Button[ids.length];
for(int i=0 ; i < arrayButton.length ; i++)
{
arrayButton[i] = (Button) findViewById(ids[i]);
}
Modified form of Sam Answer
No need of if else use Integer String Formating
Resources r = getResources();
String name = getPackageName();
int[] resIDs = new int[81];
for(int i = 0; i < 81; i++)
{
resIDs[i] = r.getIdentifier("Squares0" + String.format("%03d", i), "id", name);
}

Related

Create a arraylist from output of a for loop

I am trying to get a data set as [{a,b,c,d} {e,f,g,h}] but I'm getting it as [a,b,c,d,e,f,g,h] using below mentioned code. What should I do to achieve that. any help will be highly appreciated. I'm new to android so please be kind enough to answer me. thanks in advance
List<String> CartItemEntityList = new ArrayList<String>();
for (int i = 0; i < mCartList.size(); i++) {
if (!mCartList.isEmpty()) {
Product product = mCartList.get(i);
int quantity = product.quantity;
double subTotal = product.subTotal;
CartItemEntity = product.items;
for (int j = 0; j < CartItemEntity.size(); j++) {
Item item = CartItemEntity.get(j);
subMenuCode = item.subMenuCode;
mainMenuCode = item.mainMenuCode;
price = item.price;
CartItemEntityList.add(mainMenuCode);
CartItemEntityList.add(String.valueOf(price));
CartItemEntityList.add(String.valueOf(quantity));
CartItemEntityList.add(subMenuCode);
}
}
System.out.println("CartItemEntityList " + CartItemEntityList);
}
I was able to achieve this using json serialization and this is my answer
JSONObject jsonObj = new JSONObject();
jsonObj.put("MainMenuCode",
item.getMainMenuCode());
jsonObj.put("Price", item.getPrice());
jsonObj.put("Quantity", product.getQuantity());
jsonObj.put("SubMenuCode",
item.getSubMenuCode());
String a = jsonObj.toString();
CartIddtemEntityList.add(a);
you have to create array of arraylist.
Try something like below:
ArrayList<ArrayList<String>> group = new ArrayList<ArrayList<String>>(mCartList.size());
for (int i = 0; i < mCartList.size(); i++) {
List<String> CartItemEntityList = new ArrayList<String>();
if (!mCartList.isEmpty()) {
Product product = mCartList.get(i);
int quantity = product.quantity;
double subTotal = product.subTotal;
CartItemEntity = product.items;
for (int j = 0; j < CartItemEntity.size(); j++) {
Item item = CartItemEntity.get(j);
subMenuCode = item.subMenuCode;
mainMenuCode = item.mainMenuCode;
price = item.price;
CartItemEntityList.add(mainMenuCode);
CartItemEntityList.add(String.valueOf(price));
CartItemEntityList.add(String.valueOf(quantity));
CartItemEntityList.add(subMenuCode);
}
}
System.out.println("CartItemEntityList " + CartItemEntityList);
group.add(CartItemEntityList);
}

Android - getIdentifier() throws Resources$NotFoundException

I'm making a simple scoring system for a minesweeper clone and I keep getting the Resources$NotFoundException when it crashes. I'm pretty sure it's the getIdentifier function that's causing it and I've had nothing but trouble with this function in the past. What am I doing wrong?
Thanks in advance.
private void doScoring()
{
SharedPreferences sp = this.getSharedPreferences("scores", Context.MODE_PRIVATE);
int score = (int) Math.ceil(1000/this.getIntent().getExtras().getDouble("time"));
int[] scores = new int[10];
String[] names = new String[10];
int newOffset = 0;
for(int i = 0; i < 10; i++)
{
if(sp.getInt("s"+i,999)>score&&newOffset==0)
{
newOffset++;
names[i] = "Prompted Name";
scores[i] = score;
}
scores[i] = sp.getInt("s"+(i-newOffset), 999);
names[i] = sp.getString("n"+(i-newOffset), "No Score");
((TextView) this.findViewById(getResources().getIdentifier("score_name_"+(i+1), "id", "edu.laura.omc_prototype"))).setText(scores[i]);
((TextView) this.findViewById(getResources().getIdentifier("score_"+(i+1), "id", "edu.laura.omc_prototype"))).setText(names[i]);
}
}

How to generate random number with out duplicates using JSON array in android

I am new to android. I am doing quize app.I have one JSON array text file.how to generate random number with out repetation using JSON array in android..please help me
Thank you adv..
this is my sample code
public static JSONArray getQuesList()throws JSONException{
ArrayList<Integer> list = new ArrayList<Integer>(size);
for(i =size - 1; i >= 0; i--) {
//index = rnd.nextInt(list.size());
list.add(i);
}
Random rand = new Random();
while(list.size() > 0) {
index = rand.nextInt(list.size());
Object object = quesList.get(index);
quesList.put(index, quesList.get(i));
quesList.put(i, object);
Log.d("","Selected: "+list.remove(index));
}
return quesList;
Edited
QuestionActivity.java
Global variable
int[] quizarray = null;
Add two functions
private void createQuizIndex() {
int[] array = new int[QuizFunActivity.getQuesList().length()];
quizarray = new int[QuizFunActivity.getQuesList().length()];
for(int i = 0 ; i < QuizFunActivity.getQuesList().length() ; i++){
array[i] = i;
}
Random random = new Random();
int m = 0;
for (int n = array.length ; n > 0; n--){
int r = random.nextInt(n);
quizarray[m++] = array[r];
array[r] = array[n-1];
}
}
private int getIndexNum(int quesIndex2) {
return quizarray[quesIndex2];
}
Change every showQuestion
showQuestion(getIndexNum(quesIndex),review);
Call createQuizIndex() in line 80, and line 194 if "Retake" means another random quiz

How to sort numbers in TextViews and display them?

Hi can some one suggest me a sample example of how i can sort the textviews based on the numbers in textviews. I am able to get the text from the TextViews need to sort and place the lowest number first.
Thank you.
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
for (int i = 0; i < intValues.length; i++) {
Integer intValue = intValues[i];
//here I want to assign sorted numberes to the TextViews
}
}
So I have followed Jeffrey's advice. Here is the code which still doesn't work properly. What could be wrong?
Created an array of TextViews:
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
tvs[2] = textView43;
tvs[3] = textView53;
tvs[4] = textView63;
tvs[5] = textView73;
tvs[6] = textView83;
Sorted the array and assinged new values to the TextViews:
Arrays.sort(tvs, new TVTextComparator());
textView23.setText(tvs[0].getText().toString());
textView33.setText(tvs[1].getText().toString());
textView43.setText(tvs[2].getText().toString());
textView53.setText(tvs[3].getText().toString());
textView63.setText(tvs[4].getText().toString());
textView73.setText(tvs[5].getText().toString());
textView83.setText(tvs[6].getText().toString());
And here is the Comporator class:
public class TVTextComparator implements Comparator<TextView> {
public int compare(TextView lhs, TextView rhs) {
Integer oneInt = Integer.parseInt(lhs.getText().toString());
Integer twoInt = Integer.parseInt(rhs.getText().toString());
return oneInt.compareTo(twoInt);
}
}
to sort your textViews, first put them in an array,
TextView[] tvs = new TextView[7];
tvs[0] = textView23;
tvs[1] = textView33;
// and so on
note that if you have handle to the parent container, you could easily build the array by using ViewGroup.getChildCount() and getChildAt().
now write a comparator for a text view,
class TVTextComparator implements Comparator<TextView> {
#Override
public int compare(TextView lhs, TextView rhs) {
return lhs.getText().toString().compareTo(rhs.getText().toString());
// should check for nulls here, this is NOT a robust impl of compare()
}
}
now use the comparator to sort the array,
Arrays.sort(tvs, 0, tvs.length, new TVTextComparator());
public void sortNumbers(View v) {
String[] numbers = new String[7];
numbers[0] = textView23.getText().toString();
numbers[1] = textView33.getText().toString();
numbers[2] = textView43.getText().toString();
numbers[3] = textView53.getText().toString();
numbers[4] = textView63.getText().toString();
numbers[5] = textView73.getText().toString();
numbers[6] = textView83.getText().toString();
Integer[] intValues = new Integer[numbers.length];
for (int i = 0; i < numbers.length; i++) {
intValues[i] = Integer.parseInt(numbers[i].trim());
}
Collections.sort(Arrays.asList(intValues));
textView23.setText(intValues[0]);
textView33.setText(intValues[1]);
textView43.setText(intValues[2]);
textView53.setText(intValues[3]);
textView63.setText(intValues[4]);
textView73.setText(intValues[5]);
textView83.setText(intValues[6]);
}

For loop with object names

If I have an array of buttons in android and want to get these buttons (findviewbyid) through a for loop how do i do this? Lets say I have in my xml defined button1, button2 and button3. How do I assign arr[0],arr[1] and arr[2] to these?
for(int a = 0; a < arr.length; a++){
arr[a] = (Button) findViewById(R.id.button[a + 1]); //Doesn't work
}
Thanks in advance!
Try to implement this:
for(int a=0; a<arr.length; a++) {
String buttonID = "btn" + a;
int resID = getResources().getIdentifier(buttonID, "id", "com.package.your_app");
// To fetch Package name, you can directly call getPackageName() instead of static string "com.package.your_app
buttons[a] = ((Button) findViewById(resID));
buttons[a].setOnClickListener(this);
}
Then this work:
for(int a = 0; a < arr.length; a++) {
String buttonId = "btn" + String.valueOf(a);
int resButton = getResources().getIdentifier(buttonId, "id", "com.package.your_app");
arr[a] = (Button) findViewById(resButton);
}

Categories

Resources