Android: Unable to call back buttonOnCklick [closed] - android

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
Actually I don't understand why it doesn't see the buttonOnClick listener?
public class GeneralActivity extends AppCompatActivity {
// with or without these lines below
private View.OnClickListener buttonOnClick = this.buttonOnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = (Button)findViewById(R.id.connect);
connect.setOnClickListener(buttonOnClick);
Button send = (Button)findViewById(R.id.sendall);
send.setOnClickListener(buttonOnClick);
}
boolean clicked = false;
public static String LICENCE = "";
public void buttonOnClick(View v) {
MessageBox.Show("Connect me");
Button b = (Button) v;
if (b.getId() == R.id.connect) {
MessageBox.Show("Connect me");
return;
Also,
In GeneralActivitry designer everything is written out - onClick for both buttons and this method referred to the GeneralActivity.
Pls, see the movie and tell me what's wrong now?
youtube.com/watch?v=heD9QGKtusY&feature=youtu.be
FULL CODE OF GENERALACTIVITY LAYOUT:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText
android:id="#+id/licence"
android:layout_width="match_parent"
android:layout_height="30pt"
android:ems="10"
android:hint="1SAT"
android:inputType="textPersonName"
android:layout_weight="0"
android:singleLine="true"
android:text="SATEST LICENCE NUMBER" />
<Button
android:id="#+id/connect"
android:layout_width="match_parent"
android:layout_height="30pt"
android:layout_weight="0"
android:onClick="buttonOnClick"
android:text="CONNECT" />
<LinearLayout
android:id="#+id/messages"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="vertical" />
<Button
android:id="#+id/sendall"
android:layout_width="match_parent"
android:layout_height="30pt"
android:layout_weight="0"
android:enabled="false"
android:onClick="buttonOnClick"
android:text="SEND2ALL" />
Well, I don't like this site exactly because of that kind of people who set -1 without any reason for that.. they just like shitters in that pages.
I explained my problem with MAXIMUM example and even VIDEO.. WHAT ELSE do you need to see to get the question clear? Idiots.
Ok, let they live, it is the shit policy of this site holders..
Now you read carefully what was my error:
When I implemented OnViewListener interface I forgot to mark the method onClick with #Override and another "BIG" mistake was that the handler name onClick I wrote from UPPER LETTER OnClick..
Actually that was my main mistake. Before publishing my Q here, I try to understand everything by myself, and I tried all of the suggestions that guys gave me.. but the
letter O and o
hmm you understood )))
I am 30 years in software developing, and these kind of mistakes are the hardest mistakes I have ever met. Same like brackets [ { jr (..
Thank you all for you help.. I'll set the Answer to the first one.. Thank you again.

you can use built it OnClick method to do this for you: here is an example of how to do it
just don't forget to implement View.OnClickListener in your Activity
`
public class GeneralActivity extends AppCompatActivity implements View.OnClickListener {
// with or without these lines below
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = findViewById(R.id.connect);
connect.setOnClickListener(this);
Button send = findViewById(R.id.sendall);
send.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.connect:
//TODO
break;
case R.id.sendall:
//DO something
break;
}
}
`

Option - 1: You have already set the onClick listener to button from xml, so no need to set it again from java code. Remove those line.
public class GeneralActivity extends AppCompatActivity {
// with or without these lines below
//private View.OnClickListener buttonOnClick = this.buttonOnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
....
//Button connect = (Button) findViewById(R.id.connect);
//connect.setOnClickListener(buttonOnClick);
//Button send = (Button) findViewById(R.id.sendall);
//send.setOnClickListener(buttonOnClick);
}
public void buttonOnClick(View v) {
MessageBox.Show("Connect me");
if (v.getId() == R.id.connect) {
MessageBox.Show("Connect me");
return;
} else if(v.getId() == R.id.sendall) {
//Add your logic here
}
}
}
Option - 2: If you want to set the listener from java code, then remove onClick attribute from xml and set it like below from code:
public class GeneralActivity extends AppCompatActivity {
boolean clicked = false;
public static String LICENCE = "";
private View.OnClickListener buttonOnClick = new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.connect:
// Your connect logic here
break;
case R.id.sendall:
// Your send all logic here
break;
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GlobalData.getInstance().gContext = this;
setContentView(R.layout.activity_general);
((TextView) findViewById(R.id.licence)).setText(MySettings.Values().LicenceNo);
Button connect = (Button) findViewById(R.id.connect);
Button send = (Button) findViewById(R.id.sendall);
connect.setOnClickListener(buttonOnClick);
send.setOnClickListener(buttonOnClick);
}
}

Solution:
public class MainActivity extends Activity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
Button one = (Button) findViewById(R.id.oneButton);
one.setOnClickListener(this); // calling onClick() method
Button two = (Button) findViewById(R.id.twoButton);
two.setOnClickListener(this);
}
//outside of your oncreate()
public void onClick(View v) {
switch (v.getId()) {
case R.id.oneButton:
// do your code
break;
case R.id.twoButton:
// do your code
break;
default:
break;
}
}
TIP: Enter new View. And then press Ctrl+Spacebar you will get the function auto generated.

