Bill Splitter Calculator Android App - android

I'm trying to create an Android app to help to calculate split the bill if let's say you're eating out in a party of 2 people or more.
You're supposed to enter the subtotal of the bill, enter the number of people in the party, enter applicable discount if any, there are 2 checkboxes for 7% tax, and 10% service charges if it hasn't been included in the bill yet. Finally you just need to click on the "calculate button" for the app to calculate how much each person has to pay.
My Questions are:
for subtotal, it's supposed to be double instead of int, but I'm not sure how to parse String into a double. Is there a way to do this?
I'm not sure if that is the best way to activate the Checkboxes for the tax and 10% tips
When I click on the calculate button, it is supposed to display the Toast message with the result of the calculation, but nothing appears. I'm not sure if the problem is with parseInteger, checkBoxes, or if the onClick method is wrong, or all of them.
Here's the code that I wrote:
package com.kevinw.BillSplitter;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class BillSplitter extends Activity implements OnClickListener {
/** Declares XML Widgets */
private EditText numberDiners;
private EditText enterAmount;
private EditText enterDiscount;
private CheckBox gst;
private CheckBox tips;
private CheckBox cess;
double result;
private Button calculate;
private TextView resultAmount;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Initialize Widgets
numberDiners = (EditText) findViewById(R.id.numberDiners);
enterAmount = (EditText) findViewById(R.id.EnterAmount);
enterDiscount = (EditText) findViewById(R.id.EnterDiscount);
calculate = (Button) findViewById(R.id.calculate);
//Initialize CheckBoxes
gst = (CheckBox) findViewById(R.id.cbCheck1);
gst.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (gst.isChecked()) {
result = result + (0.07 * result);
}
else {
result = result;
}
}
});
tips = (CheckBox) findViewById(R.id.cbCheck2);
tips.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (tips.isChecked()) {
result = result + (0.1 * result);
}
else {
result = result;
}
}
});
}
#Override
public void onClick(View v) {
//Initialize EditTexts
String amount = enterAmount.getText().toString();
int subtotal = Integer.parseInt(amount);
String diners = numberDiners.getText().toString();
int people = Integer.parseInt(diners);
String disc = enterDiscount.getText().toString();
int discount = Integer.parseInt(disc);
double discounted = discount / 100;
result = (1 - discounted) * (subtotal / people);
switch (v.getId()) {
case(R.id.calculate):
Toast.makeText(this, "The Amount a Person has to pay: $" + result, Toast.LENGTH_LONG).show();
break;
}
}
}
and if it helps, this is the XML code for the layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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/dinersView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"/>
<TextView
android:id="#+id/Enter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/dinersView"
android:layout_alignLeft="#+id/EnterAmount"
android:text="#string/enter"/>
<EditText
android:id="#+id/numberDiners"
android:layout_height="wrap_content"
android:layout_below="#+id/dinersView"
android:layout_width="100dip"/>
<EditText
android:id="#+id/EnterAmount"
android:layout_height="wrap_content"
android:layout_below="#+id/Enter"
android:layout_toRightOf="#+id/numberDiners"
android:layout_width="220dip"/>
<TextView
android:id="#+id/Discount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/EnterAmount"
android:layout_alignLeft="#+id/EnterAmount"
android:text="#string/discount"/>
<EditText
android:id="#+id/EnterDiscount"
android:layout_height="wrap_content"
android:layout_below="#+id/Discount"
android:layout_alignLeft="#+id/Discount"
android:layout_width="220dip"/>
<CheckBox
android:id="#+id/cbCheck1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/EnterDiscount" />
<CheckBox
android:id="#+id/cbCheck2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/cbCheck1" />
<TextView
android:id="#+id/gst"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/cbCheck1"
android:layout_alignTop="#+id/cbCheck1"
android:layout_alignLeft="#+id/enterDiscount"
android:layout_marginTop="10dip"
android:text="#string/GST"/>
<TextView
android:id="#+id/tips"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/cbCheck2"
android:layout_alignTop="#+id/cbCheck2"
android:layout_marginTop="10dip"
android:text="#string/tips"/>
<Button
android:id="#+id/calculate"
android:layout_below="#+id/cbCheck2"
android:layout_width="wrap_content"
android:text="#string/calculate"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"/>
</RelativeLayout>
Thank you for all of the help. Really appreciate it.

