Global Reference findViewById - java

Is it possible to get a reference to an XML element such as a button using findViewById globally in the main java class?
I have so many references that I need to keep on calling them all over again multiple times because I can't use the reference I called in the onCreate method.
private long mode;
private final Button playBtn = (Button)findViewById(R.id.playBtn);
private final TextView aboutTitle = (TextView)findViewById(R.id.aboutTitle);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}
I know that to fix the error would be to reference the button and the textview after the setContentView but the problem is that I need to repeat all my references for each method in the same class.

// try this way (here i'm declare your both view object as globaly for your class so it can be acccess any where in classs and is created onCreate() at first time and further it used directly)
private long mode;
private Button playBtn;
private TextView aboutTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playBtn = (Button)findViewById(R.id.playBtn);
aboutTitle = (TextView)findViewById(R.id.aboutTitle);
playBtn.setTypeface(robotoThin);
aboutTitle.setText("hello world");
}

You have to create member variables for the Views you want to reference and you initialize them in onCreate() once. Then you reference these variables where you need inside the Activity

Related

findViewById method outside the onCreate method?

lately, I was working on a very small training project.
But there is one error in my code:
public class MainActivity extends AppCompatActivity {
TextView textView = (TextView) findViewById(R.id.textview);
#override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView.setText("Welcome");
}
}
but when I tried to cut the textview global variable and paste it inside the onCreate method, the error has gone. Why is this error occur although I already have inflated the textView in a global variable ?!
You need to call findViewById(...) after calling setContentView(...).
Fetching the view before inflating the layout isn’t possible since there is no view.
findViewById() should only be used after setContentView() in onCreate.
That's where your entire layout get inflated. Only then you can access views using findViewById().
This is what you want:
public class MainActivity extends AppCompatActivity {
TextView textView;
#override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
textView.setText("Welcome");
}
}

Android: references to findViewById

I have been doing this for all my activities when I reference an element from my UI, I create a class variable. This can sometimes lead to 10 - 20 class variables just for UI elements:
public class CommentActivity extends AppCompatActivity {
LinearLayout addComment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
addComment = (LinearLayout) findViewById(R.id.addcomment);
addComment.setOnClickListener( // add an onclick listener here //);
}
}
Now, I have observed by looking at other people's code that sometimes they would do this instead:
public class CommentActivity extends AppCompatActivity {
// LinearLayout addComment; no more reference to class variable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
//they just findViewById and add on the onclick listener
findViewById(R.id.addcomment).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
}
Is the second method more memory efficient? There is no longer a class variable strong reference and therefore garbage collection can happen more easily. But I'm just wondering what the risk is of using the second method. If garbage collection happens when using the app, does the addComment linearLayout lose its click functionality?
I'm just trying ways to optimise my app's memory use.
Is the second method more memory efficient?
Not particularly. The LinearLayout addComment reference costs ~8 bytes.
There is no longer a class variable strong reference and therefore garbage collection can happen more easily
Not in this case, since other things are holding onto the LinearLayout. After all, findViewById() is getting the LinearLayout from somewhere.

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.

i get an error stating local variables stringtext and textview2 need to be finalized? If i final them then they wont update if im correct...?

public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText stringtext; // final error here
stringtext = (EditText) findViewById(R.id.editText);
TextView textView2; // final error here
textView2 = (TextView) findViewById(R.id.textView2);
Button startprogram = (Button) findViewById(R.id.button);
View.OnClickListener listener = new View.OnClickListener(){
#Override
public void onClick(View view){
// Insert what you want the button to do here!
setContentView(R.layout.helloworld);
}
};
startprogram.setOnClickListener(listener);
// this is button to check the inserted code
Button checkbutton = (Button) findViewById(R.id.checkbutton);
View.OnClickListener listener1 = new View.OnClickListener(){
public void onClick(View view){
//insert button command here
textView2.setText(stringtext.getEditableText());
}
};
}
i get an error stating local variables stringtext and textview2 need to be finalized? If i final them then they wont update if im correct...?
final just means that a variable's reference cannot be changed. The object state will still change correctly.
If an anonymous inner class (e.g. your onClickListeners) references a local variable, that variable must be final. This is because the anonymous inner class actually receives a copy of that variable, and Java doesn't want the original and the copy to get out of sync.
A primitive type that is marked as final (e.g. an int or a double) cannot change in value; once set, it's stuck. However, a variable that refers to an object is exactly that: a reference (essentially the object's location in memory).
The reference cannot be changed to point to a new object, but the object's fields and method can be used as normal.

TextView doesn't show the required text

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.

Categories