Getting error in main activity on my basic calculator app - java

I'm creating a simple android calculator app. There is no compile time error, but when I'm tapping on any button, the app crashes.
package com.buckydroid.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
}
private void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
str = "";
}
private void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
private void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}
Error Log
10-08 19:44:59.361 19449-19449/com.buckydroid.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.buckydroid.myapplication, PID: 19449
java.lang.IllegalStateException: Could not find method onClick(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
So if you need any other code then please comment
Thank you in advance..

Ok I got it after building in Android studio. The error is a lot bigger than what you pasted and I was able to track it down with the stack trace.
Basically you are trying to concatenate a string to a null with this line in your onClick method: str += button.getText().toString();
Since you can't do that you can fix the issue by replacing:
str += button.getText().toString();
With this:
str = button.getText().toString();
OR
Since this is a calculator app, you can initialize str in the onCreate method with str = ""; and then also remove str = ""; from the onClick method.
Full Code here:
public class MainActivity extends AppCompatActivity {
private TextView screen;
private String str1,str2,str3,result,str,sign;
private Double a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (TextView)findViewById(R.id.textview);
str = "";
}
public void onClick(View v){
Button button = (Button) v;
str += button.getText().toString();
screen.setText(str);
a = Double.parseDouble(str);
}
public void onClickSigns(View v){
Button button = (Button) v;
sign = ((Button) v).getText().toString();
screen.setText(sign);
str="";
}
public void calculate(View v){
Button button = (Button) v;
str2 = screen.getText().toString();
b = Double.parseDouble(str2);
if (sign .equals("+")){
result = a+b+"";
}
else if (sign .equals("-")){
result = a-b+"";
}
else if (sign .equals("X")){
result = a*b+"";
}
else if (sign .equals("÷")){
result = a/b+"";
}
else{
result = "Something went wrong";
}
screen.setText(result);
}
}

onClick should be public not private.
also initialize your strings to empty string. Like:
private String str1 = "",str2="",str3="",result="",str="",sign="";
Hope this fixes your issue.

Way 1:
in your main_activity xml file add android:onclick="onClick" and make onClick(View view) method public.
for example
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calculate"
android:onClick="onClick"/>
And in main_activity.java file
public void onClick(View view){
}
Hope it help you :) Happy coding..

Related

Using a button with the code inside of a different class

I am trying to make an app and I have the code for a button inside of a different class. When I start my app and click the first button it brings me to a different layout where the button is located. But when I click this button it doesn't do anything, just the little click down animation.
First Button Code:
public class TextAdd extends AppCompatActivity {
public static EditText Text;
public static Button Set;
public static String[] Checkagainst = new String[1000];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Text_Checker);
Text = (EditText) findViewById(R.id.LPN);
Set = (Button) findViewById(R.id.Set);
Set.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String Text_Value = Text.getText().toString();
if (!Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.add);
for (int i = 0; i < Checkagainst.length; i++) {
if (Checkagainst[i] == null) {
Checkagainst[i] = Text_Value;
break;
}
}
} else if (Arrays.asList(Checkagainst).contains(Text_Value) && Text_Value.length() >= 1 && Text_Value.length() <= 7) {
setContentView(R.layout.have);
}
}
});
}
}
Second Button Code:
public class Have extends AppCompatActivity {
private Button HaveBack;
private TextView Have;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.have);
HaveBack = (Button) findViewById(R.id.HaveBack);
Have= (TextView) findViewById(R.id.Have);
String Text_Value= TextAdd.License.getText().toString();
String Extra = Text_Value + " is already part of Your license plates";
Have.setText(Extra);
HaveBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.Text_Checker);
}
});
}
}
Does anyone know what is wrong? If so can you please help me.
You should use setContentView() only once in your onCreate() method. Calling it multiple times is not correct. If you want to show a small layout above your current layout, you should use a Dialog and if you want to show a completely different layout above everything, you have to use Intents to go to another activity and do the rest of the work in that one.
besides, use lowercase letters at start of your variables' and objects' names and start Class names with Uppercase letters. That's the standard for knowing what is a class and what is an object. e.g.
Button firstButton, secondButton;

