Array of android buttons - android

Can't work out a way to make an array of buttons in android.
This is the code I have tried but I'm getting a java.lang.NullPointerException.
private Button[] button = {(Button) findViewById(R.id.cGuess1),
(Button) findViewById(R.id.cGuess2),(Button)
findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};
Is this even possible?
EDIT:
Sorry everyone. Just realised my mistake!
I was trying to declare the array for my whole class and trying to get the views from the ids before onCreate so there was no setContentView(R.layout.game);
Sorry.

Since no one else posted actual code for a solution, here's a working snippet.
Button[] myButtons = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myButtons = new Button[]
{
(Button)findViewById(R.id.button1),
(Button)findViewById(R.id.button2),
(Button)findViewById(R.id.button3),
};
}

Just a guess as full code is not available here, have you called setContentView() before creating array.

Could you try
final Button[] button = {(Button) findViewById(R.id.cGuess1),
(Button) findViewById(R.id.cGuess2),(Button)
findViewById(R.id.cGuess3),(Button) findViewById(R.id.cGuess4)};

One of your buttons may be null. And putting a private keyword does not allow me to create the array. Also see that Firstly you are setting the cententView for your activity and then accessing these buttons.

public class main2 extends Activity{
final int[] button = {R.id.button1,R.id.button2,R.id.button3,R.id.button4,R.id.button5,
R.id.button6,R.id.button7,R.id.button8,R.id.button9,R.id.button10};
Button[] bt = new Button[button.length];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.sign);
for(int i=0;i<button.length;i++){
final Context context = this;
final int b = i;
bt[b]= (Button) findViewById(button[b]);
Typeface font = Typeface.createFromAsset(getAssets(), "Angkor.ttf");
bt[b].setTypeface(font);
bt[b].setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent myIntent = new Intent(context,r1.class);
startActivity(myIntent);
}
});
}
}
}

Related

Android - passing array through onClick

