While trying to run my app, I noticed that a few errors claiming that many variables can not be resolved, even though declared in the code
i changed it to the following code, but once I enter the app, it collapses:
public String GetErr(){
String error="";
if(Facebook_name.toString().equals("")&& Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name.toString().equals(""))
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id.toString().equals(""))
error+="Id entered is invalid/n";
if(Pass.toString().length()<5 || Pass.toString().equals(""))
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
EDIT: Now the geterr() returns an empty string at all times.
You are declaring variables in the onCreate() method, so that is their scope. You can not use them outside this function. So when you use them in the GetErr() method, you get an error. You can solve this by moving the variables you need in multiple methods to global variables (so declare them in the class instead of in the method.
Edit
package com.example.app;
//import java.util.Calendar;
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.DatePicker;
import android.widget.TextView;
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
Button Btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Btn1 = (Button) findViewById(R.id.Btn1);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
Btn1.setOnClickListener(this);
Facebook_chk.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
if(Facebook_chk.isChecked())
Facebook_name.setEnabled(true);
else
Facebook_name.setEnabled(false);
;
}
});
}
public String GetErr(){
String error="";
if(Facebook_name==null && Facebook_chk.isChecked())//check with title if not available.
{
error+="facebook account not entered/n";//also check if not available
}
if(Name==null)
error+="Name not entered/n";
if(Id.toString().contains("[a-zA-Z]+") || Id==null)
error+="Id entered is invalid/n";
if(Pass.toString().length()<5)
error+="Passwords must contain 5 or more digits";
// int day= Date.getDayOfMonth();
// int month = Date.getMonth();
// int year=Date.getYear();
//Calendar enter = Calendar.getInstance();
// Calendar today = Calendar.getInstance();
// enter.set(year,month,day);
// today.set(Calendar.YEAR,Calendar.MONTH,Calendar.DAY_OF_MONTH);
//if((enter.getTime().before(today.getTime())))
// error+="Date entered either passed or not available.";
return error;
}
#Override
public void onClick(View v) {
if(v == Btn1){
String err = GetErr();
if(err != ""){
Txterr.setText(err);
}
}
}
}
define:
CheckBox Facebook_chk
TextView Facebook_name
TextView Name
TextView Id
TextView Txterr
TextView Pass
As Global Variables, like:
public class Second extends Activity implements OnClickListener {
CheckBox Facebook_chk;
TextView Facebook_name;
TextView Name;
TextView Id;
TextView Txterr;
TextView Pass;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.second);
Facebook_chk = (CheckBox)findViewById(R.id.Cfbook);//Represents the facebook checkbox.
Facebook_name = (TextView)findViewById(R.id.Face);//represents the facebook text.
Name = (TextView)findViewById(R.id.Name);//represents the Name text.
Id = (TextView)findViewById(R.id.Id);//represents the Id text.
Txterr = (TextView)findViewById(R.id.Txterr);//represents the Id text.
Pass = (TextView)findViewById(R.id.Pass);//represents the Pass text.
...
}
...
}
UPDATE:
If you would like to make a View to respond for Click Event, you'll need to make sure you've set that View clickable.
Since you did:
View v = findViewById(R.id.Btn1);
v.setOnClickListener((OnClickListener) this);
I've no idea R.id.Btn1 is really a Button or just a View. If it is a Button, please change to:
Button button = findViewById(R.id.Btn1);
button.setOnClickListener(this);
If it's not a button, just some View and you want it to respond to your Click, please add one line after findViewById
v.setClickable(true);
Again, if you intend to use this v sometime later in your code, you need to declare it as a global variable just like you did on your TextViews
Ref public void setClickable (boolean clickable)
Related
I am having a difficult time figuring out how to reference a view's ID in a custom class. The goal is to create a class that can change the text inside a button and change the visibility of a textView from gone to visible. The code works fine as a stand alone, but I'd like to not repeat it a bunch of times for all the drop down sections being created.
In the code below, when initiating in my main class, nothing happens when this is attached to an onclick listener
How do I reference what would otherwise be R.id.btn1 and R.id.text1 so I can use this as a class?
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class toggleSection {
private Button button;
private TextView textView;
private boolean isOpen = false;
public toggleSection(Button button, TextView textView) {
this.button = button;
this.textView = textView;
}
public void toggleSection(Button button, TextView textView, String title) {
if (!isOpen) {
button.setText(title + " ►");
textView.setVisibility(View.VISIBLE);
isOpen = true;
} else {
button.setText(title + " ▼");
textView.setVisibility(View.GONE);
isOpen = false;
}
}
}
Thanks
In your toggleSection(), you are providing references to your button and textview again and using those references only. However, you should be using instance variables here that you must have initialized in the constructor.
My Simple Interest calculator is crashing with a null pointer exception error, not sure what the problem is, there are no errors in the IDE before I complile, this is new to me. Here is my code and logcat: edit: Icouldn't post a logcat as the editor thinks it's code and I can't get it to format correctly
Code:
package com.codeherenow.sicalculator;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.SeekBar;
public class SICalculatorActivity extends Activity
implements SeekBar.OnSeekBarChangeListener, View.OnClickListener{
private int years;
private TextView YT;
private SeekBar bar;
private EditText principal = (EditText) findViewById(R.id.PA_field);
private EditText interest = (EditText) findViewById(R.id.IR_field);
public EditText pvalue;
public EditText ivalue;
private double mPvalue = 0;
private double mIvalue = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
bar = (SeekBar)findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
pvalue = (EditText) principal.getText();
ivalue = (EditText) interest.getText();
String s = principal.getText().toString();
mPvalue = Double.parseDouble(s);
String s2 = interest.getText().toString();
mIvalue = Double.parseDouble(s2);
}
#Override
public void onProgressChanged (SeekBar seekBar,int i, boolean b){
years = i;
YT = (TextView) findViewById(R.id.Years);
YT.setText(years + " Year(s)");
}
#Override
public void onStartTrackingTouch (SeekBar seekBar){
}
#Override
public void onStopTrackingTouch (SeekBar seekBar){
}
#Override
public void onClick(View view) {
TextView fTextView = (TextView) findViewById(R.id.finalText);
double finValue = mPvalue * (mIvalue/100) * years;
fTextView.setText("The interest for " + pvalue + "at a rate of " + ivalue + "for " + years + "year(s) is " + finValue);
}
}
You can't instantiate view variables by calling findViewById as you're declaring them. You have to declare them first and then instantiate either in onCreate or some method invoked after the Activity is bound with the view. Make sure to do it after setContentView(R.layout.sicalculator);
Okay, after seeing your layout, stacktrace and reading more in to your code, I saw that there are fundamental issues which ought to give you more crashes, so let's fix them.
First, pvalue and ivalue variables are unnecessary! Remove them.
Related: You cannot assign an Editable to an EditText. So this line is invalid ivalue = (EditText) interest.getText(); Because getText() returns an Editable. But these are all redundant and unnecessary anyways.
Second, in onCreate method, let's just initialize views and not try to get values and parse them yet; the user (or you) haven't interacted nor entered any values there yet; so trying to parse null values in to Doubles will crash your app.
Your onCreate method should look something like this. (Note that I'm also initializing your button and setting the click listener here).
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.sicalculator);
principal = (EditText) findViewById(R.id.PA_field);
interest = (EditText) findViewById(R.id.IR_field);
bar = (SeekBar) findViewById(R.id.seekBar);
bar.setOnSeekBarChangeListener(this);
calcBtn = (Button)findViewById(R.id.calc_btn);
calcBtn.setOnClickListener(this);
}
Now, you should get the values and parse them in your onClick listener - only when the user has entered values and clicked on the Calculate button, so your onClick() method should look something like this:
#Override
public void onClick(View view)
{
TextView fTextView = (TextView) findViewById(R.id.finalText);
mPvalue = Double.valueOf(principal.getText().toString());
mIvalue = Double.valueOf(interest.getText().toString());
double finValue = mPvalue * (mIvalue / 100) * years;
fTextView.setText("The interest for " + mPvalue + "at a rate of " + mIvalue + "for " + years + "year(s) is " + finValue);
}
And that should clear the logic and order or declaring, initializing, retrieving values from variables for you. I hope this explains how Java and Android basics work.
Oh by the way, I actually ran the code and it's running on my phone so this isn't just off the top of my head. If this helped you, please accept the answer.
Best wishes,
I have built a fortune cook app that previously currently has values hardcoded into an array
FortuneActivity.java
package juangallardo.emofortunecookie;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
package juangallardo.emofortunecookie;
import java.util.Random;
public class FortuneBox {
public String[] mFortunes = {
"What is the point?",
"Sometimes it is best to just sleep in.",
#98 other fortunes...
};
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
The problem is that now I want to add a Spanish version. So I realize that i should add that array into the strings.xml.
I looked up string resources on the Android developer page. and it gave me the idea to add this to my code
strings.xml
<string-array name="emo_fortunes">
<item>What is the point?</item>
<item>Sometimes it is best to just sleep in.</item>
</string-array>
But now I am stuck on where to add this part that has the part about Resources, etc.
I followed along to a tutorial from Treehouse about strings but my app kept crashing.
Basically the change that I made was to make the original array into
FortuneBox.java
# above unchanged from previous code
public String[] mFortunes;
# below unchanged from previous code
FortuneActivity.java
# same imports as before
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox = new FortuneBox();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
Resources resources = getResources();
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
These were my errors, but not sure where to go from here as I am new to Android and I have not touched Java since college.
log
FortuneActivity.java
FortuneBox.java
Mikki has the right answer, but it is a little confusing. In your code above, you are using the same name for two different variables: mFortuneBox. This is the root of your trouble:
private FortuneBox mFortuneBox = new FortuneBox();
...
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Change the second one to a different name, like this, and the errors go away:
final String[] fortunes = resources.getStringArray(R.array.emo_fortunes);
However, you still aren't using these fortunes from the array anywhere. You can actually delete fortunes from your Activity and move it to your FortuneBox class instead. This is slightly tricky, though, as you need to know what the context is to get a string array resource in your other class. The context is the Activity, so you need to pass this along as a parameter when you create your FortuneBox object.
I'd recommend a slight restructuring. Below are the two files that should work for you:
FortuneActivity.java
public class FortuneActivity extends Activity {
private FortuneBox mFortuneBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fortune);
mFortuneBox = new FortuneBox(this);
// Declare our View variables and assign them the Views from the layout file
final TextView fortuneLabel = (TextView) findViewById(R.id.fortuneTextView);
Button showFortuneButton = (Button) findViewById(R.id.showFortuneButton);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
String fortune = mFortuneBox.getFortune();
// Update the label with dynamic fortune
fortuneLabel.setText(fortune);
}
};
showFortuneButton.setOnClickListener(listener);
}
}
FortuneBox.java
public class FortuneBox {
public String[] mFortunes;
public FortuneBox(Context context) {
Resources resources = context.getResources();
mFortunes = resources.getStringArray(R.array.emo_fortunes);
}
// Methods (abilities)
public String getFortune() {
String fortune = "";
// Randomly select a fortune
Random randomGenerator = new Random();
int randomNumber = randomGenerator.nextInt(mFortunes.length);
fortune = mFortunes[randomNumber];
return fortune;
}
}
Your problem is simple. You can not access a non-final from an inner class (in this case your OnClickListener).
final String[] mFortuneBox = resources.getStringArray(R.array.emo_fortunes);
Try just changing the line to look like this one above.
Hope it helps.
The mFortuneBox variable in the previous way you have used is an object of FortuneBox class and hence this call mFortuneBox.getFortune() works.
In the later changed code, you have made mFortuneBox variable a reference to an Array of strings. But still tried calling mFortuneBox.getFortune(). 'getFortune()' is a method of FortuneBox class right, so you can call it with an object of Forune Box class itself.
Try doing this:
final String[] fortuneArray = resources.getStringArray(R.array.emo_fortunes);
and
private FortuneBox mFortuneBox = new FortuneBox();
Now call mFortuneBox.getFortune(fortunearray) sending it this array to the getfortune method.
Now let the getFortune() method randomly pick one from this array passed and return the random string picked
My slot machine is still in progress. I am trying to get a method from one class to another but I can't figure it out. Could anyone please help me? Here is my first code which I wanted to call the method from the other class:
GameMainActivity:
package com.ics136leeward.slotmachine;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.ViewFlipper;
public class GameMainActivity extends Activity {
ViewFlipper slotOne, slotTwo, slotThree, spinStop;
Button spin, stop, bet;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_main);
this.initSpin();
this.initStop();
}
private void initSpin() { //initialize Spin Method
spin = (Button) findViewById (R.id.spinBtn);
slotOne = (ViewFlipper) findViewById (R.id.slot1);
slotTwo = (ViewFlipper) findViewById (R.id.slot2);
slotThree = (ViewFlipper) findViewById (R.id.slot3);
spinStop = (ViewFlipper) findViewById (R.id.spinstopbutton);
spin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.setFlipInterval(40);
slotOne.startFlipping(); //slot 1 spin
slotTwo.setFlipInterval(50);
slotTwo.startFlipping(); //slot 2 spin
slotThree.setFlipInterval(60);
slotThree.startFlipping(); //slot 3 spin
spinStop.showNext(); // shows the stop button
}
});
}
private void initStop() { //initialize Stop Method
stop = (Button) findViewById (R.id.stopBtn);
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
slotOne.stopFlipping(); //stops slot 1
slotTwo.stopFlipping(); //stops slot 2
slotThree.stopFlipping(); //stops slot 3
spinStop.showNext(); //shows the spin button again
if(slotOne == slotTwo || slotTwo == slotThree) {
}
}
});
}
}
Here is the second java class which I wanted to call the method getBet1() and getBet5() to the first activity:
Bet:
package com.ics136leeward.slotmachine;
import android.app.Activity;
import android.widget.TextView;
public class Bet extends Activity {
TextView userBet, bankRoll, event;
final int BETONE = 1, BETFIVE = 5;
int uBet = 100, bet;
public void getBet1() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETONE;
bet += BETONE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
public void getBet5() {
userBet = (TextView) findViewById (R.id.userBet);
bankRoll = (TextView) findViewById (R.id.bankroll);
uBet -= BETFIVE;
bet += BETFIVE;
userBet.setText("Your Bet: " + bet);
bankRoll.setText("" + uBet);
return;
}
}
You need to make a Utility class not a Activity class
So change
public class Bet extends Activity {
to
public class Bet // Normal java class
Since its not a Activity class there is not need to initialize views
userBet = (TextView) findViewById (R.id.userBet); //remove them
// Initialize all yours views in Activity
Now in Activity class
Bet bet = new Bet();
int value =bet.getBet1();
In getBet1() do you calculations an return values.
Then in Activity you can set the value to TextView
textView.setText(String.valueOf(value));
Do also check raghav's answer #
Can i Create the object of a activity in other class?
you can define those method static and then call by its class name like
Bet.getBet1();
Bet.getBet5();
or simply you can create class object and then call it
Bet b = new Bet();
b.getBet1()
Note: You don't need to extend to Activity class as you are not using any UI. (Already suggested by Raghunandan)
Try this code in the onCreate method of your calling class i.e. GameMainActivity
Bet bet= new Bet(); // where bet is object of Bet Class
bet.getBet1();
bet.getBet5();
However, You can create the object of Bet class in any method and access the class methods provided their access modifier must be public.
I am new to android programming and I created a simple calculator. I want the user to be able to pause the application without losing the numbers entered in the two EditText boxes. I am trying to use shared preferences but for some reason my app keeps crashing. How can I fix this?
package com.example.simplecalculator;
import android.os.Bundle;
import android.app.Activity;
import android.content.SharedPreferences;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.example.simplecalculator.*;
public class MainActivity extends Activity {
SharedPreferences mySharedPreferences;
SharedPreferences.Editor editor;
public static final String MYPREFERENCES = "MyPreferences_001";
float answer;
final EditText numberone = (EditText)findViewById(R.id.number1);
final EditText numbertwo = (EditText)findViewById(R.id.number2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mySharedPreferences = getSharedPreferences(MYPREFERENCES, 0);
String number1 = mySharedPreferences.getString("number1", null);
String number2 = mySharedPreferences.getString("number2", null);
numberone.setText(number1);
numbertwo.setText(number2);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void Addition(View view) {
answer = Float.parseFloat(numberone.getText().toString()) + Float.parseFloat(numbertwo.getText().toString());;
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your sum is " + answer);
}
public void Subtraction(View view) {
answer = Float.parseFloat(numberone.getText().toString()) - Float.parseFloat(numbertwo.getText().toString());;
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your difference is " + answer);
}
public void Multiplication(View view) {
answer = Float.parseFloat(numberone.getText().toString()) * Float.parseFloat(numbertwo.getText().toString());;
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your product is " + answer);
}
public void Division(View view) {
answer = Float.parseFloat(numberone.getText().toString()) / Float.parseFloat(numbertwo.getText().toString());;
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your quotient is " + answer);
}
public void Power(View view) {
answer = (float) Math.pow(Float.parseFloat(numberone.getText().toString()), Float.parseFloat(numbertwo.getText().toString()));
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your answer is " + answer);
}
public void Root(View view) {
answer = (float) Math.sqrt(Float.parseFloat(numberone.getText().toString()));
TextView value = (TextView)findViewById(R.id.answer);
value.setText("Your answer is " + answer);
}
public void onPause(){
mySharedPreferences = getSharedPreferences(MYPREFERENCES, Activity.MODE_PRIVATE);
editor = mySharedPreferences.edit();
editor.putString("number1", numberone.getText().toString());
editor.putString("number2", numbertwo.getText().toString());
editor.commit();
}
}
final EditText numberone = (EditText)findViewById(R.id.number1);
final EditText numbertwo = (EditText)findViewById(R.id.number2);
Keep that inside onCreate(), after setContentView()
Also,
What happens the first time, when nothing is stored in sharedPref,
String number1 = mySharedPreferences.getString("number1", null);
String number2 = mySharedPreferences.getString("number2", null);
return some value then instead of "null" .
If using SharedPref pretty often for a Calculator app, i suggest making a function for get and put the sharedPref..
Something like:
public static void saveDataToPreferences(String key,
String value) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString(key, value);
editor.commit();
}
public static String getDataFromPreferences(String key) {
SharedPreferences prefs = context.getSharedPreferences("your package name",
Context.MODE_PRIVATE);
return prefs.getString(key, Constants.BLANK);
}
If the functions are inside your activity, the context for that activity can be declared globally. Else pass that in the arguments.
Your application is crashing because you are trying to initializing your view before setting any layout to your activity. Now, initialize the as follows...your problem will be solved.
EditText numberone;
EditText numbertwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberone = (EditText)findViewById(R.id.number1);
numbertwo = (EditText)findViewById(R.id.number2);
}
Try this..
You have initilize your EditText before onCreate do that inside onCreate
float answer;
final EditText numberone;
final EditText numbertwo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
numberone = (EditText)findViewById(R.id.number1);
numbertwo = (EditText)findViewById(R.id.number2);
You are getting NULL Pointer exception most probably. Its because at first when your application sharedprefrences doesn't have any thing, you tend to access it and get a value from it and when its not present you set value of string NULL. When you try to show that value which is NULL on the screen, it crashes.
Do this:
String number1 = mySharedPreferences.getString("number1", "");
String number2 = mySharedPreferences.getString("number2", "");
I think you need to use onSaveInstanceState() and onRestoreInstanceState() for this purpose.
It's used when the Activity is forcefully terminated byactivity is destroyed due to normal app behavior, such as when the user presses the Back button or your activity signals its own destruction by calling finish() or the OS (ex: when your Activity is in the background and another task needs resources) . When this happens, onSaveInstanceState(Bundle outstate) will be called and it's up to your app to add any state data you want to save in outstate.
When the user resumes your Activity, onCreate(Bundle savedInstanceState) gets called and savedInstanceState will be non-null if your Activity was terminated in a scenario described above. Your app can then grab the data from savedInstanceState and regenerate your Activity's state to how it was when the user last saw it.
Basically in onCreate, when savedInstanceState is null, then it means this is a 'fresh' launch of your Activity. And when it's non-null (if your app saved the data in onSaveInstanceState(...), it means the Activity state needs to be recreated.
Here is much more detail about it