Android - can not get resources from XML - android

Android - get resources from XML
Hi,
I am developing an android app for a quiz game, the game has 24 questions, and each question has a String(question) and four ImageButton(answer), when user select the correctImageButton`, then they go to next question.
But the problem is, after selecting the first correct answer, the screen refreshes with a new question and a new set of images, but it freezes there, and no matter what I click, it will not go to next question. I have attached my code and any help appreciated!!
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_game);
// set variables
int fourImageId[] = { R.id.1_4a, R.id.1_4b,R.id.1_4c, R.id.1_4d };
questionText = (TextView) findViewById(R.id.question1);
questionList = getResources().getStringArray(R.array.question);
correctAnswerIdList = ListOfImages.getListOfCorrectImages();
imageIdList = ListOfImages.getListOfImages(); //two dimension array
// give values to four image buttons
for (int i = 0; i < 4; i++) {
fourImages[i] = (ImageButton) findViewById(fourImageId[i]);
final int temp = fourImageId[i];
fourImages[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (temp==correctAnswerIdList[index]){
questionText.setText(questionList[index]);
for (int i = 0; i < imageIdList[index].length; i++) {
fourImages[i].setImageResource(imageIdList[index][i]);}
index++;
}
}
});}

Your temp variable never changes after all the button click listeners are set. Because of this, the if (temp==correctAnswerIdList[index]) statement will only successfully execute once.

Your for (int i = 0; i < 4; i++) statement needs to execute once for each new question. Right now it only executes once, sets up the new question and image buttons, but your app doesn't know where to go from there.

Related

how do u add multiple fixed int from four buttons to an array

edit.
I'm trying to make a game where there is 4 buttons each button has a set value.
buttone is 1 buttontwo is 2 and so on.
and on each click of the button it takes the value from what ever button is pressed and add it to an array, the number of buttons that you have to press is set by the intent from the main activity and the buttons that have to be press is set by the randomNums array.
eg.
if the randomNums give you 1,2,1,1,2.3,3,4.
green button must be pressed 3 times
blue button must be pressed 2 times
yellow button must be pressed once.
buttonOne must be pressed 3 times.
buttonTwo must be pressed 2 times.
buttonThree must be pressed 2 times.
buttonFour must be pressed once times.
I have the randomNums which gives you the up to 12 number from 1-4.
I have the buttons set up so that if the randomNums gives you 1,1,1,2,3,3.
ButtonOne will be green buttonTwo will be yellow and buttonThree will be blue
for 3 seconds then all the buttons turn grey.
but where I'm having trouble is how do u set a button to have a set value.
eg.
if I press buttonOne 3 times it will enter into an array like so 1,1,1.
so the question is how do set a fixed value to a button so that every time it is press it send a fix value to an array.
sry if I was not clear the 1st times around if u have any more question or if you need me to explain it again or want to see the code that I have to set the color of the button play let me know . thanks
hi I'm very new to android studio,
I have 4 buttons and I want each to have a fixed value.
ButtonOne =1;
ButtonTwo =2;
ButtonThree =3;
ButtonFour =4;
and when a button is pressed I want to add that fixed button value to an array.
what I have is sending an ++ number back and not sending a fixed value.
so my question is how do you send a multiple fixed int from four buttons OnClickListener to an array?
public int counterOne = 0;
final Button buttons[] = {
(Button) findViewById(R.id.ButtonOne),
(Button) findViewById(R.id.ButtonTwo),
(Button) findViewById(R.id.ButtonThree),
(Button) findViewById(R.id.ButtonFour)
};
buttons[0].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counterOne = counterOne+1;
CheckSET.setText(""+counterOne);
}
});
final int pressed[] =new int [12];
end.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String stringlevel = ""+CheckSET.getText();
String b = "";
final int intLevel = Integer.parseInt(stringlevel);
for (int i = 0; i < 12;i++){
//b = ""+ b +""+ pressed[i];
//pressed[i] = pressed[i]+1;
//if(intLevel==1){
// pressed[i] = pressed[i]+1;
//}else if (intLevel ==2){
// pressed[i] = pressed[i]+2;
//}
pressed[0] = counterOne;
b = ""+ b +""+ pressed[i];
diff.setText(b);
}
}
});
the end button is to add all the button clicks to the array.
but if there is a better way then doing an end button to run the button array that would be great. could you do a for() and have all the buttons inside the for and each time they are pressed it adds it to the array?
I have a random array set up all ready that picks 12 numbers from 1-4 and does not let any number repeat more then 3 times.
private int[] pickNums() {
Random rand = new Random();
int randomNums[] = new int[12];
int one = 0;
int two = 0;
int three = 0;
int four = 0;
for (int i = 0; i < 12; i++) {
randomNums[i] = rand.nextInt(4)+1;
if (randomNums[i] == 1) {
one = one + 1;
if (one>3){
i=i-1;
}
} else if (randomNums[i] == 2) {
two = two + 1;
if (two>3){
i=i-1;
}
} else if (randomNums[i] == 3) {
three = three + 1;
if (three>3){
i=i-1;
}
} else if (randomNums[i] == 4) {
four = four + 1;
if (four>3){
i=i-1;
}
}
}
return randomNums;
}
my plan is to do a bubble sort on the randomNums and on the buttonPress array to see if the buttons that are pressed all ==.
but I'm having a lot of trouble with the buttonpress array
I am not sure what you asking but may be this will help you
(Instead of Array you should use list)
private List<Integer> pressedNums = new ArrayList<>();
Button button1,button2,button3,button4;
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pressedNums.add(1)
}
});
similarly for button2,3,4 add 2,3,4
at last you can use loop
int total = 0;
for(Integer i : pressedNums){
total += i;
}
textField.setText(Integer.toString(total));

Android: deleting programmatically added image buttons with ID's

hows it going? I'm creating a little training app for a project, its going fine except for a formatting problem im getting. So, ive a csv file with a name and age for a client. an array is created from this, then I've got a scroll View containing a grid layout and i create Image Buttons from the client array. that's all fine. ive got an add client button at the end of this, the button and its activity work fine, but when you come back to the main screen, the buttons are all screwed up (huge, misplaced etc). So i figured i would loop through and delete all the buttons and repopulate the main screen, except, since i programmatically created them, i cant figure out how to find them to delete them. i tried setting their id's to the index of the array, but then i get a null pointer error.
Function where the buttons are created:
public void fillActivity_main(){
if(listPopulated == false) { // check to see if its aready been created
populateClientList();//fill array with client objects
listPopulated = true;
}
//setup asset manager
AssetManager am = getApplicationContext().getAssets();
//Create the "GridLayout Image Board"
GridLayout buttonBoard = (GridLayout) findViewById(R.id.buttonboard);
int idealWidth = buttonBoard.getWidth(); //get width of the board
int idealHeight = buttonBoard.getHeight() / 2;//same
//create the Listeners, this is a place holder for now but will eventually use SetCurrentClient() (or maybe just switch to Start screen, with the current client?)
View.OnClickListener imageClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("CLICK AT: " + v.getId());
Client temp = clientList[v.getId()];
Intent i = new Intent(getApplicationContext(), DisplayClient.class);
System.out.println(temp.getName());
i.putExtra("name", temp.getName());
System.out.println(i.getStringExtra("name"));
i.putExtra("age", Integer.toString(temp.getAge()));
startActivity(i);
}
};
int j = 0; //used the keep track of the id's we set for the buttons
for (int i = 0; i < clientList.length; i++) {
if (clientList[i] != null) {
//creation and ID setting
ImageButton imgbutton = (ImageButton) new ImageButton(this);
imgbutton.setId(i);
//Layout shit
imgbutton.setImageResource(R.mipmap.ic_launcher);
imgbutton.setMinimumWidth(idealWidth);
imgbutton.setMinimumHeight(idealHeight);
imgbutton.setOnClickListener(imageClickListener);
//check and set image
if(clientList[i].getClientImage().equals(" ")) {
try{
imgbutton.set(am.openFd(clientList[i].getClientImage()));}
catch(Exception ex){
ex.toString();
}
Log.d("ClientImageCheck", "No picture found for " + clientList[i].getName());
}
buttonBoard.addView(imgbutton);
j++;
}
}
//create the new Client Button at the end of all the rest.
Button newClientButton = (Button) new Button(this);
newClientButton.setText("+"); // obvious
newClientButton.setLayoutParams(new LinearLayout.LayoutParams(GridLayout.LayoutParams.WRAP_CONTENT, GridLayout.LayoutParams.WRAP_CONTENT));
newClientButton.setWidth(idealWidth);
newClientButton.setHeight(idealHeight);
View.OnClickListener newClientListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), CreateClientForm.class);
startActivityForResult(i, 199);
//System.out.println("Doing good so far, leaving the createclient form bnut still in main");
}
}; // create listener
newClientButton.setOnClickListener(newClientListener); // assign listener
buttonBoard.addView(newClientButton); //add the button the buttonBoard, after all the clients have been added
}
Function where i do the deleting:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//Check which request we're responding to
if (requestCode == 199) {
// Make sure request was successful
if (resultCode == RESULT_OK) {
// The user made a name and crap.
Bundle extras = data.getExtras();
String name = extras.getString("name");
int age = extras.getInt("age");
Client temp = new Client(name, age);
addClientToArray(temp);
System.out.println(name + "attempted add to array");
}
for(int i = 0; i<clientList.length; i++ ){
View v = findViewById(i);
((ViewManager) v.getParent()).removeView(v);
}
fillActivityMain();
}
if i've got the logic right, the 'i' in the loop should be the appropriate id. Granted, the teach has kind of thrown us in the deep end for this project, never taken mobile apps or anything, so all this code is the result of me googling issues as i run into them. I've read the basics for Views, intents, etc, but there must be something i'm missing.
I've tried making the gridLayout that the buttons sit on a class variable so i could call it buttonBoard.removeView(i) or something.
ive also tried `
for(int i = 0; i<clientList.length; i++ ){
ImageButton btn = (ImageButton) findViewByid(i);
((ViewManager) v.getParent()).removeView(btn);
}
Can you add the replacement images at the same time that you delete the existing images? If so, try this:
for(int i = 0; i < buttonBoard.getChildCount(); i++) {
ImageButton tempButton = (ImageButton) buttonBoard.getChildAt(i);
tempButton.setVisibility(View.INVISIBLE);
buttonBoard.addView(yourImageButtonHere, i); //adds a new ImageButton in the same cell you are removing the old button from
buttonBoard.removeView(tempButton);
}
This approach should also prevent the GridLayout from rearranging where the children are. I believe the default behavior if you delete a child view is that the GridLayout will re-order the children so there is not empty cell at the beginning of the grid. I hope that makes sense.
There is so much wrong with this approach.
Mainly you don't have to create the ImageButtons manually and add them to the GridLayout. That is what recycled views such as GridView or RecyclerView are for. In fact you should use those to avoid OutOfMemoryError from having too much images in your layout.
But also you cannot just call setId(i) in the for loop. Android holds many ids already assigned and you can never be sure whether the id is safe. (Unless you use View.generatViewId())
And since you only want to remove all views added to your GridLayout why don't you just call removeAllViews() on the buttonBoard?

