I'm going to create the app which will take random 3 numbers from array String [] powerBalls with 5 numbers and will switch the image with picture to every number and then show the number and picture(e.g. string "1" from array powerballs will have the image with the name "o1"). The problem is that on the display I get the numbers and can see the picture as long as switch case will find the correct image. Then the app shutting down. The images are all the time visible and they should appear only with the random number. What is wrong with this code?
I have really no idea what I'm doing wrong and could not find some example for this program.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zufallsgenerator);
bindViews();
mGenerateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generateRandomNumbers();
}
});
}
public void generateRandomNumbers(){
Collections.shuffle(Arrays.asList(powerBalls));
mFirstNumber.setText(powerBalls[0]);
mSecondNumber.setText(powerBalls[1]);
mThirdNumber.setText(powerBalls[2]);
mFourthNumber.setText(powerBalls[3]);
mFifthNumber.setText(powerBalls[4]);
mSixthNumber.setText(powerBalls[5]);
switch (powerBalls[0]) {
case "1":
imageViewDice1.setImageResource(R.drawable.o1);
imageViewDice1 = (ImageView)findViewById(R.id.image_view_dice1);
break;
case "2":
imageViewDice2.setImageResource(R.drawable.o2);
imageViewDice2 = (ImageView)findViewById(R.id.image_view_dice2);
break;
case "3":
imageViewDice3.setImageResource(R.drawable.o3);
imageViewDice3 = (ImageView)findViewById(R.id.image_view_dice3);
break;
case "4":
imageViewDice4.setImageResource(R.drawable.o4);
imageViewDice4 = (ImageView)findViewById(R.id.image_view_dice4);
break;
case "5":
imageViewDice5.setImageResource(R.drawable.o5);
imageViewDice5 = (ImageView)findViewById(R.id.image_view_dice5);
break;
case "6":
imageViewDice6.setImageResource(R.drawable.o6);
imageViewDice6 = (ImageView)findViewById(R.id.image_view_dice6);
break;
}
switch (powerBalls[1]) {
case "1":
imageViewDice1.setImageResource(R.drawable.o1);
imageViewDice1 = (ImageView)findViewById(R.id.image_view_dice1);
break;
case "2":
imageViewDice2.setImageResource(R.drawable.o2);
imageViewDice2 = (ImageView)findViewById(R.id.image_view_dice2);
break;
case "3":
imageViewDice3.setImageResource(R.drawable.o3);
imageViewDice3 = (ImageView)findViewById(R.id.image_view_dice3);
break;
case "4": // and so on...*****
and on the end of the java class:
public void bindViews(){
mFirstNumber = (TextView)findViewById(R.id.firstNumber);
mSecondNumber = (TextView)findViewById(R.id.secondNumber);
mThirdNumber = (TextView)findViewById(R.id.thirdNumber);
mFourthNumber = (TextView)findViewById(R.id.fourthNumber);
mFifthNumber = (TextView)findViewById(R.id.fifthNumber);
mSixthNumber = (TextView)findViewById(R.id.sixthNumber);
mPowerBall = (TextView)findViewById(R.id.powerBall);
mGenerateButton = (Button)findViewById(R.id.mgenerateButton);
The example of the xml file with views:
<TextView
android:id="#+id/firstNumber"
android:layout_weight="1"
android:fontFamily="serif"
android:textSize="24sp"
android:padding="4dp"
android:layout_margin="8dp"
android:text="01"
android:textColor="#color/startblue"
android:layout_width="0dp"
android:layout_height="wrap_content" />
Thank you in advance for your suggestions and answers. Cheers
Related
I would like to do something like a small selection form.
I would like to do a click event where if I select one of the first radiogroup and another one of the second it takes me to a new activity.
I got two radiogroups with two radiobuttons inside each.
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/physic"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="physic"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/math"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="math"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton android:id="#+id/theories"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="theories"
android:onClick="onRadioButtonClicked"/>
<RadioButton android:id="#+id/problems_solving"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="problem solving"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
I declared my buttons and tried to use onRadioButtonClicked like below:
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
switch(view.getId()) {
case R.id.math:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showFirstWord("math problem resolution");
break;
case R.id.theories:
if (checked)
showSecondWord("math theories");
break;
}
break;
case R.id.physic:
if (checked)
switch(view.getId()) {
case R.id.problems_solving:
if (checked)
showThirdWord("physic problem solving");
break;
case R.id.theories:
if (checked)
showFourthWord("physic theories");
break;
}
break;
}
}
I want the strings in the functions to appear in a text view in the other activities like below:
private void showFirstWord (String text) {
Intent first_word = new Intent(this, FirstActivity.class);
first_word.putExtra("key", text);
startActivity(first_word);
}
private void showSecondWord (String text) {
Intent second_word = new Intent(this, SecondActivity.class);
second_word.putExtra("key", text);
startActivity(second_word);
}
private void showThirdWord (String text) {
Intent third_word = new Intent(this, ThirdActivity.class);
third_word.putExtra("key", text);
startActivity(third_word);
}
private void showFourthWord (String text) {
Intent fourth_word = new Intent(this, FourthActivity.class);
fourth_word.putExtra("key", text);
startActivity(fourth_word);
}
I tried to follow this page from Android developers but I'm still not sure what to do with it: https://stuff.mit.edu/afs/sipb/project/android/docs/guide/topics/ui/controls/radiobutton.html
My method doesn't seem to be correct ass I can't get the strings to appear in the other activities. Is my reasonning ok for now or should I study another method?
Thanks :)
You can simplified your code onRadioButtonClicked just create first a String variable called subjectSelected.
then:
private String subjectSelected = "";
public void onRadioButtonClicked(View view) {
RadioButton radioButton = (RadioButton) view;
switch(view.getId()) {
case R.id.math:
subjectSelected = radioButton.getText().toString();
break;
case R.id.physic:
subjectSelected = radioButton.getText().toString();
break;
case R.id.problems_solving:
if (subjectSelected.equals("math")) {
showFirstWord ("math problem resolution");
} else if (subjectSelected.equals("physic")) {
showThirdWord("physic problem solving");
}
break;
case R.id.theories:
if (subjectSelected.equals("math")) {
showSecondWord("math theories");
} else if (subjectSelected.equals("physic")) {
showFourthWord("physic theories");
}
break;
}
}
and to display the text you pass to another activity. Use a Bundle to get the value of your key.
e.g.:
public class FirstActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
Bundle bundle = getIntent().getExtras();
String key = bundle.getString("key");
TextView textView = (TextView) findViewById(R.id.textView1); // Replace the textView1 with the id you set to your textview.
textView.setText(key);
}
}
You can copy the codes of your FirstActivity and paste to your SecondActivity, ThirdActivity and FourthActivity to get the key.
String str; // store the text corresponding to the RadioButton which is clicked
switch(view.getId()) {
case R.id.radioButton1:
if (checked)
str = "button1Text";
break;
case R.id.radioButton2:
if (checked)
str = "button2Text";
break;
case R.id.radioButton3:
if (checked)
str = "button3Text";
break;
}
Intent intent = new Intent(this, WinderDTActivity.class);
intent.putExtra("radioChosen", str); // pass "str" to the next Activity
Help me guys , My Imageview touch listener not working.
imgShowNewAgain.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
cstmEdtNewPasswordAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
break;
case MotionEvent.ACTION_UP:
cstmEdtNewPasswordAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
break;
default:
break;
}
return true;
}
});
and my XML Code is
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal"
android:weightSum="1">
<com.CustomEditText
android:id="#+id/cstmEdtNewAgain"
style="#style/label_text_primary"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.1"
android:backgroundTint="#color/not_black_more"
android:hint="#string/new_password"
android:paddingBottom="#dimen/normal_padding"
android:paddingLeft="#dimen/most_min_padding"
android:paddingRight="#dimen/most_min_padding"
android:paddingTop="#dimen/normal_padding"
android:typeface="normal"
android:singleLine="true"
android:maxLines="1"
android:inputType="textPassword"
android:textCursorDrawable="#drawable/cursor_color"
app:font="#string/montserrat_regular"
tools:targetApi="lollipop" />
<ImageView
android:id="#+id/imgShowNewAgain"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.9"
android:clickable="true"
android:contentDescription="#string/showpasswordAgain"
app:srcCompat="#drawable/show" />
</LinearLayout>
Help will be appreciated.
I have updated complete XML layout. The only layout iam having is above xml. and i have initialize the layout and create the touchlistener for the Imageview. but event it is not working. i dont know where i made the mistake. or is there need to add some additional information on xml file. like , focusable=false etc..
You implement the onTouchListener like this also:
imageView.setOnTouchListener(this);
#Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;
switch (view.getId()){
case R.id.img1: // example id
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
}
break;
case R.id.img2: // example id
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_CANCEL:
break;
}
break;
}
return true;
}
try this and make log point in all case.
imgShowOld.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
cstmEdtNewPasswordAgain.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
break;
case MotionEvent.ACTION_UP:
cstmEdtNewPasswordAgain.setTransformationMethod(PasswordTransformationMethod.getInstance());
break;
case MotionEvent.ACTION_MOVE:
break;
case MotionEvent.ACTION_POINTER_UP:
break;
default:
break;
}
return true;
}
});
The answer everybody said is correct. I think that you might have problem in your code. I mean, not the listener code. Are you try to handle the any other views like linearlayout listener. That listener is disturbing you imageview. Like , suppose you try to hide the keyboard programmatically when the particular view focused. The same problem I have faced when I was toddle in android. Check that. Happy coding.
I am getting the value from DB and setting it to the respective button in the below format. Is there any optimised way to do the same. All these radio buttons are inside a radio group.
if (bundlevalue.get(3).equalsIgnoreCase("Mr.")) {
rg_nametitle.check(R.id.mr);
} else if (bundlevalue.get(3).equalsIgnoreCase("Mrs.")) {
rg_nametitle.check(R.id.mrs);
} else if (bundlevalue.get(3).equalsIgnoreCase("Ms.")) {
rg_nametitle.check(R.id.ms);
} else {
rg_nametitle.check(R.id.messrs);
}
You can try as follows...
String value = bundlevalue.get(3)
Resources res = getResources();
if (value.equalsIgnoreCase("Mr.") || value.equalsIgnoreCase("Mrs.") || value.equalsIgnoreCase("Ms.")) {
String[] splitedValue = value.toLowerCase ().split(".");
int id = res.getIdentifier(splitedValue[0], "id", getContext().getPackageName());
rg_nametitle.check(id);
} else {
rg_nametitle.check(R.id.messrs);
}
In case if you use XML attribute like this :
<RadioGroup
...
...
android:checkedButton="#+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>
or you can use switch-case statement like this :
public void onRadioButtonClicked(View view) {
// Is the button now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which radio button was clicked
switch(view.getId()) {
case R.id.radio_pirates:
if (checked)
// Pirates are the best
break;
case R.id.radio_ninjas:
if (checked)
// Ninjas rule
break;
}
}
Use switch statement. Although, there is nothing big difference in using if-else or switch, you can go ahead with whichever is more readable to you.
public enum Title
{
Mr, Mrs, Ms;
}
String title = bundlevalue.get(3).equalsIgnoreCase("Mr.");
switch(Title.valueOf(title)) {
case Mr:
rg_nametitle.check(R.id.mr);
break;
case Ms:
rg_nametitle.check(R.id.ms);
break;
case Mrs:
rg_nametitle.check(R.id.mrs);
break;
default:
break;
}
I am building a simple calculator, but for some reason, it crashes as soon as I press a button. Please help me out with it.
This is my Calculator.java class.
package com.dexter.seemab;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Calculator extends Activity{
String display="";
Character op = 'q';
int i,num,numtemp;
int check=0;
EditText rd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
rd=(EditText)findViewById(R.id.etResult);
}
public void btnClicked(View v){
switch(v.getId()){
case R.id.one:{
insert(1);
}
case R.id.two:{
insert(2);
}
case R.id.three:{
insert(3);
}
case R.id.four:{
insert(4);
}
case R.id.five:{
insert(5);
}
case R.id.six:{
insert(6);
}
case R.id.seven:{
insert(7);
}
case R.id.eight:{
insert(8);
}
case R.id.nine:{
insert(9);
}
case R.id.zero:{
insert(0);
}
case R.id.add:{
perform();
op='+';
}
case R.id.sub:{
perform();
op='-';
}
case R.id.product:{
perform();
op='*';
}
case R.id.difference:{
perform();
op='/';
}
case R.id.equals:{
calculate();
}
case R.id.clear:{
clear();
}
}
}
public void insert(int digit){
if (check==1){
clear();}
display=display+Integer.toString(digit);
num=Integer.valueOf(display).intValue();
rd.setText(display);
check=0;
}
public void perform(){
numtemp=num;
display=display+op.toString();
}
public void calculate(){
switch(op){
case '+':
i=num+numtemp;
case '-':
i=num-numtemp;
case '*':
i=num*numtemp;
case '/':
i=num/numtemp;
}
display=Integer.toString(i);
rd.setText("="+display);
check=1;
}
public void clear(){
op='q';
num=0;
numtemp=0;
i=0;
display="";
rd.setText(display);
}
}
my buttons contain an onClick listener which points to the method btnClicked(). Now whenever I press a button, the program of mine crashes. PLease help me out with it. Thanks.
There are some things that should cause your App to crash:
As you do not use break-statements at the end of your cases, every case from the one matching your button-id to the last statement (R.id.clear) will be executed. This certainly is unexpected behaviour that you should fix.
Further num / numtemp is wrong as numtemp represents the firstly entered number and num the last number.
This is your fixed code. Read below what caused the Exception:
package com.dexter.seemab;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class Calculator extends Activity {
String display = "";
Character op = 'q';
int i, num, numtemp;
int check = 0;
EditText rd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator);
rd = (EditText) findViewById(R.id.etResult);
}
public void btnClicked(View v) {
switch (v.getId()) {
case R.id.one:
insert(1);
break;
case R.id.two:
insert(2);
break;
case R.id.three:
insert(3);
break;
case R.id.four:
insert(4);
break;
case R.id.five:
insert(5);
break;
case R.id.six:
insert(6);
break;
case R.id.seven:
insert(7);
break;
case R.id.eight:
insert(8);
break;
case R.id.nine:
insert(9);
break;
case R.id.zero:
insert(0);
break;
case R.id.add:
op = '+';
perform();
break;
case R.id.sub:
op = '-';
perform();
break;
case R.id.product:
op = '*';
perform();
break;
case R.id.difference:
op = '/';
perform();
break;
case R.id.equals:
calculate();
break;
case R.id.clear:
clear();
break;
}
}
public void insert(int digit) {
if (check == 1) {
clear();
}
display = display + Integer.toString(digit);
if(op == 'q') {
num = Integer.valueOf(display).intValue();
} else {
String[] digits = display.split("\\"+op.toString());
num = Integer.valueOf(digits[digits.length-1]);
}
rd.setText(display);
check = 0;
}
public void perform() {
numtemp = num;
display = display + op.toString();
}
public void calculate() {
switch (op) {
case '+':
i = numtemp + num;
break;
case '-':
i = numtemp - num;
break;
case '*':
i = numtemp * num;
break;
case '/':
i = numtemp / num;
break;
}
display = Integer.toString(i);
rd.setText("=" + display);
check = 1;
}
public void clear() {
op = 'q';
num = 0;
numtemp = 0;
i = 0;
display = "";
rd.setText(display);
}
}
Another hint: You're calculator is not able to perform simple tasks like 3+4-5. If you want those terms to be calculated you have to change at least the perform()-method.
EDIT:
I found the cause of the crash: It is an NumberFormatException thrown in this line: num = Integer.valueOf(display).intValue();. It occurs (with my corrected code) when you click the first digit after the operator. It occurs because something like 12+8 cannot be parsed to int. So you have two choices to fix this:
1) In method perform: Change display = display + op.toString(); to display = "";. This will fix the Exception, but it is not very user-friendly.
2) In method insert: Change num = Integer.valueOf(display).intValue(); to
if(op == 'q') {
num = Integer.valueOf(display).intValue();
} else {
String[] digits = display.split("\\"+op.toString());
num = Integer.valueOf(digits[digits.length-1]);
}
This way your EditText will display text like "12+52" which is more user-friendly.
first change num=Integer.valueOf(display).intValue();
TO
num=Integer.parse(display);
and change display=Integer.toString(i);
TO
display=String.valueOf(i);
This code is when i was learning Android Application Development, and I am sharing it with you. May be you can get some idea from here, hope it helps:
Layout:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:stretchColumns="*" >
<TableRow>
<EditText
android:id="#+id/editText"
android:layout_span="4"
android:editable="false"
android:gravity="right"
android:hint="Your text here..." />
</TableRow>
<View
android:layout_height="2px"
android:background="#00ff00" />
<TableRow>
<Button
android:id="#+id/button1"
android:text="1" />
<Button
android:id="#+id/button2"
android:text="2" />
<Button
android:id="#+id/button3"
android:text="3" />
<Button
android:id="#+id/buttonAdd"
android:text="+" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button4"
android:text="4" />
<Button
android:id="#+id/button5"
android:text="5" />
<Button
android:id="#+id/button6"
android:text="6" />
<Button
android:id="#+id/buttonSub"
android:text="-" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button7"
android:text="7" />
<Button
android:id="#+id/button8"
android:text="8" />
<Button
android:id="#+id/button9"
android:text="9" />
<Button
android:id="#+id/buttonMul"
android:text="*" />
</TableRow>
<TableRow>
<Button
android:id="#+id/button0"
android:layout_span="2"
android:text="0" />
<Button
android:id="#+id/buttonClear"
android:text="Clr" />
<Button
android:id="#+id/buttonDiv"
android:text="/" />
</TableRow>
<TableRow>
<Button
android:id="#+id/buttonEqu"
android:layout_span="2"
android:text="=" />
<Button
android:id="#+id/buttonCan"
android:text="C" />
<Button
android:id="#+id/buttonPow"
android:text="^" />
</TableRow>
</TableLayout>
Activity:
public class MyFirstCalculator extends Activity implements OnClickListener
{
/** Called when the activity is first created. */
Button btn0,btn1,btn2,btn3,btn4,btn5,btn6,btn7,btn8,btn9;
Button btnAdd,btnSub,btnMul,btnDiv,btnPow,btnEqu,btnCan,btnClr;
EditText editText;
Double oldValue;
char chOp=' ';
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
editText=(EditText) findViewById(R.id.editText);
btn0 = (Button)findViewById(R.id.button0);
btn1 = (Button)findViewById(R.id.button1);
btn2 = (Button)findViewById(R.id.button2);
btn3 = (Button)findViewById(R.id.button3);
btn4 = (Button)findViewById(R.id.button4);
btn5 = (Button)findViewById(R.id.button5);
btn6 = (Button)findViewById(R.id.button6);
btn7 = (Button)findViewById(R.id.button7);
btn8 = (Button)findViewById(R.id.button8);
btn9 = (Button)findViewById(R.id.button9);
btnAdd = (Button)findViewById(R.id.buttonAdd);
btnSub = (Button)findViewById(R.id.buttonSub);
btnMul = (Button)findViewById(R.id.buttonMul);
btnDiv = (Button)findViewById(R.id.buttonDiv);
btnPow = (Button)findViewById(R.id.buttonPow);
btnEqu = (Button)findViewById(R.id.buttonEqu);
btnCan = (Button)findViewById(R.id.buttonCan);
btnClr = (Button)findViewById(R.id.buttonClear);
btn0.setOnClickListener(this);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btnAdd.setOnClickListener(this);
btnSub.setOnClickListener(this);
btnDiv.setOnClickListener(this);
btnMul.setOnClickListener(this);
btnPow.setOnClickListener(this);
btnEqu.setOnClickListener(this);
btnCan.setOnClickListener(this);
btnClr.setOnClickListener(this);
}
public void onClick(View v)
{
try
{
Button btn = (Button)v;
Double answer, curValue;
switch(v.getId())
{
case R.id.button0:
case R.id.button1:
case R.id.button2:
case R.id.button3:
case R.id.button4:
case R.id.button5:
case R.id.button6:
case R.id.button7:
case R.id.button8:
case R.id.button9:
editText.setText(editText.getText()+""+btn.getText()+"");
break;
case R.id.buttonAdd:
case R.id.buttonSub:
case R.id.buttonMul:
case R.id.buttonDiv:
case R.id.buttonPow:
if(editText.getText()+"" == "")
{
return;
}
chOp=(btn.getText()+"").charAt(0);
oldValue=Double.parseDouble(editText.getText()+"");
editText.setText("");
break;
case R.id.buttonCan:
oldValue=0.0;
editText.setText("");
break;
case R.id.buttonClear:
int len = (editText.getText()+"").length();
if(len==0)
{
Toast.makeText(getApplicationContext(), "Nothing to erase...", Toast.LENGTH_LONG).show();
}
else
{
editText.setText((editText.getText()+"").substring(0, len-1));
break;
}
case R.id.buttonEqu:
if(editText.getText()+"" == "")
{
return;
}
curValue = Double.parseDouble(editText.getText()+"");
switch (chOp)
{
case '+':
answer = oldValue+curValue;
editText.setText(answer+"");
break;
case '-':
answer=oldValue-curValue;
editText.setText(answer+"");
break;
case '*':
answer=oldValue*curValue;
editText.setText(answer+"");
break;
case '/':
answer=oldValue/curValue;
editText.setText(answer+"");
break;
case '^':
answer=Math.pow(oldValue, curValue);
editText.setText(answer+"");
break;
}
}
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
}
Note: I dont remember if the code is complete or not, or whether it runs properly or not, as it was written one year ago.
I have created two classes, actually both of them extends Activity. What I am trying to do is to call a method from the second class.
What I am trying to do is calling the method from second class then implemented in first class, unfortunately I did not have success in that.
I need your help to solve this problem. Thank you
My first class:
package com.math4kids;
import android.app.Activity;
import android.os.Bundle;
public class testing002 extends Activity {
private Sounds myotherclass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.numeracy);
myotherclass.Randomsoundforrightanswer();
}
}
The second class:
package com.math4kids;
import java.util.Random;
import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
public class Sounds extends Activity {
MediaPlayer cool, good, perfect, sweet, excellent, goodthinking, greatjob,
notbad, thatstheway, youdidit, yes, again, wrong, sorry,
sundfornum01, sundfornum02;
public Random random = new Random();
public Sounds(Context context){
super.getApplicationContext();
}
public void Randomsoundforrightanswer() {
cool = MediaPlayer.create(this, R.raw.cool);
good = MediaPlayer.create(this, R.raw.good);
perfect = MediaPlayer.create(this, R.raw.perfect);
sweet = MediaPlayer.create(this, R.raw.sweet);
excellent = MediaPlayer.create(this, R.raw.excellent);
goodthinking = MediaPlayer.create(this, R.raw.goodthinking);
greatjob = MediaPlayer.create(this, R.raw.greatjob);
notbad = MediaPlayer.create(this, R.raw.notbad);
thatstheway = MediaPlayer.create(this, R.raw.thatstheway);
youdidit = MediaPlayer.create(this, R.raw.youdidit);
yes = MediaPlayer.create(this, R.raw.yes);
switch (random.nextInt(11)) {
case 0:
cool.start();
break;
case 1:
good.start();
break;
case 2:
perfect.start();
break;
case 3:
sweet.start();
break;
case 4:
excellent.start();
break;
case 5:
goodthinking.start();
break;
case 6:
greatjob.start();
break;
case 7:
notbad.start();
break;
case 8:
thatstheway.start();
break;
case 9:
youdidit.start();
break;
case 10:
yes.start();
break;
}
}
}
Make a simple normal java file then define these methods in that class.
import java.util.Random;
import android.media.MediaPlayer;
public class Sounds {
Context context;
MediaPlayer cool, good, perfect, sweet, excellent, goodthinking, greatjob,
notbad, thatstheway, youdidit, yes, again, wrong, sorry,
sundfornum01, sundfornum02;
public Random random = new Random();
public Sounds(Context context){
this.context = context;
}
public void Randomsoundforrightanswer() {
cool = MediaPlayer.create(context, R.raw.cool);
good = MediaPlayer.create(context, R.raw.good);
perfect = MediaPlayer.create(context, R.raw.perfect);
sweet = MediaPlayer.create(context, R.raw.sweet);
excellent = MediaPlayer.create(context, R.raw.excellent);
goodthinking = MediaPlayer.create(context, R.raw.goodthinking);
greatjob = MediaPlayer.create(context, R.raw.greatjob);
notbad = MediaPlayer.create(context, R.raw.notbad);
thatstheway = MediaPlayer.create(context, R.raw.thatstheway);
youdidit = MediaPlayer.create(context, R.raw.youdidit);
yes = MediaPlayer.create(context, R.raw.yes);
switch (random.nextInt(11)) {
case 0:
cool.start();
break;
case 1:
good.start();
break;
case 2:
perfect.start();
break;
case 3:
sweet.start();
break;
case 4:
excellent.start();
break;
case 5:
goodthinking.start();
break;
case 6:
greatjob.start();
break;
case 7:
notbad.start();
break;
case 8:
thatstheway.start();
break;
case 9:
youdidit.start();
break;
case 10:
yes.start();
break;
}
}
}
Call methods of regular java file in activity like this.
import android.app.Activity;
import android.os.Bundle;
public class testing002 extends Activity {
private Sounds myotherclass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.numeracy);
new Sounds().Randomsoundforrightanswer(this);
}
}
Why should you do it?
Why Sounds class extending Activity?
Please read once again the official documentation Activity.
If you did it cause you need a context just pass it like a parameter to the Sounds class.
And you also need to visit Android development guide too
Only one Activity is instantiated at a time. You should not try to call one Activity from another.
Instead, you should create a third class which contains the method you want to call.
public class SoundManager{
private context;
public SoundManager(Context context){
context.context = context;
}
public void Randomsoundforrightanswer() {
cool = MediaPlayer.create(context, R.raw.cool);
good = MediaPlayer.create(context, R.raw.good);
perfect = MediaPlayer.create(context, R.raw.perfect);
sweet = MediaPlayer.create(context, R.raw.sweet);
excellent = MediaPlayer.create(context, R.raw.excellent);
goodthinking = MediaPlayer.create(context, R.raw.goodthinking);
greatjob = MediaPlayer.create(context, R.raw.greatjob);
notbad = MediaPlayer.create(context, R.raw.notbad);
thatstheway = MediaPlayer.create(context, R.raw.thatstheway);
youdidit = MediaPlayer.create(context, R.raw.youdidit);
yes = MediaPlayer.create(context, R.raw.yes);
switch (random.nextInt(11)) {
case 0:
cool.start();
break;
case 1:
good.start();
break;
case 2:
perfect.start();
break;
case 3:
sweet.start();
break;
case 4:
excellent.start();
break;
case 5:
goodthinking.start();
break;
case 6:
greatjob.start();
break;
case 7:
notbad.start();
break;
case 8:
thatstheway.start();
break;
case 9:
youdidit.start();
break;
case 10:
yes.start();
break;
}
}
}
However, you are going to have to do more work with the MediaPlayer. You should read the documentation for it before proceeding. The code I've shown gives you the basics of what you need to do but it will not work.
Finally, best advice I can give you is to learn the basics of Java and OOP before you proceed.
Unless testing002 class is actually an Activity you want to use as an Activity, you should move the randomsound... function to a seperate class.
Like the sounds class but not an Activity. If you define the function in that class you can construct in another and call it.