TextView.setText (Android) is causing crashes.. any idea why? - android

Trying to get started with Android development, and doing some basic work with TextViews..
For some reason TextView's setText() method is causing huge problems for me.. here's a simplified version of my code to show what I mean:
package com.example.testapp;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
text = (TextView) findViewById(R.id.text1);
setContentView(R.layout.activity_main);
text.setText("literally anything");
}
}
This will cause a crash, and I don't understand why.. if I create the TextView within the onCreate it works just fine, but if I create it outside of it, it doesn't.. why is that? Has the line "TextView text;" not been executed yet or something?
Thanks!

You need to call setContentView() before initializing the TextView so that your Activity has access to all the layout components.
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.text1);
text.setText("literally anything");

switch these 2 lines
text = (TextView) findViewById(R.id.text1);
setContentView(R.layout.activity_main);
you need to set the content first

From docs:
onCreate(Bundle) is where you initialize your activity. Most
importantly, here you will usually call setContentView(int) with a
layout resource defining your UI, and using findViewById(int) to
retrieve the widgets in that UI that you need to interact with
programmatically.
So this means that if you will reference your views in the layout, you must first set the content view and already then call findViewById method to reference child views of the layout resource defining your activity's UI

text = (TextView) findViewById(R.id.text1);
setContentView(R.layout.activity_main);
text.setText("literally anything");
If "literally anything" is a variable, which often may be the case, be sure that it isn't throwing a NullPointerException. I kept having that problem myself. I fixed it to be:
text = (TextView) findViewById(R.id.text1);
setContentView(R.layout.activity_main);
try {
text.setText("literally anything");
} catch (NullPointerException e) {
// Do something
}
Exceptions can be really useful, so if you're a beginning programmer, I suggest you put exception handling on your list of things to learn soon.

Related

How do I go about accessing a view when the activity is created? [duplicate]

Quick notice: I am using SharedPreferences so that I can reload data when I re-open the app.
Problem
I have a LinearLayout in the main fragment of my application. Everything runs smoothly until I re-open the app and try to reinitialize the LinearLayout.
I am trying to initialize the LinearLayout with findViewById(). I have put the function in many different places. Currently I am trying to get it to work in onCreate and a function that is called from onCreate. Here is my code so far:
public class MainActivity extends AppCompatActivity {
LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout = findViewById(R.id.linearLayout);
// this is where is load the SharedPreferences
// this is where I implement them back into the app ('reload' the app)
reload();
}
public void reload() {
// bunch of other irrelevant stuff
linearLayout = findViewById(R.id.linearLayout);
linearLayout.addView(/*other view*/); // this is where it complains
}
// the is for when the button is clicked
public void submitEntry(View view) {
// this is fine according to Logcat
linearLayout = findViewById(R.id.linearLayout);
}
}
I would expect after initializing it twice, or at least trying to, that is would've caught on but no. Logcat complains that linearLayout is a null object reference. I don't know what to do at this point but it's probably something simple that I've overlooked. Any help would be appreciated.
LinearLayout linearLayout= new LinearLayout(context);
Initialize like this it will help you!

set text to TextView - NullPointerException [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
im working the last days on a small app but since 2 days i cant set a text to my textview. I know that normally it has to be made in this way:
TextView textview1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = findViewById(R.id.tvid1);
textview1.setText("blablabla");
}
In my case is my layout not directly the main layout where the textview is. Im using the default Navigation Drawer Example and their is another layout called that refers to the main-content-layout.
I let the program do something in another java-class and that class return a String Value that has to be displayed in my TextView. But I can get data from EditText-Field they are aswell in the same layout.
And this is the Error when my application has to set the text:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
android.widget.TextView.setText(java.lang.CharSequence)' on a null
object reference
EDIT - 13.05.18 16:00:
when i put TextView calc_price_output into the onCreate methode and the textview set the text. But why he dont do it in another methode that use the same variable :?
PROBLEM SOLVED - But no idea how ...
the problem exists only in the last methode. All other works perfectly.
you need to call the function from oncreate method
private TextView calc_price_output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calc_price_output = findViewById(R.id.tv_calculate_price);
displayOutput("blablabla"); //call the function
}
//the string returns to this method
public void displayOutput(String spritprice){
calc_price_output.setText(spritprice);
}
you have not typecasted your object calc_price_output to hold a reference of textview reference.
just typecast it like this :-
calc_price_output = (TextView)findViewById(R.id.Tvid);
Edit : I suppose you are correctly calling your function displayOutput() in the onCreate() or any event for this change to show.
The answers here suggest that you must call your setText in onCreate. It's not true, you don't have to, you can do it elsewhere, the rule is that you do it after findViewById.
Your Main.java inflates activity_main layout, but the button that you have shown is in act_calculate.xml layout file. Therefore findViewById returns null, either move your button to activity_main or use the include to include it in your main layout.
You should set text in Content XML file instead of Navigation drawer.like this.
e.g:
View view = inflater.inflate(R.layout.fragment_home, container, false);
txtname = view.findViewById(R.id.usersession);
txtname.setText(name);
return view;

How should we set widgets values in Android?