As part of my attempt to create a memory game, I have placed 12 image buttons on my layout with id names imageButton1...imageButton12. I wrote an algrorithm to create an array called cards[12] with random values to represent which card (card1..card6) is behind each imageButton, so for example if cards[5]=4 then the card behind imageButton6 is card4.
Now, i'm trying to tell the program to show the appropraite card when clicking the imageButton using the array. I'm very new to android studio and as I understood I first need to use OnClickListener on all the buttons, so I done it using a loop. This is my code so far:
public class Memory extends AppCompatActivity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
int i;
int[] cards = new int[12];
// Algorithm here
for(i=1;i<=12;i++) {
String name = "imageButton" + i;
int resID = getResources().getIdentifier(name, "id", "com.amir.supermemory");
ImageButton btn = (ImageButton) findViewById(resID);
btn.setOnClickListener(this);
}
Now comes the onClick function, which performs the action of switching the appropraite image when clicked. The problem is I can't manage to pass the array cards[] which I created before into the function (it says "cannot resolve symbol 'cards'"), how do I do that?
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageButton1:
ImageButton b = (ImageButton) findViewById(R.id.imageButton1);
String name = "card" + cards[0]; //cards is shown in red
int resID = getResources().getIdentifier(name, "drawable", "com.amir.supermemory");
b.setImageResource(resID);
break;
//copy paste forr all imageButtons
}
}
Any help is appreciated, thank you!
Because you are declaring your cards array locally in your OnCreate() you cannot access it in another method.
All you need to do is declare your cards array globally.
public class Memory extends AppCompatActivity implements OnClickListener{
int[] cards;
#Override
protected void onCreate(Bundle savedInstanceState) {
int i;
cards = new int[12];
...
}
You have declared cards[] as a local variable inside the onCreate method. Please declare it outside and try.
public class Memory extends AppCompatActivity implements OnClickListener{
int[] cards = new int[12];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_memory);
int i;
// Algorithm here
for(i=1;i<=12;i++) {
String name = "imageButton" + i;
int resID = getResources().getIdentifier(name, "id", "com.amir.supermemory");
ImageButton btn = (ImageButton) findViewById(resID);
btn.setOnClickListener(this);
}

Displaying a random string after each button press

Learning how to produce random numbers from arrays. The code will pick a random string during the onCreate method, but when the button is clicked there is no change to the string. Am I messing up the scope of my variables somehow? I really do not know what it wrong.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
}
public void onClick(View view){
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
TextView question = (TextView) findViewById(R.id.question);
question.setText(q);
}
});
}
}
First of all you haven't set click listener on button properly you made onClick method which is never called . Also you are getting the references of view multiple times you should do it like this.
public class MainActivity extends AppCompatActivity {
String[] qArray; //initialize qArray
private static final Random rgen = new Random(); //sets the new Random method to the keyword rgen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qArray = getResources().getStringArray(R.array.qArray); //grabs string array in the XML file
String q = qArray[rgen.nextInt(qArray.length)];//generates a random index of qArray to set to q
TextView question = (TextView) findViewById(R.id.question); //sets the TextView to "question"
question.setText(q); //sets the text in "question" to q
Button button = (Button) view.findViewById(R.id.button_click);
button.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
/*This should do the same thing as onCreate but each time
the button is pressed. I think the error is here.*/
String q = qArray[rgen.nextInt(qArray.length)];
question.setText(q);
}
});
}
}
You either need to set the onClickListener in xml (in which case you don't need to set the listener in code), or you need to set the listener in onCreate. Right now its being set in a function named onClick, which is never called.
First, you never set the onClickListeren. You have a method which adds one, but you never call it. Move the code in the onClick method to your onCreate method. This will probably fix your problem.
If not, don't make your Random final and add this to your #Override onClick():
rgen = new Random(System.currentTimeMillis());
This will use a different seed every time

Android change text color of button programmatically

I am creating button dynamically in linearlayout horizontalscrollview and on click i get selected button position.
I want to know how to change text color of selected button?
Here is my code.
String[] categories = {"SUN","MON", "TUS", "WED", "THU", "FRI", "SAT", "SUN","MON", "TUS", "WED", "THU", "FRI", "SAT"};
private LinearLayout ll;
Button btn;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.hsvLinearLayout);
for(int i = 0; i < categories.length; i++) {
btn = new Button(this);
btn.setText(categories[i]);
btn.setBackgroundColor(Color.parseColor("#ffffff"));
btn.setOnClickListener(buttonClick);
ll.addView(btn);
int idx = ll.indexOfChild(btn);
btn.setTag(Integer.toString(idx));
// btn.setId(idx);
}
}
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
//(String)v.getTag();
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
check the type and assign the text color
OnClickListener buttonClick = new OnClickListener() {
public void onClick(View v) {
String idxStr = Integer.toString(ll.indexOfChild(v));
if(v instanceof Button){
((Button)v).setTextColor(Color.parseColor("#000000"));
}
Toast.makeText(MainActivity.this, idxStr, 6000).show();
}
};
try this
Edited Answer
((Button)view).setTextColor(Color.parseColor("#000000"));
please check the following answer here and here .
as you can see you can do it programmatically and through xml by creating a style file for all of the states of the button .
Hope that helps
This works:
button.setTextColor(getColor(R.color.blue))
I just check all already posted solutions. No one works.
They also produce error like this
btnjava.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setTextColor(int)' on a null object reference
Real Solution :
Step-1: When you try to change setTextColor then always use try/catch, to prevent app from Crash.
Step-2: No matter you define your Button already, define(like R.id.btnId) again before setTextColor code line.
public class MainActivity extends AppCompatActivity {
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=findViewById(R.id.btnId);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// use try/catch for handle any kind of error
try {
Button btnForTextColorChange= (Button) findViewById(R.id.btnId);
// must define Button again before setTexColor code line
btnForTextColorChange.setTextColor(getResources().getColor(R.color.white));
} catch (Exception e){
Log.e(TAG, "Error:"+e);
}
}
});
}
[sorry for bad english]
Happy Coding :)
This worked for me:
btnItem.setTextColor(ContextCompat.getColor(context, R.color.black))

How to declare intent,class,buttons in one loop?

