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;
Related
I have a button with a method that is invoked upon clicking.
The method:
public void addToList(View view) {
System.out.println(1);
String str = "";
try{
str = edit.getText().toString();}
catch (Exception ex){
System.out.println( ex );
}
System.out.println(2);
new QueryInList( ).execute(helper, str);
System.out.println(3);
edit.setText(null);
System.out.println(4);
//adapter.notifyDataSetChanged();
}
Well, I always get the exception, it is a Nullpointerexception.
This quite baffles me, because edit IS initalized:
It is declared in the class:
private EditText edit;
and besides, it is initialized in onCreate:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
edit = (EditText)findViewById(R.id.textfield);
setContentView(R.layout.activity_view);
......}
So I wonder why I always get a Nullpointer?
Set the content view, before looking for the items. You dont have a view to find the items in until you set the content view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
edit = (EditText)findViewById(R.id.textfield);
......}
Move edit = (EditText)findViewById(R.id.textfield); after your setContentView statement.
Here is a nice explanation from user #Squonk from another question:
setContentView(...) perfoms something called 'layout inflation'. What that means is it parses the XML in the relevant file (main.xml in your case) and creates instances of all the UI elements within it. It then attaches that view to the Activity. When you call findViewById(...) it doesn't reference your main.xml directly - instead it references the content view attached to the Activity, in other words the one inflated by setContentView(...)
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.
I'm new to android, so maybe I'm doing something horribly wrong. I want to have a particular Activity that shows details about an instance of a "Creature" class for a game. Name, damage taken, that sort of thing.
I'm having a problem getting the creature data to be properly shown in the GUI objects. Both at initial creation (where it should copy the creature's name into the name field) and when a damage mark is added (where it doesn't update to show the proper image).
Here's my mini-example of what I have:
public class CreatureDetailActivity2 extends Activity
{
Creature creature;
public void addMark(View v)
{
// connected to the button via android:onClick="addMark" in the XML
creature.getTrack().addDamage(DamageType.Normal, 1);
refreshDisplay();
new AlertDialog.Builder(this).setTitle(creature.getName())
.setMessage(creature.getTrack().toString()).show();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_creature_detail);
creature = new Creature("Example");
refreshDisplay();
}
public void refreshDisplay()
{
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
final EditText nameField = (EditText) (creatureDetailView
.findViewById(R.id.textbox_creature_name));
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) (creatureDetailView.findViewById(R.id.damageBox0));
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
}
Now the problem is that the app will load up and start, but then none of the widgets will update properly. You can click the button, and it'll show the AlertDialog, and the text of the AlertDialog will change, but the textfield in the activity won't be changed, and the ImageView doesn't change at any point from what it starts as to the one it's supposed to change to.
So I'm very stumped. I can post more about the project's setup if I'm leaving out something important, but I'm not even sure what the problem going on is so I'm not sure what else to include in my question.
final View creatureDetailView = this.getLayoutInflater().inflate(
R.layout.activity_creature_detail, null);
Inflates your Activity's layout into basically nothing, just returning the View it inflated. setContentView is what actually inflates your layout into the Activity's View hierarchy.
Once you inflate your layout you don't need to do it again. Just use findViewById without the reference to a dangling unattached View.
Change your refreshDisplay method to this:
public void refreshDisplay()
{
final EditText nameField = (EditText) findViewById(R.id.textbox_creature_name);
nameField.setText(creature.getName());
final ImageView damageBox0 = (ImageView) findViewById(R.id.damageBox0);
damageBox0.setImageResource(R.drawable.__n);
// in the full program this does the same for 0 through 9, but this is a sample
// also, in the full program, this is a dynamic lookup for the correct pic
// but again, this is just a sample version.
}
Nothing changes because You do it completely wrong.
If You wish to update any view element of current activity You do it like this
View v = findViewById(R.id.element);
v.setText("text");
this is just simple example.
You would need to cast a returned element to correct type like to be able to access all available methods.
What You do wrong is trying to inflate a layout again.
I have two activities, activity one has buttons that refer to activity two and methods in it. I'm trying to use TextView.SetText to put something on the screen but keep getting NullPointerException.
Activity 2:
public class SomeActivity extends Activity {
TextView textview ;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.some_activity);
textview = (TextView) findViewById( R.id.textview );
spill("Some text");
}
public void spill(String s){
textview.setText(s);
}
public void methodCalledFromActivityOne(){
System.out.println("Works");
spill("Why Doesn't this work?");
}
XML has this:
<TextView
android:id="#+id/textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
tools:context=".SomeActivity" />
I'm new to Android and will REALLY appreciate all/any help.
EDIT: The name of the XML is fine, the error only occurs when I press button 1 in activity 1 which calls methodCalledFromActivityOne().
This is what I get from LogCat:
Caused by: java.lang.NullPointerException at android.app.Activity.findViewById at data.storage.SomeActivity.spill at data.storage.SomeActivity.methodCalledFromActivityOne
at data.storage.ActivityOne.button1clicked
textview in activity 2 will be initialized only when onCreate() is called. And onCreate() of activity 2 will be called only when this activity comes into the phone view. You cannot set the values of views of another activity from your current activity. It is a bad idea.
If you want the values to get to activity 2, then send those in an intent.
If you're calling methodCalledFromActivityOne() method from another activity make sure you've created TextView property at that activity also. Otherwise it'll not work.
I have several LinearLayouts contained inside their respective ScrollView which in turn are contained by a ViewFlipper. The odd stuff is that in some of the Layouts once they have the focus, it starts automatically in a place other than the top.
So what can be causing this ? In order to force them to start at the top, is there something like the tabindex property in html ?
Thanks
if you have problem called focus is gone automatically on other place instead of top position's field then you have to write this code simply at onStart() method of activity life cycle with respective field id in my case first field
is referenced by firstfield_et this is the variable of Activity.java file and it is also already referenced by etfirstfield from .xml file
the code is simply as below:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText firstfield_et= (EditText) findViewById(R.id.etfirstfield);
}
#Override
protected void onStart() {
super.onStart();
if(TextUtils.isEmpty(firstfield_et.getText().toString())){
firstfield_et.requestFocus();
}
}