For string to double conversion you can use Double.valueOf("").
you need to add clicklistener to your calculator button, either add calculate.setOnClickListener(this);
or move your onClick code without switch case inside this block.
calculate.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
}
});

for subtotal, it's supposed to be double instead of int, but I'm not sure how to parse String into a double. Is there a way to do this?
Yes there is.
I'm not sure if that is the best way to activate the Checkboxes for the tax and 10% tips
That is not a question but, moving on, no, that is not the right way to write checkbox code.
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (gst.isChecked()) {
result = result + (0.07 * result);
} else {
result = result;
}
}
This code will not work as you expect it to. The price will just keep going up and up on each second tick of the checkbox. You may want to step through what will actually happen in your head or on paper and then try and rethink it.
When I click on the calculate button, it is supposed to display the Toast message with the result of the calculation, but nothing appears. I'm not sure if the problem is with parseInteger, checkBoxes, or if the onClick method is wrong, or all of them.
I think that you will find that the onClick function is never called because you have not called the setOnClickListener function. I think that might be the problem but I'm not sure.

Related

Android calculator with button click

I am trying to calculate a field named lblAnswer by adding values txtA + txtB. I am fairly new to the android development world and would like to know what is the best way of going about this. I have already added the necessarily edit fields to the GUI. I am now working in the java file to try and create the method. This method has been named doCalc. Here is what I have thus far.
public void doCalc()
{
lblAnswer = txtA + txtB;
}
It has been suggested that I add more code here is the full code. Thank you for that suggestion.
Here is the Java File.
package com.example.wattsprofessional;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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_main, menu);
return true;
}
public void doCalc()
{
lblAnswer = txtA + txtB;
Double.parseDouble(txtA.getText().toString());
lblAnswer.setText"t
}
and here is the xml file.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<EditText
android:id="#+id/txtA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="40dp"
android:ems="10"
android:hint="Write Here"
android:inputType="numberDecimal" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/txtB"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/txtA"
android:layout_below="#+id/txtA"
android:layout_marginTop="32dp"
android:ems="10"
android:hint="Second Here"
android:inputType="numberDecimal" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:text="#string/calculate"
android:onClick="doCalc"/>
<TextView
android:id="#+id/lblAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/button1"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="TextView" />
</RelativeLayout>
Your code is missing a few key components. Review your code, and review the one I have prepared below.
package com.example.wattsprofessional;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
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 {
private EditText txtA, txtB;
private Button button1;
// ^ we have declared these as fields up here so that we can access them throughout the page, past all the curly brackets
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtA = (EditText) findViewById(R.id.txtA);
txtB = (EditText) findViewById(R.id.txtB);
button1 = (Button) findViewById(R.id.button1);
// ^ this is where we initialize these. You did the xml correctly, but you still need to hook the java to it.
// it allows us to use any names and locations we like not just same ones.
// basically you say what it is (Button) and then use the following method to look for the id that you wrote in the xml
initButton();
// i made this listener so we'd have time. this is the oncreate method and is called instantly.
// if we called doCalc here, we'd have no time to put numbers in.
}
private void initButton() {
button1.setOnClickListener(new OnClickListener() {
// this one performs an action when our button is clicked. it performs whatever is below
#Override
public void onClick(View v) {
String strA = txtA.getText().toString();
String strB = txtB.getText().toString();
// we get our strings from our editexts. i think you know how to do this well.
Double dblAnswer = doCalc(strA, strB);
// ^we pass them to our method, it does all the heavy lifting for us. and spits an answer for us.
TextView lblAnswer = (TextView) findViewById(R.id.lblAnswer);
// this is a local variable, as opposed to a field. i made so you know that you can do it like this - with the whole line here
// the disadvantage is that we can't do anything to it outside of this curly bracket. but there are performs gains.
// in general it's wasteful to use fields when you can suffice with local variable
String answer = String.valueOf(dblAnswer);
// we get our answer and turn it to a string.
lblAnswer.setText(answer);
// finally we set our result to the textView.
}
});
}
public double doCalc(String a, String b) {
// a and b are both variables. they refer to the stuff we put in
double dblA = Double.parseDouble(a);
double dblB = Double.parseDouble(b);
// we're gonna make both of these numbers so we can add them. right now they're just text.
return dblA + dblB;
// ^ this statement means that this method will spit a number out when it's done which we can use however.
}
#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_main, menu);
return true;
}
}
In order to get a Double value from an EditText, you'll need to use Double.parseDouble(txtA.getText().toString()). To set the text, you can use lblAnswer.setText("text").
In addition, the easiest way to call this from a button would be to set its android:onClick attribute in the XML, such as android:onClick="doCalc".
EDIT: You also need to create references to your objects. Before your onCreate(), put:
EditText txtA;
EditText txtB;
TextView lblAnswer;
Then inside your onCreate() you need to initialize the objects:
txtA = new (EditText)findViewById(R.Id.txtA);
txtB = new (EditText)findViewById(R.Id.txtB);
lblAnswer = new (TextView)findViewById(R.Id.lblAnswer);