Related

what is better way to organize onclicklistener? [duplicate]

This question already has answers here:
Multiple Buttons' OnClickListener() android
(11 answers)
Closed 7 years ago.
When you have many buttons in a view and all the button have listener. Your main activity gets dirty.
Anyone know how to organize listeners ?
Currently I used this way and implement onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
You could set the property:
android:onClick="buttonClicked"
in the xml file for each of those buttons, and use this in the java code:
public void buttonClicked(View view) {
if (view.getId() == R.id.button1) {
// button1 action
} else if (view.getId() == R.id.button2) {
//button2 action
} else if (view.getId() == R.id.button3){
//button3 action
}
}
You can implement onclicklistner for multiple buttons using swith case
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.firstButton:
// do your code
break;
case R.id.secButton:
// do your code
break;
case R.id.thirdButton:
// do your code
break;
......
default:
break;
}
}
Ya...It s the best way to use multiple onClickListener.
spotify =(Button)findViewById(R.id.spotifyBtn);
superDuoBtn = (Button) findViewById(R.id.superDuoBtn);
libraryBtn = (Button) findViewById(R.id.libraryBtn);
buildBiggerBtn = (Button) findViewById(R.id.buildItBiggerBtn);
capstoneBtn= (Button) findViewById(R.id.capstoneApp);
spotify.setOnClickListener(this);
superDuoBtn.setOnClickListener(this);
libraryBtn.setOnClickListener(this);
buildBiggerBtn.setOnClickListener(this);
capstoneBtn.setOnClickListener(this);
#Override
public void onClick(View v) {
Intent intent = null;
switch (v.getId()) {
case R.id.spotifyBtn:
intent = new Intent(this, SimpleSingleExample.class);
break;
case R.id.superDuoBtn:
intent = new Intent(this, CustomExample.class);
break;
case R.id.libraryBtn:
intent = new Intent(this, SequenceExample.class);
break;
case R.id.buildItBiggerBtn:
Toast.makeText(this, "Welcome", Toast.LENGTH_SHORT).show();
break;
}
if(intent!=null){
startActivity(intent);
}
}
If you want better way than you have to use Android Annotations, its simple and useful, you can find here
Add those View object references to some type of list, iterate through it usin a for-each loop, then call the setOnClickListener on each element which will reduce those lines to just 2 lines for you.
ArrayList <View> list = new ArrayList <>(spotify,superDuoBtn,libraryBtn, buildBiggerBtn, capstoneBtn);
for (View view : list) {
view.setOnClickListener(this);
}
The most obvious example of alternative approaches to solving a single problem seems to be the various ways you can handle button clicks. As far as I know, there are four different ways to add listeners for handling button clicks. If you know of other ways, please post a comment and share them with us.
Xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:text="Inner Class (btn1)" android:id="#+id/Button01"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<Button android:text="Anonymous Inner Class (btn2)"
android:id="#+id/Button02" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Implementing an Interface (btn3)"
android:id="#+id/Button03" android:layout_width="fill_parent"
android:layout_height="wrap_content">
</Button>
<Button android:text="Calling From XML Layout (btn4)"
android:id="#+id/Button04" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:onClick="btn4Listener">
</Button>
</LinearLayout>
in MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements View.OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//method 1 - uses an inner class named btn1Listener...
Button btn1 = (Button)findViewById(R.id.Button01);
btn1.setOnClickListener(btn1Listener);
//method 2 - use an anonymous inner class as a listener...
Button btn2 = (Button)findViewById(R.id.Button02);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn2 - uses an anonymouse inner class");
}
});
//method 3 - note that this class implements
//the View.OnClickListener interface
//which means that we must implement the onClick()
//method (which you'll find below)..
Button btn3 = (Button)findViewById(R.id.Button03);
btn3.setOnClickListener(this);
//method 4 - look at the method btn4Listener() below
}
//here's the inner class used as a listener for btn1...
private View.OnClickListener btn1Listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
showToastMessage("You clicked btn1 - uses an inner class named btn1Listener");
}
};
//here's a method that you must have when your activity implements the
//View.OnClickListener interface...
#Override
public void onClick(View v) {
showToastMessage("you clicked on a btn3, which uses this Activity as the listener");
}
//here's the handler for btn4 (declared in the xml layout file)...
//note: this method only works with android 2.1 (api level 7), it must be public and
//must take a single parameter which is a View
public void btn4Listener(View v) {
showToastMessage("You clicked btn4 - listener was set up in the XML layout");
}
private void showToastMessage(String msg){
Toast toast = Toast.makeText(this, msg, Toast.LENGTH_SHORT);
toast.show();
}
}

