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.
Related
I'm just a beginner in coding using Android studio and I have a couple of questions in coding a calculator (The calculator is used to only compute carbon emissions so it varies a little bit compared to an actual calculator):
How do I have a clear all button?
How do I add all of the
products that the user has calculated and show its sum? (Kind of like
how those tracking expenses kind of app)
This is my code so far:
package com.carschoolingpromo.scires.carschooling;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Calculator extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
Button caremissionscheck = findViewById(R.id.checkcar);
caremissionscheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent tocarbonemissions = new Intent(Calculator.this, CarbonEmissions.class);
startActivity(tocarbonemissions);
}
});
Button distancecheck = findViewById(R.id.checkdestination);
distancecheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkdistance = new Intent(Calculator.this, DistancesList.class);
startActivity(checkdistance);
}
});
final Button multiply =(Button)findViewById(R.id.multiply);
final EditText num1 =(EditText)findViewById(R.id.carboninput);
final EditText num2 =(EditText)findViewById(R.id.distanceinput);
final TextView ans =(TextView)findViewById(R.id.answer);
final TextView carbontotal=(TextView)findViewById(R.id.sumofcarbon);
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
double n1 = Double.parseDouble(num1.getText().toString());
double n2 = Double.parseDouble(num2.getText().toString());
ans.setText(String.valueOf(n1*n2));
}
});
}
}
How do I have a clear all button?
You need to create a new button in the layout file, and get a reference of it in your code, then set a click listener on that reference. Then in the onClick() implementation you will clear your 2 edit texts and 2 text views, something like this:
final Button clearAll =(Button)findViewById(R.id.clear_all);
clearAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
num1.setText("");
num2.setText("");
ans.setText("");
carbontotal.setText("");
}
});
How do I add all of the products that the user has calculated and show its sum? (Kind of like how those tracking expenses kind of app)
For this you need to use some sort of a way to show a list on your UI, I suggest you look into this tutorial by google to creating lists
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 !!
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());
}
}
}
I am pretty new to this and are not entirely sure why I am having this problem. From my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioButton wavelength1;
RadioButton wavelength2;
double ray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wavelength1 = (RadioButton) findViewById(R.id.lowave);
wavelength2 = (RadioButton) findViewById(R.id.hiwave);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
If (wavelength1.isChecked());{
ray = 0.7125;
}
If (wavelength2.isChecked());{
ray = 0.4436;
}
Toast.makeText(MainActivity.this, String.valueOf(ray), Toast.LENGTH_LONG).show();
}
private void If(boolean checked) {
// TODO Auto-generated method stub
}
});
}
}
When I click on either radio boxes, the same output is given in the toast (as 0.4436) when they should be different. I am really at a loss to know what is going on. The app is aimed at API 10 and I am using Eclipse. (I am sure I am missing something).
Remove semicolor(;) at the end of if statement
If (wavelength1.isChecked()); < -- remove this
And also
use small (i) if it is method If();
remove this method
private void If(boolean checked) {
}
sorry if this has been asked, i searched but didnt find anything. I am making a form in android and have some Checkboxes that i want to pass on if they are checked or not.
so i made the checkboxes and casted the view to checkbox so it will check any of the checkboxes i click on(Havent added the checkbox listeners yet). The problem is, when it determines a checkbox is checked i want to make the boolean that is for that box be true
EG when you tick the buy checkbox, i want the isbuyable boolean set to true. is this possible without the use of many if statements to set each one?
I made the string variable nameofboolean which is the name of the boolean to change the state but not sure how to actually change that boolean now without a multitude of IF statements checking each one.
EDIT: To clarify, all i want is to set the boolean matching each checkbox to be set to true when the checkbox is checked. I just dont want to use a lot of IFs to do it if possible.
package com.Assist.assistme;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
import android.widget.TextView;
public class market extends Activity implements OnItemSelectedListener
{
//UI elements
TextView choose;
Spinner list;
TextView buyrent;
CheckBox buyable;
CheckBox rentable;
TextView type;
CheckBox hard;
CheckBox soft;
CheckBox ebook;
TextView condition;
CheckBox new_book;
CheckBox used_book;
Button search;
String course_chosen;
Boolean isbuyable;
Boolean isrentable;
Boolean ishard;
Boolean issoft;
Boolean isebook;
Boolean isnew_book;
Boolean isused_book;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.market);
iteminit();
OnClickListener checkboxlistener = new OnClickListener()
{
#Override
public void onClick(View v)
{
if(((CheckBox) v).isChecked())
{
String nameofboolean = "is" + v.toString();
}
}
};
}
private void iteminit()
{
choose = (TextView)findViewById(R.id.market_choose);
buyrent = (TextView)findViewById(R.id.market_buyrent);
buyable = (CheckBox)findViewById(R.id.market_buy);
rentable = (CheckBox)findViewById(R.id.market_rent);
type = (TextView)findViewById(R.id.market_type);
hard = (CheckBox)findViewById(R.id.market_hardcover);
soft = (CheckBox)findViewById(R.id.market_softcover);
ebook = (CheckBox)findViewById(R.id.market_ebook);
condition = (TextView)findViewById(R.id.market_condition);
new_book = (CheckBox)findViewById(R.id.market_new);
used_book = (CheckBox)findViewById(R.id.market_used);
search = (Button)findViewById(R.id.market_search);
list = (Spinner)findViewById(R.id.market_list);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.course_choices, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
list.setAdapter(adapter);
list.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,
long id)
{
course_chosen = parent.getItemAtPosition(pos).toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0)
{
}
}
Thanks in advance
If I understand your question, you want something like this
CheckBox buyable,rentable,hard,soft,ebook,condition,new_book,used_book;
CheckBox[] checklist={ buyable,rentable,hard,soft,ebook,condition,new_book,used_book};
int ids[]={R.id.market_buy,R.id.market_rent,R.id.market_hardcover,R.id.market_softcover,R.id.market_ebook,R.id.market_new,R.id.market_used};
in onCreate after set contentView
for(int i=0;i<checklist.length;i++)
{
checklist[i]=findViewById(ids[i]);
}
Call this method like this
String data=getAllcheckedValues();
Get all the checked values
public String getAllCheckedValues()
{
String checkItems="";
for(int i=0;i<checklist.length;i++)
{
if(checklist[i].isChecked())
{
checkItems+=checkItems+checklist[i].getText()+"is Checked"+"\n";
}
}
return checkItems;
}
Format the string according to your requirement.