I want to increment the test variable whenever onCreate() is called but my app is crashing. Please help me find out the fix and please tell me why my app is crashing.
public int test = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView num = (TextView) findViewById(R.id.textNum);
new MainActivity().test++;
num.setText(new MainActivity().test);
}
You should never create an instance of Activity by your self
You can directly access your test in your MainActivity no need to use MainActivity().test to access your test variable
if you want to set an integer value to your textview then you need to convert your integer into a string value like String.valueOf(test) or ""+test
Try this way
public int test=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView num=(TextView) findViewById(R.id.textNum);
test++;
num.setText(String.valueOf(test));
}
if you want to increment your test variable whenever onCreate() called then you can use SharedPreferences
SAMPLE CODE
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
public class Main2Activity extends AppCompatActivity {
String prefName = "MY_PREFS_NAME";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
SharedPreferences prefs = getSharedPreferences(prefName, MODE_PRIVATE);
SharedPreferences.Editor editor = getSharedPreferences(prefName, MODE_PRIVATE).edit();
int test = prefs.getInt("counter", 0);
test++;
editor.putInt("counter", test);
editor.apply();
}
}
Okay so let me get you to understand a bit about the activity lifecycle:
onCreate()
Is called every time the activity is created, meaning there is really no use for you to increment the test in this method, because it will always be 1.
onStart()
Will be called every time the activity is shown, meaning when the activity is created or when you go back to the activity, I think this is the method where you increment test.
example
public int test = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView num = (TextView) findViewById(R.id.textNum);
}
#Override
protected void onStart() {
super.onStart();
test++;
num.setText(String.valueOf(test));
}
Related
I made a new class and I wanted to make an OnClickListener for a button but I notice that the onCreate wasn't being called. Any help is appreciated.
public class BedtimeBottomSheet extends Activity {
private static final String TAG = "BedtimeBottomSheet";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "onCreate: ");
}
}
Consider that you should use setContentView(binding.getRoot()); in your onCreate method.
I am developing a very basic Android App that adds a number in TextView whenever I hit the Button. The digit showing in TextView is also preserved when the orientation of the Mobile changes using the onSaveInstanceState() and onRestoreInstanceState() functions.
The problem is when orientation changes the value is preserved but when the Button is pressed once again after the changing of the orientation it again starts the counting from 0 rather then starting it from the preserved value.
My code:
public class MainActivity extends AppCompatActivity {
TextView showValue;
int counter=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (TextView) findViewById(R.id.CounterValue);
}
public void countIN(View view)
{
counter++;
showValue.setText(Integer.toString(counter));
}
#Override
protected void onSaveInstanceState(Bundle outState) {
outState.putString("my_text", showValue.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
showValue.setText(savedInstanceState.getString("my_text"));
}
}
Thank You for your response.
add
counter=Integer.parseInt(savedInstanceState.getString("my_text"));
inside onRestoreInstanceState method
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
showValue.setText(savedInstanceState.getString("my_text"));
counter=Integer.parseInt(savedInstanceState.getString("my_text"));
}
You can save and get data using several methods
First If your data is small, then you can use onSavedInstanceState and onRestoreInstanceState .. for details follow this answer or this one
Second if you have too much data to store, then use ViewModel instead; this is a tutorial that you can start from.
I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:
public class MainActivity extends ActionBarActivity {
//Radio Button
private int stufe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);
//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);
}
The Settings Activity looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);
//BUTTON
final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();
//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));
//---saves the values---
editor.commit();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}
What is the best way to achieve this?
onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the Android Activity lifecycle.
I have a problem here with variables. I created a simple Android game. The levels depend on the input the user does (birthay and birthmonth are the variables).
I made a simpler app which refers to the global variable problem only.
Here are the files:
Global.java
import android.app.Application;
public class Globals extends Application {
private String someVariable;
public String getSomeVariable() {
return someVariable;
}
public void setSomeVariable(String someVariable) {
this.someVariable = someVariable;
}
}
MainActivity.java:
public class MainActivity extends Activity {
EditText editText;
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
String m = editText.getText().toString();
((Globals) this.getApplication()).setSomeVariable(m);
}
public void saveName(View v) {
Intent first = new Intent(this, FirstActivity.class);
startActivity(first);
}
}
FirstActivity.java:
public class FirstActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
TextView textf = (TextView) findViewById(R.id.textfirst);
String s = ((Globals) this.getApplication()).getSomeVariable();
textf.setText(s);
}
}
The variable is a String so I made the EditText to a String with getText().toString() but it doesn't work.
When I give the value a concrete String value it works properly also
((Globals) this.getApplication()).setSomeVariable(m); to
((Globals) this.getApplication()).setSomeVariable("message");
Any idea how to solve it?
Thank you ^^
You're assigning the EditTexts content to the variable in your onCreate() method where the EditText is probably empty. Do
((Globals) this.getApplication()).setSomeVariable(m);
in your saveName(View v) method and you should be fine.
PS: "it doesn't work" is not a great description of your problem, try to be a bit more precise (what did you expect to happen, what did actually happen).
PPS: Passing your String to the next activity via intent.putExtra() would be a nicer way to pass the data.
My MainActivity class has an if that checks is something is true it starts a new Activity which sets the text of a TextView to what I want.
MainActivity:
public static int caseA = 1;
if(caseA) {
Intent i = new Intent(Timer.this, WorkTimerNotification.class);
startActivity(i);
}
then it goes to the new Activity and it should check the value of caseA.
WorkTimerNotification:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
TextView timerMetric = (TextView)findViewById(R.id.tester_texter);
if(MainActivity.caseA) {
timerMetric.setText("min");
}
Problem: It does not change the text. Also, lets say I have many other if statements in mainactivity like:
if(caseB) {}
if(caseC) {}
//and so on..
How would I perform the checks? More importantly, how do I get this caseA check to work though.
You need to call findViewById() in onCreate():
private TextView timerMetric;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
timerMetric = (TextView)findViewById(R.id.tester_texter);
if(caseA) {
timerMetric.setText("min");
}
}
Right now you are calling it before calling setContentView(), before the view hierarchy is generated. For this reason, your code fails.