I'm confused where to put this code so that the user will not go to the other page until he selected a radiobutton.
This is the code where I don’t know to put:
if(rda.isChecked() == true)
{
butNext.setEnabled(true);
}
if(rdb.isChecked() == true)
{
butNext.setEnabled(true);
}
if(rdc.isChecked() == true)
{
butNext.setEnabled(true);
}
else
{
butNext.setEnabled(false);
}
This is my whole code or MainAct.java:
List<Question> quesList;
int score=0;
int qid=0;
Question currentQ;
TextView txtQuestion;
RadioButton rda, rdb, rdc;
Button butNext;
RadioGroup radioGroup1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page);
DBase db=new DBase(this);
quesList=db.getAllQuestions();
currentQ=quesList.get(qid);
txtQuestion=(TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.rda);
rdb=(RadioButton)findViewById(R.id.rdb);
rdc=(RadioButton)findViewById(R.id.rdc);
butNext=(Button)findViewById(R.id.button1);
setQuestionView();
butNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<10)
{
currentQ=quesList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(MainAct.this, activity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void setQuestionView()
{
txtQuestion.setText(currentQ.getQUESTION());
rda.setText(currentQ.getOPTA());
rdb.setText(currentQ.getOPTB());
rdc.setText(currentQ.getOPTC());
qid++;
rda.setChecked(false);
rdb.setChecked(false);
rdc.setChecked(false);
//butNext.setEnabled(false);
}
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getANSWER().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}
if(qid<10)
{
currentQ=quesList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(MainAct.this, activity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
or inOnCheckChanged:
radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
butNext.setEnabled(true);
}else{
butNext.setEnabled(false);
}
}
});
You can simply call it OnCheckedChangeListener() method of your RadioGroup.
radioGroup1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup arg0, int arg1) {
// TODO Auto-generated method stub
if(rda.isChecked()||rdb.isChecked()||rdc.isChecked()){
butNext.setEnabled(true);
}else{
butNext.setEnabled(false);
}
}
});
For your query you simply need to start Intent only when this Radio button has been clicked.
For Ex: Use condition check which will insure that your radio box has been checked..
i.e
if( radio_b.ischecked()){
// start Intent over here
}else{
// Toast a message to user to select same
}
I hope this clears your doubt.
As far placing code is concerned then you can place same in onCreate(); Method only. That actually depends upon your need.
Cheers!
Related
This is my coding. I don't know how to validate the radio button. When I click the next button,it still can proceed eventhough the radio button is not clicked. Sorry for my bad English.Please help me. Thank you.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dengue_ques2);
radioGroup = (RadioGroup) findViewById(R.id.radioGroupDengue2);
yes2 = (RadioButton) findViewById(R.id.radioButtonQues2); //the answer is yes
no2 = (RadioButton) findViewById(R.id.radioButtonQues2No); //the answer is no
Next=(Button) findViewById(R.id.buttonNextQues2);
yes2.setSelected(true);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup radioGroup, int i) {
if (i == R.id.radioButtonQues2)
{
selectedType = yes2.getText().toString();
}
else if (i == R.id.radioButtonQues2No)
{
selectedType = no2.getText().toString();
}
/* this part does not work
else if (i == R.id.radioButtonQues2.isChecked(false) &&
i == R.id.radioButtonQues2No.isChecked(false))
{
Toast.makeText(this, "Please choose 1 answer",
Toast.LENGTH_SHORT).show();
}*/
}
});
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(dengueQues2.this, dengueQues3.class);
intent.putExtra("REST2", selectedType);
startActivity(intent);
}
});
}
public void onClickYes2 (View view)
{
Toast.makeText(this, "You have select 1 to 3 days.",Toast.LENGTH_SHORT).show();
}
public void onClickNo2 (View view)
{
Toast.makeText(this, "You have select 3 to 14 days.", Toast.LENGTH_SHORT).show();
}
You need to use the setChecked() method not the setSelected() method on the radio button.
Also you need to default selectedType = yes2.getText().toString(); since you are setting that as the default selection in onCreate().
yes2.setChecked(true);
selectedType = yes2.getText().toString();
EDIT showing how to use no default selection:
Next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yes2.isChecked() || no2.isChecked()) {
Intent intent = new Intent(dengueQues2.this, dengueQues3.class);
intent.putExtra("REST2", selectedType);
startActivity(intent);
} else {
Toast.makeText(this, "Please choose 1 answer",
Toast.LENGTH_SHORT).show();
}
}
});
I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}
the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files
I have couple of activities. On the mainActivity I have 4 buttons each leads to another activity.
On three of the activities I activate a thread which draws in a canvas and in each of them I have a button to return to the mainActivity. I have tried using:
Intent i = new Intent(getApplicationContext(), MainActivity.class);
// i tried also (theClassName.this,MainActivity.Class)
startActivity(i);
When I clicked on the return button, I did return to the mainActivity but the app stopped responding (it alerted me that the app isn't responding and I had to choose between waiting or exiting the app. Waiting doesn't help).
When I used
finish();
instead,
And clicked on the return button, I returned to the home screen of the device (went out of the app) but didn't exit it - I could still go back to the app using the task manager, and when I did it put me back in the activity I entered and not the mainActivity.
As I said I have 4 buttons on the mainActivity and when I use the fourth one it goes to another activity that doesn't activate a thread, it only has listView, and when I return from it to the mainActivity it does work.
How can I fix it? Thanks for the help
*when the problem occurs there is no error stack trace.
*if you need to see any code tell and I'll be happy to post it here
The code:
MainActivity:
public class MainActivity extends Activity {
Button classic;
Button vsPlayer;
Button vsComp;
// Button settings;
Button scores;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
classic=(Button) findViewById(R.id.Classic);
classic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ClassicActivity.class);
startActivity(i);
}
});
vsPlayer=(Button) findViewById(R.id.PlayerVSPlayer);
vsPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsPlayerActivity.class);
startActivity(i);
}
});
vsComp=(Button) findViewById(R.id.PlayerVSComp);
vsComp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,VsCompActivity.class);
startActivity(i);
}
});
/* settings=(Button) findViewById(R.id.Settings);
settings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
});
*/
scores=(Button) findViewById(R.id.Scores);
scores.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(MainActivity.this,ScoresActivity.class);
startActivity(i);
}
});
}//onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mains, menu);
return true;
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
MainActivity.this.finish();
}
}
-=------ some other activity:
public class ClassicActivity extends Activity {
Classic g;
ImageView left;
ImageView right;
ImageView up;
ImageView down;
TextView pause;
TextView back;
TextView scoretv;
LinearLayout surface;
LinearLayout screen;
LinearLayout stoped;
LinearLayout gameover;
ScoreDataSource sds;
Button no;
Button yes;
EditText name;
Button continueb;
Button leave;
//protected static TextView MyScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
v= new GameView1(this);
setContentView(v);
*/
setContentView(R.layout.activity_classic);
sds=new ScoreDataSource(this);
gameover=(LinearLayout) findViewById(R.id.gameover);
screen = (LinearLayout)findViewById(R.id.screen);
surface = (LinearLayout)findViewById(R.id.surface);
g= new Classic(this, surface);
surface.addView(g);
//MyScore=(TextView) findViewById(R.id.MyScore);
//MyScore.setText("My score:"+gv.getPoints());
left=(ImageView) findViewById(R.id.left);
right=(ImageView) findViewById(R.id.right);
up=(ImageView) findViewById(R.id.up);
down=(ImageView) findViewById(R.id.down);
left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="LEFT"&&g.snake.getDir()!="RIGHT"){
g.snake.Left();
}
}
});
right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="RIGHT"&&g.snake.getDir()!="LEFT"){
g.snake.Right();
}
}
});
up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="UP"&&g.snake.getDir()!="DOWN"){
g.snake.Up();
}
}
});
down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(g.snake.getDir()!="DOWN"&&g.snake.getDir()!="UP"){
g.snake.Down();
}
}
});
pause=(TextView) findViewById(R.id.Pause);
back=(TextView) findViewById(R.id.Back);
stoped=(LinearLayout) findViewById(R.id.stoped);
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getRunning()){
pause.setText("continue");
g.setRunning(false);
}
else{
pause.setText("pause");
g.setRunning(true);
new Thread(g.snakethread).start();
}
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
g.setRunning(false);
stoped.setVisibility(View.VISIBLE);
}
});
no=(Button) findViewById(R.id.no);
yes=(Button) findViewById(R.id.yes);
continueb=(Button) findViewById(R.id.Continue);
leave=(Button) findViewById(R.id.leave);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
name=(EditText) findViewById(R.id.name);
yes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
String date = df.format(c.getTime());
sds.open();
Score s=new Score(0,name.getText().toString(),date, g.getPoints(),"Classic");
s=sds.createScore(s);
sds.close();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
continueb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stoped.setVisibility(View.GONE);
g.setRunning(true);
new Thread(g.snakethread).start();
}
});
leave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
});
scoretv=(TextView) findViewById(R.id.scoretv);
screen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(g.getGameover()){
scoretv.setText("Your score is:"+g.getPoints());
gameover.setVisibility(View.VISIBLE);
g.setGameover(false);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
----ClassicActivity usus this activity:
public class Classic extends SurfaceView implements Runnable {
private boolean isRunning=false;
private final long FPS=8;//MAX is 16
final float scale = Resources.getSystem().getDisplayMetrics().density;
float PART_SIZE= 10*scale;
private SurfaceHolder holder;
Thread snakethread;
static SnakePlayer snake;
Arena a;
LinearLayout view;
Bitmap arena;
Food food1;
Boolean gameover;
int points;
Paint writePB=new Paint();
Paint writePR=new Paint();
public Classic(Context context,LinearLayout view) {
super(context);
this.gameover=false;
this.view=view;
this.a=new Arena(view,PART_SIZE,33,36,1,0);
this.food1=new Food(PART_SIZE,"GRAY");
points=0;
writePB.setColor(Color.BLACK);
writePB.setTextSize(PART_SIZE);
writePR.setColor(Color.RED);
writePR.setTextSize(PART_SIZE);
snakethread=new Thread(this);
holder= getHolder();
holder.addCallback(new SurfaceHolder.Callback(){
#Override
public void surfaceCreated(SurfaceHolder arg0) {
setRunning(true);
snakethread.start();
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,int arg3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
setRunning(false);
while(true){
try {
snakethread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
snake=new SnakePlayer(0+3*PART_SIZE, 0+3*PART_SIZE, "RIGHT",PART_SIZE,2,"RED","BLACK");
}
#SuppressLint("WrongCall")
#Override
public void onDraw(Canvas c) {
a.onDraw(c);
c.drawText("Your Score:"+points, 5*scale, 10*scale, writePB);
food1.drawFood(c);
snake.onDraw(c);
}
#SuppressLint("WrongCall")
#Override
public void run() {
long stepPerSecond=1000/FPS;
long startTime;
long sleepTime;
Canvas c = null;
while(isRunning){
startTime=System.currentTimeMillis();
c = null;
try{
c=this.getHolder().lockCanvas();
onDraw(c);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
AllChecks(c);
sleepTime= stepPerSecond-(System.currentTimeMillis()-startTime);
if(sleepTime>0)
try {
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(gameover){
try{
c=this.getHolder().lockCanvas();
c.drawText("GAMEOVER", 125*scale, 150*scale, writePR);
c.drawText("Touch Anywhere To Continue ", 87*scale, 162*scale, writePR);
}
catch(Exception e){
}
finally{
if(c!=null){
this.getHolder().unlockCanvasAndPost(c);
}
}
}
}
boolean firstTime=true;
public void AllChecks(Canvas c){
/*
* Call all the right function, to check if the snake has bumped in a wall, or eaten a food.
*/
if(Arena.WallCollision(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(snake.snakeCollisionNoHead(snake.getxLoc(), snake.getyLoc())){
setRunning(false);
gameover=true;
}
if(firstTime){
firstTime=false;
changeFoodLoc(food1);
}
if(food1.hasEaten(snake.getxLoc(), snake.getyLoc())){
changeFoodLoc(food1);
snake.Add();
points+=10;
}
}
public void changeFoodLoc(Food food){
/*
* if a snake has eaten a food it changes the location of the food randomly
*/
Random rnd = new Random();
food.x=(rnd.nextInt(32) + 3)*food.SIZE;
food.y=(rnd.nextInt(35) + 1)*food.SIZE;
if(snake.snakeCollision(food.getX(), food.getY()))
changeFoodLoc(food);
}
public void setRunning(boolean b){
isRunning=b;
}
public Boolean getRunning(){
return isRunning;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public Boolean getGameover() {
return gameover;
}
public void setGameover(Boolean gameover) {
this.gameover = gameover;
}
}
First I would try removing the override on the MainActivity for onPause - you do not need to call finish. In your second activity, if you want to go back to the MainActivity- call finish on the 2nd activity and it should go back to the MainActivity.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to set an onclicklistener for an imagebutton in eclipse. When clicked, the app should lead to the default contacts app. This is the code I have but I'm getting an error with the "}" brackets and I can't seem to figure out whats the problem. Can anyone help?
public class First extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
addButtonListener();
}
private void addButtonListener() {
// TODO Auto-generated method stub
//finding your image button
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}); //!!!!THE ERROR APPEARS UNDER THE } BRACKET ON THIS LINE!!!
}
#Override
public boolean onCreateOptionsMenu(Menu menu){
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
}
It is a simple Syntax Error. You have misplaced the end-parenthesis. Also, you have declared a method inside a method. The below code-block should be outside the method.
The correct should be:
#Override
public boolean onCreateOptionsMenu(Menu menu){
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
private void addButtonListener() {
// TODO Auto-generated method stub
//finding your image button
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
} // `);` moved from here to the line below
});
} // This little thingy was waaaaaay too far down. This is the end for one method
#Override
public boolean onCreateOptionsMenu(Menu menu){ // So here another method can start
//Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.first, menu);
return true;
}
Try this:
private void addButtonListener() {
// TODO Auto-generated method stub
//finding your image button
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}
});
}
change this:
private void addButtonListener() {
// TODO Auto-generated method stub
//finding your image button
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}); //!!!!THE ERROR APPEARS UNDER THE } BRACKET ON THIS LINE!!!
}
To this:
private void addButtonListener() {
// TODO Auto-generated method stub
//finding your image button
ImageButton btn1 = (ImageButton) findViewById(R.id.imageButton2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 1);
}
}); //!!!!THE ERROR APPEARS UNDER THE } BRACKET ON THIS LINE!!!
}
I have a radio button activity with 5 choices for the game. It's a quiz game, so the user can choose to play until he or she makes one error, two errors, tree, four and five errors. My question is....is it better to make 5 activities and 5 classes, so I can call intent of each activity when user check that radio button, or, is better to make one activity, for all five choices and depending on what user chose, to count until 1,2,3,4 or 5 errors? I know how do the first option, but I don't know how to do the second one. Here my choice activity:
public class Izbor extends Activity implements OnClickListener, OnCheckedChangeListener{
MediaPlayer buttonBack;
RadioButton rbDeset,rbDvadeset,rbNeogranicenoTriGreske,rbNeogranicenoJednaGreska,rbNeogranicenoPetGresaka;
Button dNazad, dStart;
RadioGroup rGrupa;
TextView tv1;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
addListenerOnButton();
}
private void addListenerOnButton() {
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanjeVrh = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
rbDeset = (RadioButton) findViewById(R.id.radio1);
rbDvadeset = (RadioButton) findViewById(R.id.radio2);
rbNeogranicenoJednaGreska = (RadioButton) findViewById(R.id.radio3);
rbNeogranicenoTriGreske = (RadioButton) findViewById(R.id.radio4);
rbNeogranicenoPetGresaka = (RadioButton) findViewById(R.id.radio5);
dNazad = (Button) findViewById(R.id.bNazad);
dStart = (Button) findViewById(R.id.bStart);
rGrupa = (RadioGroup) findViewById(R.id.radioGroup1);
buttonBack = MediaPlayer.create(Izbor.this, R.raw.back);
tv1 = (TextView) findViewById(R.id.tv1);
dNazad.setTypeface(dugmad);
dStart.setTypeface(dugmad);
rbDeset.setTypeface(dugmad);
rbDvadeset.setTypeface(dugmad);
rbNeogranicenoPetGresaka.setTypeface(dugmad);
rbNeogranicenoJednaGreska.setTypeface(dugmad);
rbNeogranicenoTriGreske.setTypeface(dugmad);
tv1.setTypeface(pitanjeVrh);
rGrupa.setOnCheckedChangeListener(this);
rbDeset.setOnClickListener(this);
rbDvadeset.setOnClickListener(this);
rbNeogranicenoJednaGreska.setOnClickListener(this);
rbNeogranicenoTriGreske.setOnClickListener(this);
rbNeogranicenoPetGresaka.setOnClickListener(this);
dStart.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(rbDeset.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.KVIZ"));
}else if(rbDvadeset.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.DVADESETPITANJA"));
}else if(rbNeogranicenoJednaGreska.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.TRIDESETPITANJA"));
}else if(rbNeogranicenoPetGresaka.isChecked()){
startActivity(new Intent("rs.androidaplikacijekvizopstekulture.NEOGRANICENOPETGRESAKA"));
}
}
});
dNazad.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
buttonBack.start();
finish();
}
});
}
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
And here is one activity where a user can play until 5 mistakes:
public class NeogranicenoPetGresaka extends Activity implements OnClickListener{
Button bIzlazIzKviza, bOdgovor1, bOdgovor2, bOdgovor3, bOdgovor4;
TextView question, netacniOdg, score;
int counter = 0;
int brojacPogresnihOdgovora = 0;
int brojacTacnihOdgovora = 0;
Runnable mLaunchTask = new Runnable() {
public void run() {
nextQuestion();
}
};
Runnable mLaunchTaskFinish = new Runnable() {
public void run() {
finish();
}
};
private class Answer {
public Answer(String opt, boolean correct) {
option = opt;
isCorrect = correct;
}
String option;
boolean isCorrect;
}
Handler mHandler = new Handler();
final OnClickListener clickListener = new OnClickListener() {
public void onClick(View v) {
Answer ans = (Answer) v.getTag();
if (ans.isCorrect) {
brojacTacnihOdgovora++;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.TACANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,1200);
}
else{
brojacPogresnihOdgovora++;
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.POGRESANODGOVOR");
startActivity(i);
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.neograniceno5gresaka);
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
Typeface pitanje = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
bIzlazIzKviza = (Button) findViewById(R.id.bIzlazIzKvizaN);
netacniOdg = (TextView) findViewById(R.id.tvBrojPitanjaN);
question = (TextView) findViewById(R.id.tvPitanjeN);
bOdgovor1 = (Button) findViewById(R.id.bOdgovorN1);
bOdgovor2 = (Button) findViewById(R.id.bOdgovorN2);
bOdgovor3 = (Button) findViewById(R.id.bOdgovorN3);
bOdgovor4 = (Button) findViewById(R.id.bOdgovorN4);
score = (TextView) findViewById(R.id.tvSkor2N);
bOdgovor1.setTypeface(dugmad);
bOdgovor2.setTypeface(dugmad);
bOdgovor3.setTypeface(dugmad);
bOdgovor4.setTypeface(dugmad);
bIzlazIzKviza.setTypeface(dugmad);
netacniOdg.setTypeface(dugmad);
question.setTypeface(pitanje);
score.setTypeface(dugmad);
nextQuestion(); //startuje prvo pitanje!
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
public void nextQuestion() {
TestAdapter mDbHelper = new TestAdapter(this);
mDbHelper.createDatabase();
try{ //Pokusava da otvori db
mDbHelper.open(); //baza otvorena
Cursor c = mDbHelper.getTestData();
List<Answer> labels = new ArrayList<Answer>();
labels.add(new Answer(c.getString(2), true));
labels.add(new Answer(c.getString(3), false));
labels.add(new Answer(c.getString(4), false));
labels.add(new Answer(c.getString(5), false));
Collections.shuffle(labels);
if(brojacPogresnihOdgovora < 5){
question.setText(c.getString(1));
bOdgovor1.setText(labels.get(0).option);
bOdgovor1.setTag(labels.get(0));
bOdgovor1.setOnClickListener(clickListener);
bOdgovor2.setText(labels.get(1).option);
bOdgovor2.setTag(labels.get(1));
bOdgovor2.setOnClickListener(clickListener);
bOdgovor3.setText(labels.get(2).option);
bOdgovor3.setTag(labels.get(2));
bOdgovor3.setOnClickListener(clickListener);
bOdgovor4.setText(labels.get(3).option);
bOdgovor4.setTag(labels.get(3));
bOdgovor4.setOnClickListener(clickListener);
//reset your next question and all four options here
netacniOdg.setText("" + brojacPogresnihOdgovora);
score.setText("Score: " + brojacTacnihOdgovora);
}
else{
Intent i = new Intent("rs.androidaplikacijekvizopstekulture.REZULTAT");
startActivity(i);
mHandler.postDelayed(mLaunchTaskFinish,4000);
}
}
finally{ // kada zavrsi sa koriscenjem baze podataka, zatvara db
mDbHelper.close();
}
bIzlazIzKviza.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
Considering that the choice is just a small setting to the same game I see absolutely no reason to create one class/activity for each choice, it would be sheer madness.
As for the settings part, just create a numeric only input field that accepts any amount of "errors" ( why not ? ).
OnClick get the input from this field, save the value to the intent extras and start the game with the intent. In the onCreate of the game read the intent extras and get the number of "tries"/"errors".
OK, I tried with onNewIntent, but I can only call one method, and I need at least 3. Here's the code in my choice activity with radio buttons(group):
public void onClick(View v) {
if(rbDeset.isChecked()){
Intent intent = new Intent(Izbor.this, Kviz.class);
intent.putExtra("myMethod", "nextQuestion");
startActivity(intent);
And here's my quiz activity:
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if(intent.getStringExtra("methodName").equals("nextQuestion")){
nextQuestion();
}
}
I tried with ELSE IF but it didn't work. My methods are named: nextQuestion(), nextQuestion2() and nextQuestion3(). These are pretty much same methods only with different counters (one for 10 questions, one for 20 and one for 30). Maybe I don't need 3 methods to do this but honestly I don't know other way to do that.