Not able to start multiple threads in my application

I am trying to create a simple wack-a-mole in android. I created an array of buttons. When users clicks "start" I want to start a thread for each button . This thread will toggle the button in on and off state. I coded the application in swing(java) it works well. I am trying the same in android but it is creating problems. Please suggest what is wrong. I am starting a thread for each button but the application terminates. If I just start only one thread for any particular button then it works fine.
EDIT: Even after hard coding the buttons thread it is crashing on the click. Nothing is displayed in the logcat.
Creating the buttons : all buttons are intialized I am able to click on them and their action perform is working. Code written in oncreate method.
int j=0;
for (int k = 0; k <ROWS; k++) {
TableRow row = new TableRow(this);
//inner loop:
for (int l = 0; l < COLS; l++) {
btn[j] = new Button(this);
TableRow.LayoutParams tr = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT);
layout.setWeightSum(12.0f);
tr.setMargins(left, top, right, bottom);
btn[j].setLayoutParams(tr);
row.addView(btn[j]);
j++;
}
EDIT: COde written on onclick() listener of start(some other button from above created buttons) button. If I start only one thread the application works, but crashes if I ret to create mutiple thread. Is it not the correct way of creating thread? I sont think ASYNCTASK is useful here but comments are welcome.
start.setOnClickListener(new Button.OnClickListener() {
EditText timer = (EditText) findViewById(R.id.time);
// Called when user clicks the start button
public void onClick(View v) {
Log.i("thread started for ", btn[0]+"");
ButtonsThread bt2 = new ButtonsThread(btn[0]);
bt2.start();
ButtonsThread bt3 = new ButtonsThread(btn[1]);
bt3.start();
ButtonsThread bt4 = new ButtonsThread(btn[2]);
bt4.start();
ButtonsThread bt5 = new ButtonsThread(btn[3]);
bt5.start();
ButtonsThread bt6 = new ButtonsThread(btn[4]);
bt6.start();
}});
Please suggest why this for loop is crashing the application.
Question 2: When I am creating the buttons in oncreate() method I want to attach a listener to them.
I created a class implementing onClickListener() and attached its object on all the buttons :
// this was the wrong code which I corrected now.
for (int k = 1; k < 10; k++) {
TableRow row = new TableRow(this);
//innerloop:
for (int l = 1,j=0; l < 4; j++,l++) {
btn[j] = new Button(this);
btn[j].setEnabled(true);
//listner class
Score scoreListener = new Score();
btn[j].setOnClickListener(scoreListener);
row.addView(btn[j]);
this is also causing the application to fail if I click any button.
This is the code of Thread class:
class ButtonsThread extends Thread {
Button moleButton;
ButtonsThread(Button b) {
this.moleButton = b;
Log.i(TAG,"buttone thread created"+b);
}
public void run() {
while (timerInLong > 0) {
Log.i("while","while loop ");
try {
MapLocation.this.runOnUiThread(new Runnable() {
#Override
public void run() {
moleButton.setEnabled(true);
moleButton.setText(":-)");
}
});
moleButton.runOnUiThread(new Runnable() {
#Override
public void run() {
moleButton.setEnabled(true);
moleButton.setText(":-)");
moleButton.setBackgroundColor(Color.BLUE);
}
});
Thread.sleep(1000);
moleButton.post(new Runnable() {
#Override
public void run() {
moleButton.setEnabled(false);
moleButton.setText(":-(");
moleButton.setBackgroundColor(Color.RED);
}
});
Thread.sleep(1000);
You're not consistent in your treatment of how many buttons are in your array:
In the "working" code you use btn[0].
In the "problem" loop you use btn[1], btn[2], btn[3], btn[4].
In the button creation loop you initialize btn[0], btn[1], btn[2] only, but you repeatedly reinitialize those elements with 9 different buttons each.
It's hard to make sense of this but it seems you're leaving btn[3] and btn[4] uninitialized, probably causing a NullPointerException when you start using them. (You've neglected to say what exception you're getting...)
Be careful with your loop conditions. Unless you want to treat specially the first element of an array you shouldn't write a loop of the form:
for (int k = 1; k < N; k++)
Much more often you'd want to start at 0:
for (int k = 0; k < N; k++)
or for some uses, start at 1 and use <= as the boundary condition:
for (int k = 1; k <= N; k++)
I can't answer your question 2 because you say you've post the score listener code and you haven't.

Switching images for slide show

I am trying to write a program for a slide show. So far I cannot figure out how to switch between images. Every time I write a loop, the only image that shows is the last one. What am I doing wrong
P.S. I know its bad code, I am playing around with it because I am new to images for android
int currentInt;
int imgid[] = { R.drawable.better, R.drawable.beyond_innovation,
R.drawable.innovation, R.drawable.jobs, R.drawable.no_limits,
R.drawable.praxis_name, R.drawable.reinvent,
R.drawable.single_source, R.drawable.toys_to_rockets,
R.drawable.design };
RefreshHandler refreshHandler = new RefreshHandler();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.slideshow);
this.txtStatus = (TextView) this.findViewById(R.id.pic_view1);
this.imageView = (ImageView) this.findViewById(R.id.slides);
for (int i = 1; i < 100000; i++) {
imageView.setImageResource(imgid[0]);
}
for (int i = 1; i < 100000; i++) {
imageView.setImageResource(imgid[1]);
}
It seems like you are putting all your images into a single ImageView and hence only the last one (which is on top) will be displayed.
If you want to make a slideshow, it is easily doable using ViewPager. I believe that's exactly the widget people want to use for displaying things using a slide show.

Where do I code Dynamically created android buttons and how do I pass value's to the listeners

So I am creating Dynamically Allocated Buttons. I want to query my database and based on the table the user selects (which are the dynamic buttons) a new activity will open that the user can work with the specified table.
protected void createButtons(){
// dynamically created buttons work just need to
LinearLayout scrViewButLay = (LinearLayout) findViewById(R.id.scrollViewLinLay);
scrViewButLay.removeAllViews();
ArrayList<String> tanks = new ArrayList<String>();
tanks = dbHand.getTableList();
Button[] tankButtons = new Button[tanks.size()];
Log.i("DB_Tag", "DB Size = " + tanks.size());
for(int i = 0; i < tanks.size(); i++){
Log.i("DB_NAME_TAG", tanks.get(i));
}
for (int index = 0; index < tanks.size(); index++) {
tankButtons[index] = new Button(this);
tankButtons[index].setText(tanks.get(index));
scrViewButLay.addView(tankButtons[index]);
tankButtons[index].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Each buttons specific event
/*
* Left off here
*/
Intent intent = new Intent(MainAquariumActivity.this, ProfilesOptionsScreen.class);
startActivity(intent);
//How would I send tanks.get(index) to the new ProfilesOptionsScreen
}
});
}
// end of dynamically allocated buttons
}
I am assuming that you have to dynamically create the onClickListeners along with creating the buttons. Is there a simpler solution to this?

Categories

Resources