how to add back button In Quiz App? - android

Please Give Me some Solution to add back button in quiz app
What I want to create is back button in my quiz app, the questions come from database. I want button to go to previous question without messing up.I am new to android can any one help me to solve the problem..
package in.gtarena.myquizapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import in.gtarena.myquizapp.db.DBAdapter;
import in.gtarena.myquizapp.model.Question;
public class ComputerActivity extends AppCompatActivity {
private List<Question> questionsList;
private Question currentQuestion;
private TextView txtQuestion,tvNoOfQs;
private RadioButton rbtnA, rbtnB, rbtnC,rbtnD;
private Button btnNext,btnBack;
private RadioGroup grp;
private int obtainedScore=0;
private int questionId=0;
private int answeredQsNo=0;
ArrayList<String> myAnsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_concept);
init();
btnBack = (Button) findViewById(R.id.btnBack);
grp=(RadioGroup)findViewById(R.id.radioGroup1);
//Initialize the database
final DBAdapter dbAdapter =new DBAdapter(this);
questionsList= dbAdapter.getQuestions();
currentQuestion =questionsList.get(questionId);
//Set question
setQuestionsView();
//Check and Next
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
Log.e("Answer ID", "Selected Positioned value - "+grp.getCheckedRadioButtonId());
if(answer!=null){
Log.e("Answer", currentQuestion.getANSWER() + " -- " + answer.getText());
//Add answer to the list
myAnsList.add(""+answer.getText());
if(currentQuestion.getANSWER().equals(answer.getText())){
obtainedScore++;
Log.e("comments", "Correct Answer");
Log.d("score", "Obtained score " + obtainedScore);
}else{
Log.e("comments", "Wrong Answer");
}
if(questionId < dbAdapter.rowCount()){
currentQuestion =questionsList.get(questionId);
setQuestionsView();
}else{
Intent intent = new Intent(ComputerActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", obtainedScore);
b.putInt("totalQs", questionsList.size());
b.putStringArrayList("myAnsList", myAnsList);
intent.putExtras(b);
startActivity(intent);
finish();
}
}else{
Log.e("comments", "No Answer");
}
//Need to clear the checked item id
grp.clearCheck();
}//end onClick Method
});
//Check and Back
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//WHAT SHOULD I DO HERE FOR GO BACK TO PREVIOUS QUESTION//
}
});
}
public void init(){
tvNoOfQs=(TextView)findViewById(R.id.tvNumberOfQuestions);
txtQuestion=(TextView)findViewById(R.id.tvQuestion);
rbtnA=(RadioButton)findViewById(R.id.radio0);
rbtnB=(RadioButton)findViewById(R.id.radio1);
rbtnC=(RadioButton)findViewById(R.id.radio2);
rbtnD=(RadioButton)findViewById(R.id.radio3);
btnNext=(Button)findViewById(R.id.btnNext);
myAnsList = new ArrayList<String>();
}
private void setQuestionsView()
{
rbtnA.setChecked(false);
rbtnB.setChecked(false);
rbtnC.setChecked(false);
rbtnD.setChecked(false);
answeredQsNo=questionId+1;
tvNoOfQs.setText("Questions "+answeredQsNo+" of "+questionsList.size());
txtQuestion.setText(currentQuestion.getQUESTION());
rbtnA.setText(currentQuestion.getOptionA());
rbtnB.setText(currentQuestion.getOptionB());
rbtnC.setText(currentQuestion.getOptionC());
rbtnD.setText(currentQuestion.getOptionD());
questionId++;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Respond to the action bar's Up/Home button
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}

Are you using separate activity for every question?
If yes, then you can use onBackPressed method.

It would be easy for you to go back to question if you provide a id(ex.1,2,3..) for every question in database and take a variable named id and increment id every time you click the next button and fetch the question matching to the id and when you press back button the decrement id and fetch the question again...
Just decrement questionid in back button listener and call the questions again

You can do this by two approaches :
Create a button and than link that button to the previous activity
Create a method onBackPressed like this code :
#Override
public void onBackPressed() {
Intent intent = new Intent(OrderList.this, MainActivity.class);
startActivity(intent);
}
You can simply use the second code in any activity to lead you back to previous activity.
Hope this helps !!

Related