which one is best way to implements OnClickListener in Android? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
which one is best way to implements OnClickListener Interface in Android.
/*- First - */
public class EmployeeActivity extends Activity implements OnClickListener
{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnUpdate = (Button)findViewById(R.id.btnUpdate);
Button btnEdit = (Button)findViewById(R.id.btnEdit);
btnUpdate.setOnClickListener(this);
btnEdit.setOnClickListener(this);
#Override
public void onClick(View v) {
if (v == btnAddEmployee)
{}
if (v == btnUpdate)
{}
}
/- Second -/
public class EmployeeActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnUpdate = (Button)findViewById(R.id.btnUpdate);
Button btnEdit = (Button)findViewById(R.id.btnEdit);
btnUpdate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
btnEdit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
}
}
which one is best way to implements OnClickListener Interface in Android
This depends solely on what fits best for you as the developer. They all work the same and you even have another option to declare onClick in xml. I like the first especially if you will have multiple Buttons that you want to share functionality. But a better way to do the first is to switch on the id of the View being clicked. Something like
#Override
public void onClick(View v) {
int id = v.getId();
switch (id)
{
case R.id.btnUpdate:
// do work
break;
case R.id.btnEdit
// do work for edit button
break;
}
// put shared functionality code like starting an Activity, calling a method, etc...
}
The second I like to use if there is only one or two Buttons and they have completely different functionality. I think this way makes the code look more cluttered and messy if you have too many Buttons. But these all work the same and won't change the performance of your app.
Neither one is "better." Which one you use is a personal choice, and will depend on which one fits your coding style.
The advantage to the second method is that you can have a unique OnClickListener for each View. The advantage to the first option is that all of your onClick() code is in one place.
The first method is good.
But rather than if-else. use switch case.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnUpdate = (Button)findViewById(R.id.btnUpdate);
Button btnEdit = (Button)findViewById(R.id.btnEdit);
btnUpdate.setOnClickListener(this);
btnEdit.setOnClickListener(this);
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.btnUpdate:
//your work
break
}
Your first example is incorrect, you shouldn't compare the objects like that. You need to do something like:
switch(v.getId()) {
case R.id.yourButton:
...
}
They are both equivalent for the most part, except the second allocates a new object for each listener. If I have lots of buttons on one screen I like to organize it like you have in the first example to avoid more boilerplate code.
It depends upon the number of elements that you have in your current activity. I prefer the second method for few buttons (2 or 3). Any thing more than that I use first method and ofcourse with a switch statement.

