Remove from arraylist - android

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…

Related

Android: Unable to call back buttonOnCklick [closed]

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

what is better way to organize onclicklistener? [duplicate]

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

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);

Bill Splitter Calculator Android App

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.

Show random xml files in Android

In my Android app i click on the "random" button and the app shows me a random xml file out of first.xml, second.xml or third.xml. This works all fine but i wondered if there is an easier or a nicer way to implement it if you have 100+ xml files.
I found some code (which works fine) which shows random ImageViews:
private Integer [] mImageIds = {
R.drawable.one,
R.drawable.two,
R.drawable.three,
};
private static final Random rgenerator = new Random();
private ImageView iv;
.
.
.
Integer q = mImageIds[rgenerator.nextInt(mImageIds.length)];
iv = (ImageView) findViewById(R.id.imageviewyeah);
iv.setImageResource(q);
This is how my main.xml looks:
<?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:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello"
/>
<Button
android:id="#+id/first_button"
android:onClick="change"
android:text="first"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/second_button"
android:onClick="change"
android:text="second"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/third_button"
android:onClick="change"
android:text="third"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="#+id/random_button"
android:onClick="change"
android:text="random"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
and this is the code which is processed when you click on a button:
package com.random;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void change(final View view){
switch (view.getId()) {
case R.id.first_button:
startActivity(new Intent(this, FirstPage.class));
break;
case R.id.second_button:
startActivity(new Intent(this, SecondPage.class));
break;
case R.id.third_button:
startActivity(new Intent(this, ThirdPage.class));
break;
case R.id.random_button:
Random random = new java.util.Random();
int rand = random.nextInt(3);
switch (rand) {
case 0:
startActivity(new Intent(this, FirstPage.class));
break;
case 1:
startActivity(new Intent(this, SecondPage.class));
break;
case 2:
startActivity(new Intent(this, ThirdPage.class));
break;
}
}
}
}
Any help is much appreciated!
Now I've got a fairly similar question. So far i implemented a "Random"-button. If you click on it a random xml-file will be shown. Note: The content (TextViews, ImageViews) are different in the xml-files but the java code (clicking on buttons etc.) is the same!
That's the code if you click on the "Random"-button:
switch (view.getId()) {
case R.id.first_button:
startActivity(new Intent(this, FirstPage.class));
break;
case R.id.second_button:
startActivity(new Intent(this, SecondPage.class));
break;
case R.id.third_button:
startActivity(new Intent(this, ThirdPage.class));
break;
case R.id.random_button:
Intent intent = new Intent(this, DisplayRandomPage.class);
startActivity(intent);
and this is in the DisplayRandomPage.class
public class DisplayRandomPage extends Activity {
private Integer [] mLinearLayoutIds = {
R.layout.one
R.layout.two,
R.layout.three
};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Random random = new java.util.Random();
int rand = random.nextInt(3);
setContentView(mLinearLayoutIds[rand]);
}
}
What i'd like to do is creating a DisplaySpecificPage.class. Above I've shown my main.class with the switch-case-clause. So when i click on the first button, it will start the FirstPage.class, clicking the second, it will start SecondPage.class, and so on. So for each xml-file i have to create a new java-class although the different java-classes do all the same. Only the xml-files are different. So i'd like to put something like this:
pseudo-code:
case R.id.first_button:
startActivity(new Intent(this, DisplaySpecificPage.class)) with R.layout.first_page;
break;
how do i pass the ID from the layout (R.layout.first_page) on?
If your classes all do the same thing except have a different layout called, you could create a single display class
public class DisplayPage extends Activity
and send it the id of the layout in the intent extras.
You can get the id by doing something like
Class c = Class.forName("com.random.R$layout");
Integer iLayout = new Integer(c.getField("layout"+rand).getInt(new R.layout()));
(assuming your layouts are called layout1.xml, layout2.xml etc.)
Send it to your DisplayPage,
Intent intent = new Intent(this, DisplayPage.class);
intent.putExtra("Layout", iLayout);
startActivity(intent);
and get it back by doing something like
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// default value
int iLayout = R.id.main;
if (savedInstanceState != null)
{
iLayout = savedInstanceState.getInt("Layout");
}
else
{
Bundle extras = getIntent().getExtras();
if (extras != null)
{
iLayout = extras.getInt("Layout");
}
}
setContentView(iLayout);
}
You'll also want to override onSaveInstanceState to include that int so that, e.g., changing the screen orientation doesn't make it forget what it was showing.
try
{
Class c = Class.forName("com.random.R$layout");
Field[] aFields = c.getFields();
Random random = new Random();
boolean isUsableLayout = false;
Integer iLayout = 0;
while (!isUsableLayout)
{
int rand = random.nextInt(aFields.length);
iLayout = new Integer(c.getField(aFields[rand].getName()).getInt(new R.layout()));
if (iLayout != R.layout.main)
{
isUsableLayout = true;
}
}
Intent intent = new Intent(this, DisplayPage.class);
intent.putExtra("Layout", iLayout);
startActivity(intent);
}
catch (Exception e)
{
e.printStackTrace();
}

Categories

Resources