Android EditText to int conversation error [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
This probably the most asked question, but it very difficult to find some answers. First I am newbie. I want to make simple quadratic equation formula app. That would allow to to find solution fast. I bump with the problem that Android Studio say Code is okey, but device crashes after opening app.
private Button mButton;
private EditText mEdit;
private EditText mEdit1;
private EditText mEdit2;
private TextView mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mButton = (Button)findViewById(R.id.button2);
mEdit = (EditText)findViewById(R.id.editText);
mEdit1 = (EditText)findViewById(R.id.editText2);
mEdit2 = (EditText)findViewById(R.id.editText3);
mText = (TextView)findViewById(R.id.textView4);
//Int definēšana
final int i1 = Integer.parseInt(mEdit.getText().toString());
final int i2 = Integer.parseInt(mEdit1.getText().toString());
final int i3 = Integer.parseInt(mEdit2.getText().toString());
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Mainīgo ievade
int a = i1;
//Pārbauda vai a nav nulle
if (a == 0){
mText.setText(String.valueOf("Nav kvadrātvienādojums"));
} else {
int b = i2;
int c = i3;
//Diskriminanta aprēķināšana
double diskr = (b*b)-4*a*c;
//Kvadrātsakne no diskriminanta
double sd = (double) Math.sqrt(diskr);
//Sakņu aprēķināšana
double x1 = (-b+sd)/(2*a);
double x2 = (-b-sd)/(2*a);
//Rezultāta izvade
if (diskr < 0){
mText.setText(String.valueOf("Kvadrātvienādojumam nav sakņu"));
} else if (diskr == 0){
mText.setText(String.valueOf("Kvadrātvienādojumam ir viena sakne: " + x1));
} else {
mText.setText(String.valueOf("Kvadrātvienādojuma saknes: " + x1 + " un " + x2));
}
}
}
});
}
And logcat that may help detect a problem
FATAL EXCEPTION: main
Process: com.homemade.prtbust.kvadratvienadojums, PID: 4552
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.homem`enter code here`ade.prtbust.kvadratvienadojums/com.homemade.prtbust.kvadratvienadojums.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3133)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
at com.homemade.prtbust.kvadratvienadojums.MainActivity.onCreate(MainActivity.java:38)
at android.app.Activity.performCreate(Activity.java:6609)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3086)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3243)
at android.app.ActivityThread.access$1000(ActivityThread.java:218)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1718)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6917)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199) 
I think you miss
setContentView(R.layout.activity_main); " activity_name is the name of layout where is the edit text"
setContentView must be called before using findViewById
You are not assigning any layout to the Activity, therefore all your EditTexts, Button and TextView are not present, when you try to access any of them by code the program will crash.
Second, you should read the values for your variables when clicking the button, not in the oncreate, because that will cause you another error given that you'll try to parse something that is an empty string (unless you have set a value in the android:text tag in the xml).
I also wouldn't declare them as final (because you won't be able to modify them later.
Try using this code:
private Button mButton;
private EditText mEdit;
private EditText mEdit1;
private EditText mEdit2;
private TextView mText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button2);
mEdit = (EditText)findViewById(R.id.editText);
mEdit1 = (EditText)findViewById(R.id.editText2);
mEdit2 = (EditText)findViewById(R.id.editText3);
mText = (TextView)findViewById(R.id.textView4);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
//Int definēšana
int i1 = Integer.parseInt(mEdit.getText().toString());
int i2 = Integer.parseInt(mEdit1.getText().toString());
int i3 = Integer.parseInt(mEdit2.getText().toString());
//Mainīgo ievade
int a = i1;
//Pārbauda vai a nav nulle
if (a == 0){
mText.setText(String.valueOf("Nav kvadrātvienādojums"));
} else {
int b = i2;
int c = i3;
//Diskriminanta aprēķināšana
double diskr = (b*b)-4*a*c;
//Kvadrātsakne no diskriminanta
double sd = (double) Math.sqrt(diskr);
//Sakņu aprēķināšana
double x1 = (-b+sd)/(2*a);
double x2 = (-b-sd)/(2*a);
//Rezultāta izvade
if (diskr < 0){
mText.setText(String.valueOf("Kvadrātvienādojumam nav sakņu"));
} else if (diskr == 0){
mText.setText(String.valueOf("Kvadrātvienādojumam ir viena sakne: " + x1));
} else {
mText.setText(String.valueOf("Kvadrātvienādojuma saknes: " + x1 + " un " + x2));
}
}
}
});
}
try write this code ofter you set the content view for the activity
//load all the views from the xml file
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.button2);
mEdit = (EditText)findViewById(R.id.editText);
mEdit1 = (EditText)findViewById(R.id.editText2);
mEdit2 = (EditText)findViewById(R.id.editText3);
mText = (TextView)findViewById(R.id.textView4);
//Int definēšana
final int i1 = Integer.parseInt(mEdit.getText().toString());
final int i2 = Integer.parseInt(mEdit1.getText().toString());
...
mButton.setOnClickListener(/*your code here*/);
you cant get the text from EditText before the EditText view created.
if this not solved youre problem, try write your i1/2/3 variables at onStart
#Override
protected void onStart() {
super.onStart();
final int i1 = Integer.parseInt(mEdit.getText().toString());
final int i2 = Integer.parseInt(mEdit1.getText().toString());
final int i3 = Integer.parseInt(mEdit2.getText().toString());
}

