I have 50 Buttons coded like this:
button_list.set(0,(Button) findViewById(R.id.button0));
button_list.set(1,(Button) findViewById(R.id.button1));
button_list.set(2,(Button) findViewById(R.id.button2));
button_list.set(3,(Button) findViewById(R.id.button3));
button_list.set(4,(Button) findViewById(R.id.button4));
button_list.set(5,(Button) findViewById(R.id.button5));
button_list.set(6,(Button) findViewById(R.id.button6));
button_list.set(7,(Button) findViewById(R.id.button7));
button_list.set(8,(Button) findViewById(R.id.button8));
button_list.set(9,(Button) findViewById(R.id.button9));
button_list.set(10,(Button) findViewById(R.id.button10));
button_list.set(11,(Button) findViewById(R.id.button11));
button_list.set(12,(Button) findViewById(R.id.button12));
button_list.set(13,(Button) findViewById(R.id.button13));
button_list.set(14,(Button) findViewById(R.id.button14));
button_list.set(15,(Button) findViewById(R.id.button15));
.
.
.
How can I put this all in a loop?
When I run the below code I get NullPointerExceptions, I guess meaning the Buttons are not recognized when I attempt to use findViewById. Does anyone know what is wrong with the following code and how I can fix it?
Button[] bttn = new Button[50];
String ids[] = new String[50];
for(int i=0; i<50; i++)
{
ids[i] = "button" + Integer.toString(i);
}
for(int i=0; i<50; i++)
{
int resID = getResources().getIdentifier(ids[i], "id", "your.package.name");
bttn[i] = (Button) findViewById(resID);
}
for(int i=0; i<50; i++)
{
button_list.set(i, bttn[i]);
}
You can do it in a single loop
Button[] buttons = new Button[50];
for(int i = 0; i < buttons.length; i++){
button[i] = (Button) findViewById(getResources().getIdentifier("button" + i, "id", getPackageName());
buttonList.set(i, button[i]); // if your list is already built
//buttonList.add(button[1]); // if you are building your list
}
I use getPackageName() as I assume you are in an Activity, if that is not the case you need to get a reference to the context and use context.getPackageName(); This goes the same for the getResources() call as it also needs a reference to your context.
Related
How can I fill views using cycles. For example, I have a three element:
TextView tv_1, tv_2, tv_3
Can I do something like this?
for(int i=1; i<=3; i++){
tv_{i}.setText(i);
}
Just create an List of textViews and run cycles/loop on it.
List<TextView> textViews = new ArrayList<>();
textViews.add(textView1);
textViews.add(textView2);
textViews.add(textView3);
after that just iterate through it :
for(int i=0 ;i <textViews.size(); i++)
{
textViews.get(i).setText("text");
}
Here, try this.
TextView[] tvs = new TextView[3];
tvs[0] = findViewById(R.id.tv1);
tvs[1] = findViewById(R.id.tv2);
tvs[2] = findViewById(R.id.tv3);
for(int i=0; i<3; i++){
tvs[i].setText(i);
}
I have 16 buttons, whose names are "button1", "button2", and so on. Is there a way I can iterate through them using a for loop, by somehow appending the number value upon each iteration? Something like this:
for(int i = 1; i<17; i++ ){
Button b = (Button)findViewById(R.id.buttoni);
I know I can simply initialize each button in my onCreate() method, but I was just curious if I could do it in a way similar to my example code.
Thank you.
You can use getIdentifier :
for(int i = 1; i<17; i++ ){
int buttonId = getResources().getIdentifier("button"+i, "id", getPackageName());
Button b = (Button)findViewById(buttonId);
//Your stuff with the button
}
You can create an array of Button's and use getIdentifier method that allows you to get an identifier by its name.
final int number = 17;
final Button[] buttons = new Button[number];
final Resources resources = getResources();
for (int i = 0; i < number; i++) {
final String name = "btn" + (i + 1);
final int id = resources.getIdentifier(name, "id", getPackageName());
buttons[i] = (Button) findViewById(id);
}
In case someone is interested how to achive the same result using Java only
The solution above uses Android specific methods (such as getResources, getIdentifier) and can not be used in usual Java, but we can use a reflection and write a method that works like a getIdentifier:
public static int getIdByName(final String name) {
try {
final Field field = R.id.class.getDeclaredField(name);
field.setAccessible(true);
return field.getInt(null);
} catch (Exception ignore) {
return -1;
}
}
And then:
final Button[] buttons = new Button[17];
for (int i = 0; i < buttons.length; i++) {
buttons[i] = (Button) findViewById(getIdByName("btn" + (i + 1)));
}
NOTE:
Instead of optimizing this kind of code you should rethink your layout. If you have 17 buttons on the screen, a ListView is probably the better solution. You can access the items via index and handle onClick events just like with the buttons.
I am having trouble in displaying the values in text view. It displays only the last value in text view. I want to iterate each and every value in new line.
Here is my code.
PreviewCatNameTxt = new TextView[obdatin.catCount];
PreviewNameTxt = new TextView[10];
PreviewQtyTxt = new TextView[10];
PreviewAmtTxt = new TextView[10];
System.out.println("setview3");
for(int i=0;i<obdatin.catCount;i++){
System.out.println("num oof prca"+obdatin.catList[i].getNumCategory());
if(obdatin.catList[i].isTotQtyNonZero(0)){
PreviewCatNameTxt[i] = (TextView) findViewById(R.id.textViewh);
PreviewCatNameTxt[i].setText(obdatin.catList[i].getCategoryName(0));
System.out.println("prca"+obdatin.catList[i].getCategoryName(0));
}
int cnt =obdatin.catList[i].proList.getNumProduct();
System.out.println("setview3");
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
PreviewNameTxt[j] = (TextView)findViewById(R.id.textView1);
PreviewNameTxt[j].setText(obdatin.catList[i].proList.getProductName(j));
PreviewQtyTxt[j] = (TextView)findViewById(R.id.textView2);
PreviewQtyTxt[j].setText(obdatin.catList[i].proList.getProductQty(j));
PreviewAmtTxt[j] = (TextView)findViewById(R.id.textView3);
String amt = obdatin.catList[i].proList.getProductAmt(j);
PreviewAmtTxt[j].setText(amt);
System.out.println("prcaN"+obdatin.catList[i].proList.getProductName(j));
System.out.println("prcaQ"+obdatin.catList[i].proList.getProductQty(j));
System.out.println("prcaA"+obdatin.catList[i].proList.getProductAmt(j));
}
}
Edited Code as per your requirement
PreviewCatNameTxt = (TextView) findViewById(R.id.textViewh);
for(int i=0;i<obdatin.catCount;i++){
System.out.println("num oof prca"+obdatin.catList[i].getNumCategory());
if(obdatin.catList[i].isTotQtyNonZero(0)){
PreviewCatNameTxt.append(" "+obdatin.catList[i].getCategoryName(0));
System.out.println("prca"+obdatin.catList[i].getCategoryName(0));
}
int cnt =obdatin.catList[i].proList.getNumProduct();
System.out.println("setview3");
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
PreviewCatNameTxt.append("\n"+obdatin.catList[i].proList.getProductName(j));
PreviewCatNameTxt.append("\n"obdatin.catList[i].proList.getProductQty(j));
String amt = obdatin.catList[i].proList.getProductAmt(j);
PreviewCatNameTxt.append("\n"+amt+"\n\n");
System.out.println("prcaN"+obdatin.catList[i].proList.getProductName(j));
System.out.println("prcaQ"+obdatin.catList[i].proList.getProductQty(j));
System.out.println("prcaA"+obdatin.catList[i].proList.getProductAmt(j));
}
Please remove TextView array and all those things. Please reply your feedback.
I am not entirely sure what you are trying to do.Why do you use System.out.println?
If I got it right you want a larger text to be put in TextView separated by newlines after each loop of the for. One way to do it is to have a String which you fill with every iteration, also adding a newline after each iteration and after the for setting the text.
So, you could have something like this:
String catList="";
for(int i=0;i<obdatin.catCount;i++){
if(obdatin.catList[i].isTotQtyNonZero(0)){
catList = catList + obdatin.catList[i].getCategoryName(0) + "\n";
}
int cnt =obdatin.catList[i].proList.getNumProduct();
PreviewCatNameTxt[i] = (TextView) findViewById(R.id.textViewh);
PreviewCatNameTxt[i].setText(catList);
Also, if you want to log something you should od to use LogCat. You can read about Reading and Writing in LogCat here and here.
Good luck!
PreviewNameTxt[j] = (TextView)findViewById(R.id.textView1);
PreviewQtyTxt[j] = (TextView)findViewById(R.id.textView2);
PreviewAmtTxt[j] = (TextView)findViewById(R.id.textView3);
String cat="",obtaincat="",amt="";
for(int j = 0; j<cnt; j++) {
if(obdatin.catList[i].proList.isQtyNonZero(j)){
cat = cat + obdatin.catList[i].getCategoryName(j) + "\n";
obtaincat=btaincat+obdatin.catList[i].proList.getProductQty(j)+"\n";
amt =amt+ obdatin.catList[i].proList.getProductAmt(j)+"\n";
}
}
PreviewNameTxt[j].setText(cat);
PreviewQtyTxt[j].setText(obtaincat);
PreviewAmtTxt[j].setText(amt);
Change to Logcat :
Log.w("","prcaN"+obdatin.catList[i].proList.getProductName(j));
Log.w("","prcaQ"+obdatin.catList[i].proList.getProductQty(j));
Log.w("","prcaA"+obdatin.catList[i].proList.getProductAmt(j));
I am making an app in which there are list of questions and respective answers.
Questions are in one string array, while answers are in another string array.
I have implemented the following in a wish to shuffle the questions. (Of course the answers need to be linked to that question, else meaningless)
Code:
selected_Q = new String[totalnoofQ];
selected_A = new String[totalnoofQ];
int[] random_code = new int[totalnoofQ];
for (int i = 0; i < totalnoofQ; i++)
{
random_code[i] = i;
}
Collections.shuffle(Arrays.asList(random_code));
for (int j = 0; j < totalnoofQ; j++)
{
int k = random_code[j];
selected_Q [j] = databank_Q [k];
selected_A[j] = databank_A [k];
}
The code reports no fatal error, but the selected_Q is still in sequential order. Why?
Could you please show me how can I amend the codes? Thanks!!!
You shuffle a list created using random_code, but random_code is not modified.
You need to create a temporary list based on random_code. Shuffle this list and then use it to fill the selected_X arrays.
Something like this should work :
int[] random_code = new int[totalnoofQ];
for (int i = 0 ; i < totalnoofQ ; i++) {
random_code[i] = i;
}
List<Integer> random_code_list = new ArrayList<Integer>(); // Create an arraylist (arraylist is used here because it has indexes)
for (int idx = 0 ; idx < random_code.length ; idx++) {
random_code_list.add(random_code[idx]); // Fill it
}
Collections.shuffle(random_code_list); // Shuffle it
for (int j = 0 ; j < totalnoofQ ; j++) {
int k = random_code_list.get(j); // Get the value
selected_Q[j] = databank_Q[k];
selected_A[j] = databank_A[k];
}
I'm making an android application, where there is a view composed of hundreds of buttons, each with a specific callback. Now, I'd like to set these callbacks using a loop, instead of having to write hundreds of lines of code (for each one of the buttons).
My question is: How can I use findViewById without statically having to type in each button id?
Here is what I would like to do:
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
buttons[i][j] = ((Button) findViewById(R.id.buttonID));
buttons[i][j].setOnClickListener(this);
}
}
Thanks in advance!
You should use getIdentifier()
for(int i=0; i<some_value; i++) {
for(int j=0; j<some_other_value; j++) {
String buttonID = "btn" + i + "-" + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = ((Button) findViewById(resID));
buttons[i][j].setOnClickListener(this);
}
}
You can try making an int[] that holds all of your button IDs, and then iterate over that:
int[] buttonIDs = new int[] {R.id.button1ID, R.id.button2ID, R.id.button3ID, ... }
for(int i=0; i<buttonIDs.length; i++) {
Button b = (Button) findViewById(buttonIDs[i]);
b.setOnClickListener(this);
}
Take a look at these answers:
Android and getting a view with id cast as a string
Array of ImageButtons, assign R.view.id from a variable
you can Use tag if you want to access.
in onClick
int i=Integer.parseInt(v.getTag);
But you cant access that button like this.
simply create button programatically
by Button b=new Button(this);
create Custom Button in java code rather in Xml as i shown below
Button bs_text[]= new Button[some_value];
for(int z=0;z<some_value;z++)
{
try
{
bs_text[z] = (Button) new Button(this);
}
catch(ArrayIndexOutOfBoundsException e)
{
Log.d("ArrayIndexOutOfBoundsException",e.toString());
}
}
If your top level view only has those button views as children, you could do
for (int i = 0 ; i < yourView.getChildCount(); i++) {
Button b = (Button) yourView.getChildAt(i);
b.setOnClickListener(xxxx);
}
If there are more views present you'd need to check if the selected one is one of your buttons.
If for some reason you can't use the getIdentifier() function and/or you know the possible id's beforehand, you could use a switch.
int id = 0;
switch(name) {
case "x":
id = R.id.x;
break;
etc.etc.
}
String value = findViewById(id);
To put it simply, here's a function for it
public View findViewByArrayName (String name, int i) {
buttonID = name + Integer.toString(i);
resID = getResources().getIdentifier(buttonID, "id", getPackageName());
return findViewById(resID);
}
Also unlike Python, Java is a compiled language, so it probably makes sense that there aren't any chances for dynamic variable names. Unless achieved through a certain approach like this one.