Switching activities (at the same time resetting text field) don't change smoothly

I'm working on an android app. I created log in form in one activity and after log in it switches to another activity. I'm trying to reset EditText field while switching activity but while clicking on login button, it shows the edittext box before switching. It should switch smoothly, not showing the text box. Below my code, what can I do to make better?
package com.mtilab.blogspot.imtiapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.content.Intent;
public class MainActivity extends AppCompatActivity {
private TextView messageRef;
private EditText usernameRef, passwordRef;
private Button submitRef, signupRef;
//user and pass for test case
private String user = "admin", pass = "admin";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageRef = (TextView)findViewById(R.id.loginTV);
usernameRef = (EditText)findViewById(R.id.usernameET);
passwordRef = (EditText)findViewById(R.id.passwordET);
submitRef = (Button)findViewById(R.id.loginB);
signupRef = (Button)findViewById(R.id.registrationB);
//submitref is ref of login button
submitRef.setOnClickListener(
new View.OnClickListener(){
public void onClick(View vw){
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
Intent userIntent = new Intent(MainActivity.this, User.class);
startActivity(userIntent);
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
} else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}
}
);
}
// way 2 , when login button pressed
/*public void onClickLoginButton(View view) {
messageRef = (TextView)findViewById(R.id.loginTV);
usernameRef = (EditText)findViewById(R.id.usernameET);
passwordRef = (EditText)findeViewById(R.id.passwordET);
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
Intent userIntent = new Intent(this, User.class);
startActivity(userIntent);
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
}else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}*/
}
You can hide all Views before starting the next activity:
submitRef.setOnClickListener(
new View.OnClickListener(){
public void onClick(View vw){
if(usernameRef.getText().toString().equals(user) &&
passwordRef.getText().toString().equals(pass)){
usernameRef.setVisibility(View.INVISIBLE);
passwordRef.setVisibility(View.INVISIBLE);
messageRef.setVisibility(View.INVISIBLE);
// you might want to keep that
usernameRef.setText("");
passwordRef.setText("");
messageRef.setText("");
Intent userIntent = new Intent(MainActivity.this, User.class);
startActivity(userIntent);
} else{
messageRef.setText("U R Not You!");
passwordRef.setText("");
}
}
}
);
Using View.INVISIBLE will just hide the View, but it will still occupy space in the layout. If you do not want that, use View.GONE.
For more info, see the documentation.

Android: Click on back button twice?

I am a beginner in android.
My Scenario
I have a screen A which has 2 buttons
Button A
Button B.
When I open my application screen A opens up with the above 2 buttons, when I click on Button B a textview and Edittext is displayed.
What I want ?
When the back button is pressed the textview and edittext should hide and when I press back again, I should exit out of Screen A.
What have I tried so far ?
Is my below code correct for what I want ?
Main Activity.xml
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity implements OnClickListener {
TextView title;
EditText userinput;
Button buttonA,buttonB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
userinput = (EditText)findViewById(R.id.userinput);
title = (TextView)findViewById(R.id.title);
buttonA = (Button)findViewById(R.id.buttonA);
buttonB = (Button)findViewById(R.id.buttonB);
buttonA.setOnClickListener(this);
buttonB.setOnClickListener(this);
}
#Override
public void onBackPressed() {
title.setVisibility(View.INVISIBLE);
userinput.setVisibility(View.INVISIBLE);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.buttonA:
break;
case R.id.buttonB:
title.setVisibility(View.VISIBLE);
userinput.setVisibility(View.VISIBLE);
break;
}
}
}
I referred this and this link but did not understand. If some one could help me in achieving me want I want 1
When the back button is pressed the textview and edittext should hide
and when I press back again,
#Override
public void onBackPressed() {
if (title.getVisibility() != View.VISIBLE &&
userInput.getVisibility() != View.VISIBLE) {
super.onBackPressed();
return;
}
title.setText(null);
userinput.setText(null);
title.setVisibility(View.INVISIBLE);
userinput.setVisibility(View.INVISIBLE);
}
Do like this.
#Override
public void onBackPressed() {
if(title.getVisibility()==View.VISIBLE)
{
title.setVisibility(View.INVISIBLE);
userinput.setVisibility(View.INVISIBLE);
}
else
{
finish();
}
}
Hop it will do what you want.
Change the code to below
#Override
public void onBackPressed() {
if (title.getVisibility() != View.VISIBLE &&
userInput.getVisibility() != View.VISIBLE){
title.setVisibility(View.INVISIBLE);
userinput.setVisibility(View.INVISIBLE);
}
super.onBackPressed();
}