android multiply button case switch

I have been looking at some posts and still I cannot get mine code to work (I am a beginner) .. I am just tring to use the toast with my two buttons with a case switch .. When compiling it just crashes .. one something has an idea ?
Code :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
TextView et = (TextView) findViewById(R.id.txtHeader);
Button btnAdd = (Button) findViewById(R.id.btnAdd);
Button btnDis = (Button) findViewById(R.id.btnDisplay);
btnAdd.setOnClickListener((OnClickListener) this);
btnDis.setOnClickListener((OnClickListener) this);
}
public void OnClick(View v) {
switch (v.getId()) {
case R.id.btnAdd:
// Toast msg = Toast.makeText(getBaseContext(), "Torben", Toast.LENGTH_LONG);
// msg.show();
break;
case R.id.btnDisplay:
// Toast msg1 = Toast.makeText(getBaseContext(), "Henriksen", Toast.LENGTH_LONG);
// msg1.show();
break;
default:
break;
}
}
I see two main problems:
((OnClickListener) this
Make sure your class implements OnClickListener because you never need to cast if you are actually implementing the interface.'
The declaration of the class should be something like:
public class MyActivity extends Activity implements OnClickListener
Then change OnClick to lowercase o.
#Override
public void onClick(View v) {
some log output would be helpful!
a wild guess is that your activiy does not implement OnClickListener, why else would you cast this to OnClickListener?
just check in your layout manifest that whether the buttons id are correct and given the same id which your are using and if it is then please update the question with the LogCat output.
And also check that the activity is defined in manifest because there is no mistake in your code to implemts the onclick listener for multiple buttons.
Enjoy!!
Example adding a button listener:
Button b = ((Button)findViewById(R.id.button_name));
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
//do something
}
});
and make sure the button is defined in your xml file with the id #+id/button_name or #id/button_name (just make sure they match)

Disable Button on click