Why this doesn't work?
public class MainActivity extends Activity {
Button[] b = null;
Intent[] intent=null;
Class[] klasa;
Typeface font;
TextView glavninaslov;
ImageView plavi,ljubicasti;
AnimationDrawable plavian,ljubicastian;
String[] naslovi;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String[] naslovi = {"","First","Second","Third","Fourth","Fifth"};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
for(i=1;i<6;i++)
{
klasa[i]=Class.forName(naslovi[i]);//Problem is in:"Class not found exception"
intent[i] = new Intent(MainActivity.this,klasa[i]);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[i]);
gasenje();
}
});
}
Can anyone help me...?
Does anyone had similar problems?
Please help me...
The rest of code cannot affect on program... Please help me... I would appreciate it...
I have updated my code...it starts mainactivity but when i click on some button it crush app...
Button[] b = null;
Intent[] intent=null;
Typeface font;
TextView glavninaslov;
ImageView plavi,ljubicasti;
AnimationDrawable plavian,ljubicastian;
int i=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
font = Typeface.createFromAsset(getAssets(),"FatMarker.ttf");
b = new Button[]
{
( Button ) findViewById(R.id.button1),
( Button ) findViewById(R.id.button2),
( Button ) findViewById(R.id.button3),
( Button ) findViewById(R.id.button4),
( Button ) findViewById(R.id.button5),
};
intent = new Intent[b.length];
for(i=0;i<5;i++)
{
intent[i] = new Intent(MainActivity.this,naslovi[i]);
b[i].setTag(i);
b[i].setOnClickListener(new Button.OnClickListener() {
public void onClick(View v)
{
startActivity(intent[(Integer)v.getTag()]);
gasenje();
}
});
}
This code works...thanks guys
Update:
Rather than using reflection as you are to create these classes, as kcoppock suggested you should just do this:
Class[] naslovi = {
First.class,
Second.class,
Third.class,
Fourth.class,
Fifth.class};
And then in your loop:
intent[i] = new Intent(MainActivity.this, naslovi[i]);
Original Answer:
Assuming you have a classes called First, Second, etc, you need to include the package name:
String[] naslovi = {"",
"com.package.First",
"com.package.Second",
"com.package.Third",
"com.package.Fourth",
"com.package.Fifth"};
Replace com.package with the package for each class.
Also after you fix that, I foresee that you'll then get an IndexOutOfBoundsException - remove the blank "" element from naslovi, and change your for loop to for(i=0;i<5;i++)
The problem is that i will not be retained at the current value when the OnClickListener is executed. You can use the buttons' tag value to retain the proper value.
for (int i=0; i<b.length; i++) {
//existing logic
b[i].setTag(i);
b[i].setOnClickListener(new OnClickListener() {
public void onClick(View view) {
startActivity(intent[(Integer)view.getTag()]);
}
});
}

Button to transfer me to next page and start a game

It's hard to explain in the title. Basically as far as I can tell the submit button is taking the name and placing it in the array like I want. What I need now is for the Play(done) Button to transfer the user and the data to the next class (which I believe is coded correctly) and I need it to start a game. The game which you will see in the second class (get the data from the previous) I need it to display the names from the names array 1 at a time and randomly assign them a task to do from the tasks array.
Currently the app is force closing after I click the play button. I'm linking both classes cause I'm pretty sure the problem is in the second class. Thanks for your help ahead of time.
Class1
public class Class1 extends Activity
{
int players=0;
String names[];
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.class1);
final EditText input = (EditText) findViewById(R.id.nameinput);
final ArrayList<String> names = new ArrayList<String>();
Button submitButton = (Button) findViewById(R.id.submit_btn);
submitButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View submit1)
{
players++;
for(int i=0; i < 6; i++)
{
names.add(input.getText().toString());
input.setText("");
}
}
});
Button doneButton = (Button) findViewById(R.id.done_btn);
doneButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View done1)
{
Intent done = new Intent(Class1.this, Game.class);
Bundle bundle = new Bundle();
bundle.putStringArrayList("arrayKey", names);
done.putExtra("players", players);
//done.putExtra("names", names[players]);
startActivity(done);
}
});
}
Game Class
public class Game extends Activity
{
int players, counter=0, score, ptasks,rindex;
String[] names, tasks;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Bundle bundle = this.getIntent().getExtras();
String[] names = bundle.getStringArray("arrayKey");
Intent game = getIntent();
players = game.getIntExtra("players", 1);
//names = game.getStringArrayExtra("names");
Random generator = new Random();
tasks[0]= "";
tasks[1]= "";
tasks[2]= "";
tasks[3]= "";
tasks[4]= "";
tasks[5]= "";
tasks[6]= "";
tasks[7]= "";
tasks[8]= "";
tasks[9]= "";
while (counter <5)
{
for (int i = 0; i < players; i++)
{
TextView name1 = (TextView) findViewById(R.id.pname);
name1.setText( names[i]+":");
ptasks = 10;
rindex = generator.nextInt(ptasks);
TextView task = (TextView) findViewById(R.id.task);
task.setText( tasks[rindex]);
}
Button failButton = (Button) findViewById(R.id.fail_btn);
failButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View failed)
{
}
});
Button notButton = (Button) findViewById(R.id.notbad_btn);
notButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View notbad)
{
}
});
Button champButton = (Button) findViewById(R.id.champ_btn);
champButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View champp)
{
}
});
counter++;
}
}
Thought I should also mention that these buttons on the 2nd page I would like to assign a score to whichever name array person is up and keep track until the final round where it will display the winner. If anyone has any idea how to make that work.
Have you made sure to include the Game activity as an Application Node in your AndroidManifest?
If not, open your manifest to the application tab, on the bottom hit Add, and add an Activity of the name .Game
Without this, that intent never gets received by the other class.
You've already been told that you use non-initialized arrays here: EditText and using buttons to submit them. But also you're trying to get array extra, however you don't put it inside intent. And you're using uninitialized tasks array in Game class.

Categories

Resources