I was looking at my code and I realized that there are at least 3 ways of getting widget's reference in code:
First one (before onCreate):
private TextView textView= (TextView) findViewById(R.id.textView);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
}
Second one (in onCreate):
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
final TextView textView= (TextView) findViewById(R.id.textView);
}
Third one (creating out and setting in onCreate):
private TextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
textView= (TextView) findViewById(R.id.textView);
}
What is the difference between this 3 methods? When should I use them?
You must call setContentView() prior calling findViewById(), therefore on 1st approach will give you null all the times. 2nd and 3rd are the same with the exception for final keyword, but this is Java feature, not Android's.
The first does not guarantee that your widget is actually instantiated, it is not within the onCreate.
Second will be instantiated, but its value can not be changed because it becomes a constant to be the final.
Third, it is a global variable that will be instantiated in onCreate and you can use it in any other part of your code.
If you need to call findViewById() then the call should be anywhere after setContentView. Not before that like in your first option. Your third option creates an instance variable, use it only if the textview will be accessed a lot throughout the class, otherwise just call findViewById wherever you need it.

TabHost crashes when changing a TextView inside it

In short, I set up a tabhost, and since I want the tab's content to have dynamic TextView's (among other things), I try initializing the text and it crashes. I am unsure of why, but commenting out the code that sets the text in the TextView's stopped the crashing.
One reference towards fixing this mentioned using intents to set activities for the tab's content, but apparently this didn't actually fix the crashing, it somehow changed it and then that lead died out without him ever saying how he fixed it, and my attempt at it also failed.
package com.example.main;
//removed imports
#SuppressWarnings("deprecation")
public class MainActivity extends TabActivity {
private boolean atMainMenu;
TextView warframeText;
TextView primaryText;
TextView secondaryText;
TextView meleeText;
TextView sentinelText;
TextView sentinelWeaponText;
Warframe warframe;
PrimaryWeapon primary;
SecondaryWeapon secondary;
MeleeWeapon melee;
Sentinel sentinel;
Weapon sentinelWeapon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
TabHost mTabHost = getTabHost();
//TabHost
mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("Build").setContent(R.id.build));
mTabHost.addTab(mTabHost.newTabSpec("tab2").setIndicator("Stats").setContent(R.id.stats));
TextView title1 = (TextView)mTabHost.getTabWidget().getChildAt(0).findViewById(android.R.id.title);
title1.setTextColor(Color.parseColor("#30A0F0"));
TextView title2 = (TextView)mTabHost.getTabWidget().getChildAt(1).findViewById(android.R.id.title);
title2.setTextColor(Color.parseColor("#30A0F0"));
mTabHost.setCurrentTab(0);
warframeText = (TextView)findViewById(R.id.warframe);
primaryText = (TextView)findViewById(R.id.primary);
secondaryText = (TextView)findViewById(R.id.secondary);
meleeText = (TextView)findViewById(R.id.melee);
sentinelText = (TextView)findViewById(R.id.sentinel);
sentinelWeaponText = (TextView)findViewById(R.id.sentinelWeapon);
//Change To First Time Setup
warframe = new Excalibur();
primary = new BratonMk1();
secondary = new Lato();
melee = new Skana();
setBuild(); //<--removing this fixed the crashing, the method is included after onCreate, it sets the TextView's text
atMainMenu = true;
}
public void setBuild() {
warframeText.setText(warframe.getName());
primaryText.setText(primary.getName());
secondaryText.setText(secondary.getName());
meleeText.setText(melee.getName());
sentinelText.setText(sentinel.getName());
sentinelWeaponText.setText(sentinelWeapon.getName());
}
}
So what I would like to know, if anyone has the answer, why does editing the Textviews contained in a tab layout cause the app to crash and how can I fix this? :/
(also the code I provided is quite shortened, but I believe it contains all the relevant parts to the problem)
You did not initialize sentinel and sentinelWeapon but you are trying to get name from that
sentinelText.setText(sentinel.getName());
sentinelWeaponText.setText(sentinelWeapon.getName());
It May be a cause to your app get crashed

android: adding button to the title of the app?

Is it possible to add a button to the right corner of the app title?
e.g., adding a "refresh" button to the title of "Feed: my feeds"?
http://www.android.com/market/apps/feedr-lg-01.jpg
The simplest way to do that, IMHO, is to get rid of the standard title bar (android:theme="#android:style/Theme.NoTitleBar" in the <activity> element in the manifest) and put your own "title bar" at the top of the activity.
Note, though, that the "button in the title bar" style is more iPhone-ish. Android would typically have that in the option menu, so the UI is less cluttered (at the cost of two taps to do the refresh).
Why don't you try this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final boolean customTitle= requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
if ( customTitle ) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, Set your layout for title here and mention your button in this layout);
}
final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
if ( myTitleText != null ) {
myTitleText.setText("NEW TITLE");
myTitleText.setBackgroundColor(Color.BLUE);
}
}
yep this solveed an issue i had... trimmed version is below...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, Set your layout for title here and mention your button in this layout);
final TextView myTitleText = (TextView) findViewById(R.id.myTitle);
if ( myTitleText != null ) {
/* your code here */
}
}
I think a better approach would be to simply refresh the view if it is active by using a Handler. If your pulling content when the activity is resumed then any time you leave and come back to the view it will refresh. If you are expecting users to sit at the top level of the view and need to update the information then you can handle this with a delayed handler which will call your resume method and periodically refresh the view thus negating the need for a button.
Here is a link to the documentation for the handler class. I would start by looking into the basic use of handler. Then test the sendMessageDelayed method so that at the end of every call you restart the handler. Also be sure to only create a new handler if your activity is the top activity and don't bother refreshing the ui if it is not. Adding a simple isActive flag to on pause and on resume is a decent way to check for this.

Categories

Resources