Android- How can I show text selection on textview?

I am implementing a epub reading app where I am using textview for showing text of epub. I want to select text from textview when user long presses on textview and then do multiple operations on selected text of textview like highlight etc..
So, How can I show those cursors to user to select text whatever user wants.
*I dont want to use EditText and make it look like textview. May be overriding textview is prefered.
*I have attached screenshot to explain what I am looking for-
This is asked long time ago, when I had this problem myself as well. I made a Selectable TextView myself for my own app Jade Reader. I've hosted the solution to GitHub. (The code at BitBucket ties to the application, but it's more complete and polished.)
Selectable TextView (on GitHub)
Jade Reader (on BitBucket)
Using the following code will make your TextView selectable.
package com.zyz.mobile.example;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
public class MainActivity extends Activity {
private SelectableTextView mTextView;
private int mTouchX;
private int mTouchY;
private final static int DEFAULT_SELECTION_LEN = 5;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// make sure the TextView's BufferType is Spannable, see the main.xml
mTextView = (SelectableTextView) findViewById(R.id.main_text);
mTextView.setDefaultSelectionColor(0x40FF00FF);
mTextView.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showSelectionCursors(mTouchX, mTouchY);
return true;
}
});
mTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mTextView.hideCursor();
}
});
mTextView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
mTouchX = (int) event.getX();
mTouchY = (int) event.getY();
return false;
}
});
}
private void showSelectionCursors(int x, int y) {
int start = mTextView.getPreciseOffset(x, y);
if (start > -1) {
int end = start + DEFAULT_SELECTION_LEN;
if (end >= mTextView.getText().length()) {
end = mTextView.getText().length() - 1;
}
mTextView.showSelectionControls(start, end);
}
}
}
It depends on the minimum Android version that you'd like to support.
On 3.0+, you have the textIsSelectable attribute on the TextView, which enables this behavior. E.g.:
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="#dimen/padding_medium"
android:text="#string/hello_world"
android:bufferType="spannable"
android:textIsSelectable="true"
android:textSize="28dip"
tools:context=".MainActivity" />
Below that, you best bet is to use an EditText that looks and behaves like a TextView (apart from the slection thing). Or you can implement this feature yourself using spans.

need help programming math between editText