How to use java classes within one activity?

How can you use a java class within one activity, by that I mean is having different components of that activity spread out in a bunch of java classes. I'm a little new to android and this is what I have tried so far:
MainActivity.java
package com.example.alex.myapplication;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Something(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add,subtract,multiply,devide;
private EditText editA, editB, editC;
private double doubleA,doubleB,doubleC;
public Something(Activity a){
activity=a;
click();
}
public void click(){
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
doubleA =Double.parseDouble(editA.getText().toString());
doubleB =Double.parseDouble(editB.getText().toString());
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA+doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA-doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA*doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
doubleC = doubleA/doubleB;
String s = "" + doubleC;
editC.setText(s);
}
});
}
}
So I wasn't sure why my listeners weren't working on my buttons so I tried passing the activity to the class that has the listeners added to the buttons but that didn't work in fact now my application won't even start in the emulator. All I wanted to do was have "MainActivity" handle the "Gui" and have the "Something" class handle the listeners but no matter what I do I can't seem to make them communicate with one another to form one Activity.
LogCat
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference
at android.app.Activity.findViewById(Activity.java:2071)
at com.example.alex.myapplication.Something.click(Something.java:32)
at com.example.alex.myapplication.MainActivity.onCreate(MainActivity.java:19)
at android.app.Activity.performCreate(Activity.java:5937)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity
(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
like a before post XD with 1 java class, call it again after pressing buttons, for example, you can have a invisible buttons, radiobuttons whatever you want invisible and just with a click it turns visible and useful for you, here i go:
First the variable which controls the activity are going to do
String num ="";
then have your buttons, i use 2 of them and the others are invisible
Button bn1;
Button bn2;
Button bn3;
Button bn4;
bn3.setVisibility(View.INVISIBLE);
bn4.setVisibility(View.INVISIBLE);
then the button code, depends on how many buttons you want
Button.setOnClickListener(new Button onclickListener(){
public void onClick(){
//get a default variable in this case String num
Intent intent = new Intent(MainActivity.this, MainActivity.class); num="cero"; intent.putExtra("po", num);
CodigoPeticion=2; startActivityForResult (intent,CodigoPeticion); finish(); break;
}
}
});
this one to get the String num:
Bundle extras = getIntent().getExtras();
if (extras!= null) {
num =extras.getString("po");
}
and at last but not least this one to do someting depending the String:
if (num.matches("cero")){
//do something, enable more buttons, disable radiobuttons,
bn3.setVisibility(View.VISIBLE);
}else if(num.matches("one")){//this string is from another button
//do something else in the same activity, as you spected enable radiobuttons, show a image, etc
bn4.setVisibility(View.VISIBLE);
}else{
//some textview with a specific title
TextView.setText("Something's Wrong");
}
don't forget the bn3 and bn4 listeners!
hope that helps you, see ya!
I think that you should rearrange the code to have the onClickListener inside Something constructor:
Something.java
import android.view.View;
import android.widget.EditText;
import android.widget.Button;
import android.app.Activity;
public class Something {
private Activity activity;
private Button add, subtract, multiply, devide;
private EditText editA, editB, editC;
private double doubleA, doubleB, doubleC;
public Something(Activity a) {
activity = a;
editA = (EditText) activity.findViewById(R.id.editText);
editB = (EditText) activity.findViewById(R.id.editText2);
editC = (EditText) activity.findViewById(R.id.editText3);
add = (Button) activity.findViewById(R.id.add);
subtract = (Button) activity.findViewById(R.id.subtract);
multiply = (Button) activity.findViewById(R.id.multiply);
devide = (Button) activity.findViewById(R.id.devide);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(1);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(2);
}
});
multiply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(3);
}
});
devide.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click(4);
}
});
}
public void click(int calculate) {
// assume number entered - no error
doubleA = Double.parseDouble(editA.getText().toString());
doubleB = Double.parseDouble(editB.getText().toString());
switch (calculate) {
case 1:
doubleC = doubleA + doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 2:
doubleC = doubleA - doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 3:
doubleC = doubleA * doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
case 4:
doubleC = doubleA / doubleB;
String s = "" + doubleC;
editC.setText(s);
break;
default:
break;
}
}
}
I think the problem was putting 'click()' method inside the main constructor runs through the code once only. I hope this helps!
You can use your "something" class in the mainactivity.
first initialize "Something" class in the main activity by
Something s = new Something(MainActivity.this);
Than you can use every method of that class in your main Activity.Just as you wanted,like this
s.add.setonclicklistener(...
or
s.click();
//Just use like this.
As I know this will help someone else who encountered the same problem as me will benefit, the problem was that I needed to pass the activity into my Something(Activity a){} constructor and initialize everything into that. Like Something(Activity a){
aT1 = (EditText) a.findViewById(R.id.numberOne);
aT2 = (EditText) a.findViewById(R.id.numberTwo);
aT3 = (EditText) a.findViewById(R.id.result);
add = (Button) a.findViewById(R.id.add);
subtract = (Button) a.findViewById(R.id.subtract);
multiply = (Button) a.findViewById(R.id.multiply);
devide = (Button) a.findViewById(R.id.devide);
}
And all you need to do in main activity is pass the Activity when you make an instance/execute the code(ex: Something s = new Something(this);/new Something(this);) After you done that you can just call s.click(); and it should work.

How to reset class variable to default value 0?

If anybody can tell me different way to do this, I would appreciate. How to reset class variable to 0, or default value? I use class variable cause I don't know another way to do this. After my game ends I place result in class variable, cause I have two rounds of my game, and after first round ends I add the result, and class variable is good for this cause even after I restart my game method it still holds my previous result. After second round is over I add that result to previous result and then close the activity and set text result as text to a button. But when I click New game, that button still holds that text, cause class variable still holds it. How to reset that class variable when I go on New game?
Here's my game code, some of it (100 points are start amount, and it gets lower in game progress):
public class Asocijacije extends Activity implements OnClickListener{
int brojPoenaAsocijacije = 100;
public static int brojPoenaUkupno;
Then I skip here a lot of code and here's where I add points. brojPoenaAsocijacije are points earned in that round:
brojPoenaUkupno = brojPoenaUkupno + brojPoenaAsocijacije;
Here's my main activity where I set points from my class variable to a button (where I added comment):
public class Izbor extends Activity implements OnClickListener{
Asocijacije poeni = new Asocijacije();
Button toploHladno, asocijacije, cigle, spojnice, nazad, poeniTH, poeniAso, poeniCigle, poeniSpojnice;
TextView naslov;
public boolean music;
MediaPlayer buttonClicks, buttonBack;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE); //full screen
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.izbor);
SharedPreferences getPrefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
music = getPrefs.getBoolean("checkbox", true);
addListenerOnButton();
}
private void addListenerOnButton() {
buttonClicks = MediaPlayer.create(this, R.raw.click);
buttonBack = MediaPlayer.create(this, R.raw.button31);
Typeface naslovType = Typeface.createFromAsset(getAssets(), "Lobster.ttf");
Typeface dugmad = Typeface.createFromAsset(getAssets(), "Bebas.ttf");
naslov = (TextView) findViewById(R.id.tvIzborNaslov);
toploHladno = (Button) findViewById(R.id.bIzbor1);
asocijacije = (Button) findViewById(R.id.bIzbor2);
cigle = (Button) findViewById(R.id.bIzbor3);
spojnice = (Button) findViewById(R.id.bIzbor4);
nazad = (Button) findViewById(R.id.bIzborNazad);
poeniTH = (Button) findViewById(R.id.bPoeniTH);
poeniAso = (Button) findViewById(R.id.bPoeniAso);
poeniCigle = (Button) findViewById(R.id.bPoeniCigle);
poeniSpojnice = (Button) findViewById(R.id.bPoeniSpojnice);
naslov.setTypeface(naslovType);
toploHladno.setTypeface(dugmad);
asocijacije.setTypeface(dugmad);
cigle.setTypeface(dugmad);
spojnice.setTypeface(dugmad);
nazad.setTypeface(dugmad);
poeniAso.setTypeface(dugmad);
toploHladno.setOnClickListener(this);
asocijacije.setOnClickListener(this);
cigle.setOnClickListener(this);
spojnice.setOnClickListener(this);
nazad.setOnClickListener(this);
}
#Override
protected void onStart() {
super.onStart();
poeniAso.setText("" + poeni.brojPoenaUkupno); //I do it here
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bIzbor1:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.GAME"));
break;
case R.id.bIzbor2:
if(music == true){
buttonClicks.start();
}
startActivity(new Intent("rs.androidaplikacije.toplo_hladno.ASOCIJACIJE"));
break;
case R.id.bIzbor3:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzbor4:
if(music == true){
buttonClicks.start();
}
break;
case R.id.bIzborNazad:
if(music == true){
buttonBack.start();
}
poeniAso.setText("");
finish();
break;
}
}
}
Because I don't find the piece of code where you start the new game, I can only say:
Asocijacije.brojPoenaUkupno = 0;
Probably want to reset your state when you close the in-game activity.
#Override
protected void onDestroy() {
super.onDestroy();
Asocijacije.brojPoenaUkupno = 0;
//whatever other things need to be reset.
}