I am newbie to the programming world and my knowledge is limited. Please excuse me if i ask any blunder.
My question is that.
I am creating an Activity which has START & STOP button. when user clicks on START button a service must start; and on STOP service must stop.
Now I want to disable my START button when i Click start button(service starts on click START button) and when clicks STOP button i want to see the START button as normal clickable button.
I have used .setEnabled(false) by creating the button object.
i need help...Thanks in advance
int count = 0;
if (count == 0) {
stop.setEnabled(false);
PlayButton.setEnabled(true);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.play:
count++;
play.setEnabled(false);
Toast.makeText(this, "Button Disabled", Toast.LENGTH_LONG).show();
Stopbutton.setEnabled(true);
break;
case R.id.stop:
Toast.makeText(this, "Button Disabled", Toast.LENGTH_LONG).show();
count--;
PlayButton.setEnabled(true);
stop.setEnabled(false);
break;
}
}
& check this link
How to disable an Android button?
You can also try:-
for button enable-
button.setClickable(true);
for button disable-
button.setClickable(false);
in the body of onclick
disable button1 as it get clicked
public void onClick(View v) {
if(v.getId() == R.id.button1)
{
Button btn = (Button)findViewById(R.id.buton1);
btn.setEnabled(false);
}
}
If you want to disable it from another class you can use this,
Button btn = ((MainActivity)context).findViewById(R.id.myButton);
btn.setEnabled(false); //or (true) to enable it
You must also declare 'context' at the beginning of your class
public class MyClass extends AppCompatActivity {
Context context;
I usually use it in my onPreExecute and onPostExecute when I need to perform an action and don't want a user to keep clicking the button.
#Override
protected void onPreExecute() {
//some actions to be performed or set before executing task
Button btn = ((MainActivity)context).findViewById(R.id.myButton);
btn.setEnabled(false);
}
#Override
protected void onPostExecute() {
//some actions to be performed or set after executing task
Button btn = ((MainActivity)context).findViewById(R.id.myButton);
btn.setEnabled(true);
}
With kotlin you disable a button on click with,
myButton.setOnClickListener {
it.isClickable = false // to disable clicking on button
it.isEnabled = false // to disable button
}
Don't forget that the view here is it
Try this:
MainActivity.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.view.View;
public class MainActivity extends Activity {
private Button start, stop;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button)findViewById(R.id.start);
stop = (Button)findViewById(R.id.stop);
start.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
start.setVisibility(View.GONE);
/* do something else */
}
});
stop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
start.setVisibility(View.VISIBLE);
/* do something else */
}
});
}
}
And your layout main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
android:id="#+id/start"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Start"
android:visibility="visible"
/>
<Button
android:id="#+id/stop"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Stop"
android:visibility="visible"
/>
If you wanna make the button invisible after button cleck then 1st disable it as vipin said and also add this .setVisibility(View.INVISIBLE); this will hide the button after the button click and when you want to again make it visible use this .setVisibility(View.VISIBLE);
NOTE: if you want the button to be invisible and not don't want it to consume the layout space it requires then you can use View.GONE instead of View.INVISIBLE
I hope I am clear.
more preferred solution is,
onclick(){
btn.setEnabled(false);
btn.setClickable(false);
//yourwork
myWork();
}
myWork(){
//your tasks.
btn.setEnabled(true);
btn.setClickable(true);
}
initialise onClickListener for the button.inside the fist button simply do setEnable() to false ..and from the second button click listener set setEnable to true
enjoy
You can call button.setOnClickListener(null); to cancel the event listner. Additionally you can change the background drawable to give it a disabled effect.
PS: Only try this solution when nothing else works.
myButton.setEnabled(false);
Timer buttonTimer = new Timer();
buttonTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
myButton.setEnabled(true);
}
});
}
}, 5000);
try this it,s work perfectly

Remove from arraylist