I need help understanding how to accomplish math between different EditText views. I am not asking someone to write me the code but maybe explain what is involved to get this done.
I wanted to post a picture of this but as a new user I can not. Basicly I have a EditText for the following: Width, Length, Eave Height, Pitch.
I have ID's for all the TextViews I just dont know how to program the behind the scenes math involved to make them work. I do have the equations needed to perform the math just not sure where and how to put them in java.
Basicly I need the user to enter a number in each of the top 4 boxes. I need to use an equation to generate the answer that will be displayed in the "SQFT" box. The user will also input a number in a cost box which will generat a "Total" that needs to be displayed in a separate TextView.
Any help would be appreciated, even if it is to point me in a direction of a tutorial to get me started. Thanks for your help.
Just to show what type of math I need to use, below is the equation I use for excel to calulate.
(length+width)*(Eave+1)*2 + (((width/2)/12*Pitch)*(width/2)*2)
I'm not sure if you don't know how to extract the numbers entered in the EditTexts, how to actually do the math calculation, how to let the user initiate the calculate or how to present it.
I created a small demo that has 2 EditTexts, and a TextView that displays the sum of the numbers entered. The user does not need to press any buttons to perform the calculation, it is performed automatically every time the user updates the text (I assumed this is what you wanted).
Please note this code is not good code, it uses lots of internal anonymous classes etc but it supposed to demonstrate the mechanics of how to do this.
This is the main.xml layout file:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
<EditText
android:id="#+id/a"
android:hint="input a"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:minWidth="60dp"/>
<EditText
android:id="#+id/b"
android:hint="input b"
android:inputType="number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:minWidth="60dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="a+b = " />
<TextView
android:id="#+id/total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
</LinearLayout>
And this is the sample Activity:
package com.example;
import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;
import android.widget.TextView;
public class SumActivity extends Activity
{
private int a;
private int b;
private TextView totalOutput;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText inputA = (EditText) findViewById(R.id.a);
EditText inputB = (EditText) findViewById(R.id.b);
totalOutput = (TextView) findViewById(R.id.total);
inputA.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(int number)
{
a = number;
updateTotal();
}
});
inputB.addTextChangedListener(new TextChangedListener()
{
#Override
public void numberEntered(int number)
{
b = number;
updateTotal();
}
});
}
private void updateTotal()
{
int total = a + b; // This is where you apply your function
totalOutput.setText("" + total); // need to do that otherwise int will
// be treated as res id.
}
private abstract class TextChangedListener implements TextWatcher
{
public abstract void numberEntered(int number);
#Override
public void afterTextChanged(Editable s)
{
String text = s.toString();
try
{
int parsedInt = Integer.parseInt(text);
numberEntered(parsedInt);
} catch (NumberFormatException e)
{
Log.w(getPackageName(), "Could not parse '" + text + "' as a number", e);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
}
}

Calling a EditText field into focus

I have a EditText that I have set to invisible by default. I would like to make this box visible onclick of a ImageView, but cant find any documentation online to help me, how would I go about doing this?
In your xml
<EditText
android:id="#+id/my_edit_text"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_weight="1"
android:singleLine="true"
android:inputType="number"
android:visibility="gone"
android:paddingRight="8dp" />
In your Activity Class
import android.widget.Button;
import android.widget.EditText;
public class MyActivity extends Activity {
private EditText editTxt = null;
private Button myBtn = null;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.my_xml_layout);
editTxt = (EditText) findViewById(R.id.my_edit_text);
myBtn = (Button) findViewById(R.id.my_button);
myBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
editTxt.setVisibility(View.VISIBLE);
}
});
}
}
well instead of invisible you can make it disable. This way you can prevent it from user input. And it is very easy to enable or disable EditTex.
You can use JQuery to toggle display (display:none vs. display:block) on your EditText field. You probably want to start out with display:none on the EditTextBox. You will also need to have JQuery loaded in your page. Can't make it a detailed tutorial here so giving you enough to get to next level.
$jq(document).ready(function() {
$jq("#yourImageView").click(function(e) {
$jq("#yourEditTextBox").fadeToggle("slow", "linear");
});

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