Retain Values from edit boxes android code

I have this code, I want to retain my value of the editbox from the first input after change or start of new activity.
this what happens in this code:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = null
I need this to happened:
editbox1 = 1 > start new activity > back to recent activity > editbox1 = 1
CODE
package org.example.touch;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.*;
import android.widget.EditText;
public class SettingsClass extends Activity {
private EditText Alpha;
private EditText Beta;
private EditText Charlie;
private EditText Delta;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
Alpha = (EditText) findViewById(R.id.editText1);
Beta = (EditText) findViewById(R.id.editText2);
Charlie = (EditText) findViewById(R.id.editText3);
Delta = (EditText) findViewById(R.id.editText4);
}
public void buttonSBHandler (View view){
String Aint = Alpha.getText().toString();
String Bint = Beta.getText().toString();
String Cint = Charlie.getText().toString();
String Dint = Delta.getText().toString();
Intent startNewActivityOpen = new Intent(SettingsClass.this, GameUi.class);
startNewActivityOpen.putExtra("Aint", Aint);
startNewActivityOpen.putExtra("Bint", Bint);
startNewActivityOpen.putExtra("Cint", Cint);
startNewActivityOpen.putExtra("Dint", Dint);
startActivityForResult(startNewActivityOpen, 0);
//startActivity(new Intent(view.getContext(), GameUi.class));
}
}
1)One thing is that you can go with shared preference store your value in shared preference and on oncreate() method first check whether shared preference is null or not if it is not null than get the value from shared preference.
or
2)Just make those data of edit text as static like-
static String Aint = Alpha.getText().toString();
static String Bint = Beta.getText().toString();
static String Cint = Charlie.getText().toString();
static String Dint = Delta.getText().toString();
so whenever you will come back to the activity so the previous data of the edit text will be shown there.
hope these thing will work for you perfectly.
thanks

Categories