Im doing an App on Android Studio and im trying to add all my checkbox IDs into an array, so i can use it , without doing it manually.
I tried to do it on another way, but i didn´t find nothing on google that help me,
So here is my goal:
I want to get all my Checkbox ids, so i can get their text. And i don´t want to do it manually because i got alot of checkboxs.
I tried to write a code by myself but i´m getting an message error.
Here is my code:
CheckBox[] MinhaCheckBox;
SharedPreferences Dados;
String MinhaPasta = "Pasta";
String valor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_Gerar(View v)
{
Dados = getSharedPreferences(MinhaPasta,0);
SharedPreferences.Editor Edita = Dados.edit();
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
for(int i = 0 ; i < IDTexBoz.length; i++)
{
*//I GOT AN ERRO HERE. please help me.*
* // when i try to put mycheckbox on my array, i got th error!*
MinhaCheckBox[i] = (CheckBox)findViewById(IDTexBoz[i]);
}
for (int a= 0; a < MinhaCheckBox.length;a++)
{
if(MinhaCheckBox[a].isChecked())
valor += MinhaCheckBox[a].getText().toString() + ";";
}
Edita.putString("Dado", valor);
Edita.commit();
Intent MeuIntent = new Intent(this,Main2Activity.class);
startActivity(MeuIntent);
}
}
You need to initialize your checkbox array.
Maybe this example could help, you don't need to store the ID name, do something like this..
for(int i=1;i<=12 ;i++){
int resID = getResources().getIdentifier("checkBox"+i, "id",getPackageName());
CheckBox cb = (CheckBox) findViewById(resID);
//Handle cb object here
}
It's Very Simple.
int IDTexBoz[] = {R.id.checkBox,R.id.checkBox2,R.id.checkBox3,R.id.checkBox4,R.id.checkBox5,
R.id.checkBox6,R.id.checkBox7,R.id.checkBox8};
//Here is code for array initialization.
MinhaCheckBox = new CheckBox[IDTexBoz.length];
Related
I am having trouble with my output screen!
When I click on Click button with these inputs output screen looks like attached image, which is so far great!
But if I change my input, the program gives new answer by adding more rows with previous answers! I want only new answers on screen to be shown!
Also without updating input if I click on button same way screen adds up new rows!
I am including a picture of this also..
I used this code given below,
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
bisection();
}
});
private void bisection() {
if ((f(aI) < 0 && f(bI) > 0) || (f(aI) > 0 && f(bI) < 0)) {
for (int i = 0; i < cI; i++) {
View tableRow = LayoutInflater.from(this).inflate(R.layout.table_item, null, false);
TextView iteration = (TextView) tableRow.findViewById(R.id.index);
TextView a = (TextView) tableRow.findViewById(R.id.a);
TextView b = (TextView) tableRow.findViewById(R.id.b);
TextView x = (TextView) tableRow.findViewById(R.id.x);
TextView fx = (TextView) tableRow.findViewById(R.id.fx);
double root = (aI+bI)/2;
iteration.setText(" " + (i + 1));
a.setText(Double.toString(aI));
b.setText(Double.toString(bI));
x.setText(Double.toString(root));
fx.setText(Double.toString(f(root)));
tableLayout.addView(tableRow);
if(f(aI)*f(root) < 0){
bI = root;
}else if (f(aI)*f(root) >0) {
aI = root;
}
}
} else {
Toast.makeText(getApplicationContext(), R.string.popUpMsg,Toast.LENGTH_SHORT).show();
}
}
public static double f(double x){
return ((Math.pow(x,3))-x-4);
}
I have already found almost same problem has been solved in a post previously asked by someone else but I couldn't fix mine! Help me. Thanks!
In your button click listener method, add following line of code before calling bisection().
tableLayout.removeAllViews();
Whenever, you will click the button, previous output will be removed before calculating new input values.
Your code would look like this:
clickbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aI = Double.parseDouble(Ia.getText().toString());
bI = Double.parseDouble(Ib.getText().toString());
cI = Double.parseDouble(Ic.getText().toString());
tableLayout.removeAllViews(); // Remove previous output
bisection();
}
});
first way; You have to use
removeAllViews();
Before adding. To do this, you have to have a layout variable around. ex;
linearLayout.removeAllViews();
Another way is adding the Textviews in the beginning with VIEW.INVISIBLE or VIEW.GONE
Whichever suits you.
for(int i=1;i<=3;i++)
{
String my_id="Ezequiel_1_"+i;
final TextView modelTextview = (TextView) findViewById(R.id.my_id);
modelTextview.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
the_controller.buttonController(v);
}
});
}
I arranged my ids in the previous manner and I don't want to set the method one by one. Is it possible to iterate like that?
Not directly, because strings aren't ids. There's two ways to do what you want though:
1)Data based
int textViewIds[] = [R.id.Ezequiel_1_1, R.id.Ezequiel_1_2, R.id.Ezequiel_1_3,...]
for(int id: textViewIds) {
TextView tv = (TextView) findViewById(id);
...
}
2)Name based
for(int i=0; i<numView, i++) {
int resourceId = resources.getIdentifier("Ezequiel_1_"+i, "id",
context.getPackageName());
TextView tv = (TextView) findViewById(id);
...
}
I prefer method 1 as it gives you clearer code and protection against off by 1 errors (they won't compile).
I am developing a simple questionnaire-like app which includes lots of radio buttons joined into groups and spinners. I have multiple activities (6); some of them having RBs and some Spinners to let the user answer the questions.
The following step, which I have trouble with, is how to fetch lots of selections (of all the radio buttons/choices) and possibly do that in a for loop (so I don't have to initialize each new variable 30+ times in a row for just one activity). I've already assigned IDs to all of the views, but am having a hard time how to actually fetch the selection, initialize a new var corresponding to the selection (let's say radio button 1 in radio group 1 gives me a new variable with a value of 1) and then make the variables available to all of the activities (should I use global when initializing?).
My failed attempt on generating 10 variables for the first "page"
public void goTo2(View v) {
checkRB();
Intent intent1 = new Intent(Vprasalnik1.this, Vprasalnik2.class);
startActivity(intent1);
finish();
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
RadioButton "vRB" + i; //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Put variables into array like a
int size = 9;
RadioButton[] views = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
views[i] = (RadioButton)findViewByID(...);//For example
}
}
Or make a structure :
public class Choise
{
int mRadioButtonChoise;
int mSpinnerChoise;
}
And use something like this:
...
Choise c = new Choise();
c.mRadioButtonChoise = yourRadioButtonID;
c.mSpinnerChoise = youtSpinnerChoiseID;
...
Using a variable to identify a resource:
RadioButton[] rb = new RadioButton[size];
public static checkRB()
{
for(int i=0;i<size;i++)
{
int id = context.getResources().getIdentifier("vRB" + i, "id", context.getPackageName())
rb[i] = (RadioButton)findViewByID(id);
}
}
If you have an array of RadioButtons then you can get all the values at the same time, however initializing them will have to be manual.
RadioButton rb[];
boolean rbc[];
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
rbc=new boolean[200];
rb=new RadioButton[200]();
rb[0]=(RadioButton)findViewById(R.id.rb1);
rb[1]=(RadioButton)findViewById(R.id.rb2);
rb[2]=(RadioButton)findViewById(R.id.rb3);
rb[3]=(RadioButton)findViewById(R.id.rb4);
// many more.
}
public void checkRB()
{
for (int i=0;i<9;i++)
{
rbc[i]=rb.isChecked(); //I'd like to loop and initialize vars by adding a number to them (vRB1, vRB2, ...)
}
}
Then before starting your intent add all relevant data to it.
So I've managed to cramp up the radio buttons activity, so that it finally works. If anyone is interested - I've used tags in xml code to properly assign values (1, 2 and 3 for each group of buttons) and managed to get an output in my testToast. At least I didn't have to initialize all of the variables manually - I've been saving the values into an ArrayList and then appended to them via StringBuilder.
Thanks to everyone who tried to help - it turned out I've needed a bit more research, testing and teasing my half-awake brain.
btn = (Button) findViewById(R.id.v3_btn1);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for(int i = 1; i <= 36; i++)
{
tmpRGid = "radioGroup_v3q" + i;
tmp2RGid = getResources().getIdentifier(tmpRGid, "id", getPackageName());
RGid = (RadioGroup) findViewById(tmp2RGid);
selectedOption = RGid.getCheckedRadioButtonId();
RBid = (RadioButton) findViewById(selectedOption);
addToIDList.add((String)RBid.getTag());
}
String testToast = "";
StringBuilder builder = new StringBuilder();
builder.append("Vaša izbira (");
for (int z=0; z < addToIDList.size(); z++) {
testToast = addToIDList.get(z);
builder.append(testToast + ", ");
}
builder.setLength(builder.length() - 2);
builder.append(") je bila shranjena.");
Toast.makeText(Vprasalnik3.this, builder, Toast.LENGTH_LONG).show();
I am trying to create dynamic buttons. When clicking a button it should go to the specified url assigned to the text of the button.
For testing, first I tried to get that ID, if it is equal it prints the value of i. But whenever I clicked any one button, instead of telling that particular i value, it enters into whole loop, and prints all the values of i starting from 1 to 19 (the number of buttons that are dynamically created)
And after printing all values from 1 to 19, the program is getting force closed saying Null pointer exception.
I even tried by placing the handler code outside onCreate(), but I'm still getting the same error.
for ( i = 0; i <itemList.getTitle().size()-1; i++) {
title[i] = new TextView(this);
title[i].setTextColor( -16711936 );
title[i].setTextSize(18);
title[i].setText("Title = "+itemList.getTitle().get(i));
description[i] = new TextView(this);
description[i].setTextColor(-16776961);
description[i].setText("Description = "+itemList.getDescription().get(i)+"......");
more[i]=new Button(this);
more[i].setText(itemList.getLink().get(i));
layout.addView(title[i]);
System.out.println("Title view is set");
layout.addView(description[i]);
//System.out.println("Description view is set");
layout.addView(more[i]);
more[i].setOnClickListener(listener);
}
private OnClickListener listener=new OnClickListener(){
public void onClick(View arg) {
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
//System.out.println("Vlaue of I in onclick"+i);
//Uri uri=Uri.parse(itemList.getLink().get(i));
//startActivity(new Intent(Intent.ACTION_VIEW,uri));
//Toast.makeText(getApplicationContext(), "This button is clicked"+i+more[i].getText()+itemList.getLink().get(i),Toast.LENGTH_LONG).show();
}
}
You can use setTag() and getTag() method of View to identify different button.
for (i = 0; i < itemList.getTitle().size()-1; i++) {
...
more[i].setTag(i); // Use index of itemList as the tag
}
In onClick:
int index = (Integer)arg.getTag();
you can also set the id of button
more[i].setid(i);
int index = 0;
for (i = 0; i < more.length; i++)
{
if (more[i].getId() == arg.getId())
{
index = i;
System.out.println("Value of i onclick is"+i);
}
}
As you can see here, i is still in your for loop.
Put the System.out.println("Value of i onclick is"+i); outside of your for loop and it should work
PS: format your code, it's easier to read that way and you'll notice small mistakes like these more easily
I think this will help you..
set button tag also dynamic like
more[i].setId(i);
and also changed condition like
if (more[i].getId() == i) {
index = i;
}
hope this will help you...
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.