TextView doesn't show the required text - java

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.

Related

Why is onCreate() method not being called?

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.

Increment a variable whenever onCreate() is called

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

How to edit global variables with EditText to pass the value to an other activity?

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.

How to reference button for onClickListener?

I am trying to create an Android app, and i want to create a on click listener, here is what I have so far.
public void amazonListener() {
amazonButton = (Button) findViewById(R.id.amazonButton);
}
As you see, i am in the very early stages, but where I first referenced amazonButton (before the = sign) button, it turns into red text and it says Cannot resolve symbol 'amazonButton'. Also, I have referenced this method in the onCreate method
This is how you'd go about creating a button and setting a click listener to it.
public class MainActivity extends YouTubeFailureRecoveryActivity {
Button amazonButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
amazonButton = (Button) findViewById(R.id.amazonButton);
amazonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Define what should happen when the button is clicked.
}
});
}
}
You can also put the initializations in a single method and call that method, like you've tried :
public class MainActivity extends YouTubeFailureRecoveryActivity {
Button amazonButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeViews();
}
private void initializeViews() {
//Make sure you've declared the buttons before you initialize them.
amazonButton = (Button) findViewById(R.id.amazonButton);
amazonButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Define what should happen when the button is clicked.
}
});
// Add more Views initialization here ...
....
}
}
You need to give the type of the variable when you declare it.
Button amazonButton = (Button) findViewById(R.id.amazonButton);
The alternative is to declare it (but not initialize it) outside of any method and then initialize it later.
Button amazonButton;
/* ... */
private void amazonListener() {
amazonButton = (Button) findViewById(R.id.amazonButton);
}

Null PointerExeption ALL the time?

Why is mainB_news allways null? (in the method onBackPressed())
In onCreate I set a value to the button!!! :(
PS: with findViewById() I get the same error...
public class MainActivity extends Activity {
private Button mainB_news;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainB_news = (Button) findViewById(R.id.mainB_news);
mainB_news.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
setContentView(R.layout.news);
}
});
}
#Override
public void onBackPressed() {
// check if page 2 is open
if (mainB_news != null && mainB_news.isShown()){
setContentView(R.layout.main); // open main view again
return;
}else
super.onBackPressed(); // allows standard use of backbutton for page 1
}
}
THANKS a lot!
Because you change contentView on button click. mainB_news doesn't exist after contentView changing. You shouldn't use setContentView() in this manner. Consider using another activity for showing news.
Because it is not defined in res/layout/main.xml ?

Categories