My code is this:
public class startgame extends Activity implements OnClickListener {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level1);
final Random rgenerator = new Random();
//setup the questions
List<String> questions1 = new ArrayList<String>();
questions1.add("Who is the actual CEO at Apple?");
questions1.add("Who is the actual CEO at Microsoft?");
questions1.add("Android is made by:");
String thequestion = questions1.get(rgenerator.nextInt(questions1.size()));
TextView question = (TextView)findViewById(R.id.textView1);
question.setText(thequestion);
questions1.remove(thequestion);
//Initialise the button variables
Button button1 = (Button)findViewById(R.id.button1);
Button button2 = (Button)findViewById(R.id.button2);
Button button3 = (Button)findViewById(R.id.button3);
Button button4 = (Button)findViewById(R.id.button4);
if (thequestion.equals("Who is the actual CEO at Apple?")) {
List<String> questions1res = new ArrayList<String>();
questions1res.add("Steve Jobs");
questions1res.add("Steven Sinofsky");
questions1res.add("Tim Cook");
questions1res.add("Steve Ballmer");
button1.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button1.getText());
button2.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button2.getText());
button3.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button3.getText());
button4.setText(questions1res.get(rgenerator.nextInt(questions1res.size())));
questions1res.remove(button4.getText());
}
}
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
case R.id.button2:
case R.id.button3:
case R.id.button4:
}
}
}
What id does is this:
Choose 1 question from that arraylist of questions. Create the buttons, and put the chosen question in a string, and show that string on the screen. If that string is 'Who is the actual CEO at Apple?' then randomly put Steve Jobs and all those answers on buttons.
What I want is this:
If the user presses the button that contains: 'Tim Cook' then:
Remove 'Who is the actual CEO at Apple?' from the questions list, and randomly chose another question from the ArrayList of questions, and randomly put the answers on the buttons (the same stuff I already did, just that is another question).
My problem is that I can't really have acces to the array to delete it,because all I got is the case when the button is pressed.I tried to make a function,but every time I execute the function,the list is always recreated....
Can someone correct the code for me? And add what is missing?
Put the code that displays a random question in a new method (let's call it displayNewQuestion()) and let questions1 be a field of your Activity class. displayNewQuestion will then be able to use the activity-wide question array, and the click handler can remove a question out of it.
Try to change the scope of the ArrayList (use a private member for example) to enable access from your onClick method… I assume you'll have to do the same with your adapter to tweak it to your needs.
Update:
A quick-and-dirty implementation (without adapter nor ViewHolder, etc.):
package com.stackoverflow.randomarray;
import java.lang.String;
import java.util.List;
import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SoRandomArray extends Activity implements View.OnClickListener {
private Random mRandom = new Random();
private List<String> mQuestionsList;
private String mCurrentQuestion = null;
private List<String> mAnswersList;
TextView mQuestionTv;
Button mButton1;
Button mButton2;
Button mButton3;
Button mButton4;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mQuestionsList = new ArrayList<String>();
mAnswersList = new ArrayList<String>();
initQuizData();
mQuestionTv = (TextView)findViewById(R.id.textView1);
// Retrieve the buttons declared by the xml layout
mButton1 = (Button)findViewById(R.id.button1);
mButton2 = (Button)findViewById(R.id.button2);
mButton3 = (Button)findViewById(R.id.button3);
mButton4 = (Button)findViewById(R.id.button4);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
mButton4.setOnClickListener(this);
shuffle();
}
private void initQuizData() {
mQuestionsList.add("Who is the actual CEO at Apple?");
mQuestionsList.add("Who is the actual CEO at Microsoft?");
mQuestionsList.add("Android is made by:");
mAnswersList.add("Steve Jobs");
mAnswersList.add("Steven Sinofsky");
mAnswersList.add("Tim Cook");
mAnswersList.add("Steve Ballmer");
}
private void shuffle() {
mCurrentQuestion = mQuestionsList.get(mRandom.nextInt(mQuestionsList.size()));
mQuestionsList.remove(mCurrentQuestion);
mQuestionTv.setText(mCurrentQuestion);
mAnswersList.add("Steve Jobs");
mAnswersList.add("Steven Sinofsky");
mAnswersList.add("Tim Cook");
mAnswersList.add("Steve Ballmer");
mButton1.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton1.getText());
mButton2.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton2.getText());
mButton3.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton3.getText());
mButton4.setText(mAnswersList.get(mRandom.nextInt(mAnswersList.size())));
mAnswersList.remove(mButton4.getText());
}
private boolean validateAnswer(String question, String answer) {
if(question.equals("Who is the actual CEO at Apple?")) {
if(answer.equals("Tim Cook")) {
return true;
} else {
return false;
}
} else if (question.equals("Android is made by:")) {
return false;
} else if (question.equals("Who is the actual CEO at Microsoft?")) {
if(answer.equals("Steve Ballmer")) {
return true;
} else {
return false;
}
}
return false;
}
public void onClick(View v) {
Toast toast;
if(validateAnswer(mCurrentQuestion, ((Button)findViewById(v.getId())).getText().toString())) {
toast = Toast.makeText(this, "Good!", Toast.LENGTH_SHORT);
} else {
toast = Toast.makeText(this, "Too bad!", Toast.LENGTH_SHORT);
}
if(mQuestionsList.size()>0) {
toast.show();
shuffle();
} else {
toast.show();
}
}
}
The associated layout main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="#+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, SoRandomArray"
/>
<Button
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button2"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button3"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text=""
/>
<Button
android:id="#+id/button4"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="" />
</LinearLayout>
You'll have to correct some issue with the randomizing of the buttons, that's not state-of-the-art but that's the idea and it will give you a start…

Categories

Resources