How to assign a value to radio button in eclipse

I am developing an application that contains 10 set of questions. One questions belong to one page, thus i have 10 different pages. Each answer using radio button. I want to ask, how to assign value on radio button and bring along the value through the 10 pages and displays the result in the result page?
package com.project.logicalthinking;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.Button;
import android.widget.RadioGroup;
public class question1 extends Activity
{
private Button Button2;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.question1);
addListenerRadioButton() ;
//Button2
Button2 = (Button) findViewById(R.id.button1);
Button2.setOnClickListener((new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(),question2.class);
startActivityForResult(intent,0);
}
}
));
}
private void addListenerRadioButton() {
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radioGroup1);
radioGroup.setOnTouchListener(new OnTouchListener()
{
#SuppressLint("ClickableViewAccessibility")
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
});
}
;
}
I'm not an android guru (someone correct me if I'm wrong), but could you declare static variables for each activity that define which option was selected and then in the Results activity check the static variable values?
public static int QUESTION1_NO_ANSWER = 0;
public static int QUESTION1_ANSWER1 = 1;
public static int QUESTION1_ANSWER2 = 2;
public static int QUESTION1_ANSWER3 = 3;
public static int selectedAnswer;
Then in your results....
if(QUESTION1.selectedAnswer = QUESTION1_ANSWER2)
//YAY got question right!
} else {
//uh oh, it was wrong
}
You will need to populate the questions, one by one, as the user selects Yes/No using the radio button and pressing "Next". Yes/No could be a radio button and "Next" is just a Button. A new question is loaded in the OnClickListener of the "Next" button.

How to implement the prev and next button

I want to implement 2 activities , one is a listview with image and text which works well now. The other one is a onClicklistener when I click any ListItem it will start another activity to show more information, with 1 previous button and next button to see the Prev information or next. However there is something wrong with the button. It can only see the previous one and next one once. Which means you can't click the next button twice. Any suggestions will be appreciated .
Here is my main activity code
package com.example.manchesterunited;
import com.example.manchesterunited.R;
import android.os.Bundle;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Intent;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
static PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomAdapter adapter = new CustomAdapter(this);
setListAdapter(adapter);
}
public void onListItemClick(ListView l,View v, int pos, long id){
int playerId = (int)id;
Toast.makeText(getApplicationContext(),"Selected "+data.getName(pos),Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, InfoActivity.class);
intent.putExtra("playerId", playerId);
startActivity(intent);
}
}
And here is the second activity
package com.example.manchesterunited;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class InfoActivity extends Activity {
TextView dobText;
TextView pobText;
TextView internationalText;
Button prevButton;
Button nextButton;
PlayerData data = new PlayerData();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_info);
dobText = (TextView)findViewById(R.id.textView1);
pobText = (TextView)findViewById(R.id.textView2);
internationalText = (TextView)findViewById(R.id.textView3);
prevButton = (Button)findViewById(R.id.prev);
nextButton = (Button)findViewById(R.id.next);
Intent intent = getIntent();
final int playerId = intent.getExtras().getInt("playerId");
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId-1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_info, menu);
return true;
}
}
You're not updating the playerID.
You're just getting a new ID.
you should put
int newId = playerId+1;
playerID = newId; //insert this line
so that when you click again,
playerID gets updated.
You are always adding just 1 to player ID which will now point to next item. But as soon as you re-click the button it will have the same player ID that was passed through intent. So again it will add in the same value. Make a new variable which will store the current player ID that is visible and keep on incrementing it then you will be able to browse next and vice versa in the previous case.
You can't increment player ID as it has been declared as final, so you can either make a global variable or put a variable in intent and increment it on button clicks.
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
//make newId global then it will work. And keep on updating it when the button is clicked accordingly.
newId = playerId+1;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(newId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(newId).getPob()));
internationalText.setText("International:"+data.getPlayer(newId).getInternational());
}
});}
Try this on InfoActivity,
private int playerId;
...
...onCreate(...){
...
playerId = intent.getExtras().getInt("playerId");
prevButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId--;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
nextButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
...
playerId++;
dobText.setText("Birthdate:"+String.valueOf(data.getPlayer(playerId).getDob()));
pobText.setText("Birthplace:"+String.valueOf(data.getPlayer(playerId).getPob()));
internationalText.setText("International:"+data.getPlayer(playerId).getInternational());
}
}
}

Android: user login and stays in session until logout (which needs approval)

I would like to make sure that when user log in it will stay in session no matter what happens (crashed, shut down/power down/reboot, leaving the app) at same time the user info data will be sending with all the activities in the app to the webserver.
for example at the start up of the app, user login '9999' it goes to the main activity that have 5 diff. activities. user 9999 will send one activity (i.e. gps location) it will send that info to the webserver as user 9999 gps 123.234 123.123.
I want to ensure the users stays in session and also send its users data with the "activity" data sent.
I read this link
What is the most appropriate way to store user settings in Android application
I was still unable to put it together.
At the same time in the same main screen it has a logout. User needs manager approval to logout by inputting the code(i.e. 1234) to completely logout and for new user to input their id number. I want to know how to put the hardcode '1234' within the activity.
this code is my main screen after login to give you the idea
MainActivity.java
import android.app.ListActivity;
import android.content.Intent; import
android.os.Bundle; import
android.view.View; import
android.widget.ArrayAdapter; import
android.widget.ListView; import
android.widget.TextView;
public class Customer extends ListActivity {TextView selection;
CustomerListItem[] items ={
new CustomerListItem("Start Trip",StartTripActivity.class),
new CustomerListItem("Clock in",ClockinActivity.class),
new CustomerListItem("Customer Svc",CustomerSvcActivity.class),
new CustomerListItem("IndependentInspection",InspectionActivity.class),
new CustomerListItem("Pick Up", PickUpActivity.class),
new CustomerListItem("Log Out", LogoutActivity.class)};
private TextView resultsTxt;
#Override
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<CustomerListItem>(
this, android.R.layout.simple_list_item_1,
items));
selection = (TextView) findViewById(R.id.selection);
}
#Override
protected void onListItemClick(ListView l, View v,
int position, long id)
{
super.onListItemClick(l, v, position, id);
final Intent intent = new Intent(this,
items[position].getActivity());
startActivityForResult(intent, position);
}
#Override
protected void onActivityResult(int requestCode, int
resultCode, Intent intent)
{
super.onActivityResult(requestCode,
resultCode, intent);
if (resultCode == RESULT_OK)
{
// Perform different actions based on from which activity is
// the application returning:
switch (requestCode)
{
case 0:
// TODO: handle the return of the StartTripActivity
break;
case 1:
// TODO: handle the return of the ClockinActivity
break;
case 2:
// TODO: handle the return of the CustomerSvcActivity
case 3:
// TODO: handle the return of the InspectionActivity
break;
case 4:
// TODO: handle the return of the PickUpActivity
break;
case 5:
// TODO: handle the return of the LogoutActivity
break;
default:
break;
}
}
else if (resultCode == RESULT_CANCELED)
{
resultsTxt.setText("Canceled");
}
} }
UPDATE:
Login.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Login extends Activity {
private EditText etUsername;
private Button btnLogin;
private Button btnCancel;
private TextView lblResult;
/** Called when the activity is first created. */
//#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
etUsername = (EditText)findViewById(R.id.username);
btnLogin = (Button)findViewById(R.id.login_button);
btnCancel = (Button)findViewById(R.id.cancel_button);
lblResult = (TextView)findViewById(R.id.result);
btnLogin.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
// Check Login
String username = etUsername.getText().toString();
if(username.equals("guest")){
lblResult.setText("Login successful.");
Intent i = new Intent(getApplicationContext(), Customer.class);
startActivity(i);
} else {
lblResult.setText("Login failed. Username doesn't match.");
}
}
});
btnCancel.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
// Close the application
finish();
}
});
}
}
The link you included shows the way to store the user's ID - you can use SharedPreferences or you can store it in the database.
You can store the "approval code" anywhere. If you want to hard-code it, you may want to put it in a "static" helper class in a public static final String variable.

Categories

Resources