This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I have a problem with my Android application. If I use setText() method for a textView I have problem like: The Application has stopped unexpectedly. Please try again.
Code of the application:
public class TC1 extends ActionBarActivity {
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tc1);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
textView = (TextView)findViewById(R.id.textView);
textView.setText("Hi"); // wrong line
}
...
}
XML fragment:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.tc.TC1$PlaceholderFragment" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="35dp"
android:layout_marginTop="20dp"
android:text="Text" />
</RelativeLayout>
Your TextView is part of the Fragment xml but you try to get it from the Activity layout. Move the findViewById() call to the onCreateView() method of your Fragment.
For future questions:
Please do not quote "The Application has stopped unexpectedly" instead check the LogCat output for error messages and stack traces. The error message you quoted is the default crashed information for the user, nothing that provides any detailed informations for us developers.
add this to your code
View view = inflater.inflate(R.layout.fragment_blank, R.id.container,false);
and change
textView = (TextView)findViewById(R.id.textView);
to this
textView = (TextView)view.findViewById(R.id.textView);
Your code is currently trying to access your main activities view which does not contain your textview. Another option is to access it through your fragment in a similar fashion.
It seems that textview is part of fragment not activity_tc1.
So either use textview in activity_tc1 layout. or use textview in onCreateView method of fragment. where fragment_tc1 will be your fragment name.
For example
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tc1, container,
false);
TextView textView = (TextView) rootView.findViewById(R.id.textView);
textView.setText("Hi");
return rootView;
}
Related
I have the following fragment working in view pager:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/window_background"
android:id="#+id/font"
tools:context="com.cuentos.lib.cuentosmusicales.Libro">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:gravity="center"
android:id="#+id/titleBook"
android:textSize="25sp"
android:textColor="#2211CC"
android:text="#string/hello_blank_fragment" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/titleBook"
android:id="#+id/textBook"
android:textSize="15sp"
android:textColor="#44BB11"
android:text="#string/hello_blank_fragment" />
</RelativeLayout>
and i want to modify textview values from fragment class
public class Libro extends Fragment {
String titleLibro;
String text;
TextView title, text1;
public Libro() {}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_libro, container, false);
title = (TextView) view.findViewById(R.id.titleBook);
text1 = (TextView) view.findViewById(R.id.textBook);
title.setText("hi friends");
text1.setText("text");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_libro, container, false);
}
}
So, I detect im not able to change data because there is no change, so how I can instanciate textview in fragment?
First, you're inflating your view two times. There's one on the first line of the onCreateView, which is the one that you modify the TextViews, but in the return statement you create and return another, you're not returning the one you modified, but a new one instead, so the view that will be presented in the UI is the not modified.
Also, you're calling the findViewById in the wrong lifecycle stage. Notice that onCreateView returns the view that will be present in your fragment. It's not possible to retrieve a view component like yours TextViews that way, because the view itself doesn't exists yet.
The right method to modify your view components is in the onViewCreated:
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
title = (TextView) view.findViewById(R.id.titleBook);
text1 = (TextView) view.findViewById(R.id.textBook);
title.setText("hi friends");
text1.setText(text);
}
Try setting the text when overriding your Fragments onActivityCreated or onResume methods.
I have tried everything I can possibly think of, I have tried many solutions in Stack as well. None seem to resolve my issue. I am trying to pass a string that I passed from an earlier intent (parsed JSON data). Everytime I call set text I get a Null Pointer Exception, I have tried using a method to set the text as well as just setting it. Any assistance would be greatly appreciated.
This is the fragment I am trying to update.
public class HomeFragment extends Fragment{
TextView tv;
public HomeFragment(){}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LayoutInflater lf = getActivity().getLayoutInflater();
View rootView = lf.inflate(R.layout.fragment_home, container, false);
tv = (TextView) rootView.findViewById(R.id.accountName);
tv.setText("test");
return rootView;
}
}
I just put a regular string in to test. Here is the XML.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="#+id/lblCompany"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="71dp" />
</RelativeLayout>
Thanks In advance for absolutely any help.
This is the id set on your TextView in xml:
android:id="#+id/lblCompany"
This is the id you are searching for in onCreateView:
tv = (TextView) rootView.findViewById(R.id.accountName);
The ids need to match for you to update the text in that particular TextView. Try
tv = (TextView) rootView.findViewById(R.id.lblCompany);
instead.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I don't understand why this code does not running:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matchpage);
SeekBar sb1 = (SeekBar) findViewById(R.id.seek1);
sb1.setEnabled(false);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
sb1 will be null.
Why?
I will try to answer one thing from my experience that the error is coming in SeekBar sb1 = (SeekBar) findViewById(R.id.seek1); but what i have noticed android compiles code from bottom so it might happen that the reason is above or somewhere else so what i will suggest replace the code in this manner :-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_matchpage);
}
then if it executes then just add SeekBar sb1 = (SeekBar) findViewById(R.id.seek1); below setContentview
its bit big but since you didnt provided the xml and we cant figure out if its package issue or something else so i tried to go really primitive and fundamental...
hope it helps.
You likely are using a Fragment. You should have in your code a class called PlaceHolderFragment, that has an onCreateView method.
In that project you have two xml layout, one named activity_matchpage and other for the fragment, fragment_main. You need to modify the latter and keep the first like this:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="youor.packaque.MainActivity"
tools:ignore="MergeRootFrame" />
And in fragment_main, you declare your Views.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.tformacion.finale.MainActivity$PlaceholderFragment" >
<!-- Your Views here -->
</RelativeLayout>
Then, in your Java code, in PlaceHolderFragment, inside of onCreateView:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
seekBar = (seekBar) rootView.findViewById(R.id.yourSeekBarId);
}
If you want to get rid of the fragment you simply create your XML in activity_matchpage and do not add the fragment, so, remove this:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
I downloaded latest android SDK which uses api level 19.
When I use setText there is no problem in earlier version of SDK but in the latest version I wrote the same code but when I install the app on my phone it forces to exit. This error occurs when I use setText(). However I use the same code earlier version of SDK but there is no error. I couldn't find the issue. Please help.
Here is my code
Activity:
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
TextView txt = (TextView) findViewById(R.id.textView1);
txt.setText("Düğme");
}
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.yeni.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="104dp"
android:layout_marginTop="62dp"
android:text="TextView" />
Your textView1 is in the fragment layout and not in the activity layout. Activity onCreate() is too early to access it with findViewById() on the activity view hierarchy.
Move the findViewById() and setText() to the PlaceholderFragment onCreateView() and call findViewById() on the inflated rootView there, e.g.
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView txt = (TextView) rootView.findViewById(R.id.textView1);
txt.setText("Düğme");
Try this:
Check your logcat: fix the error and then you should do this:
Remove the Import R from your activity which can be found at the top of your activity file, and clean + rebuild your solution.
I have a simple Android app. The layout folder shows an activity_main.xml file and a fragment_main.xml file. In that fragment.xml file I have placed a button that I've named buttonTest.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.snapvest.thunderbird.app.MainActivity$PlaceholderFragment">
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TEST"
android:id="#+id/buttonTest"
android:layout_gravity="center_horizontal" />
</LinearLayout>
in the MainActivity.java file I'm trying to gain access to that buttonTest.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
// Get access to the buttons
final Button buttonTest = (Button)findViewById(R.id.buttonTest);
}
It compiles just fine. But when I run it the buttonTest variable comes back as a null pointer.
Why is it not finding the buttonTest object?
I think I found the solution. MainActivity.java sets up the activity_main.xml which then uses fragment_main.xml as its (initially) single, primary fragment. That's why we are supposed to actually put all of our UI for the activity primarily in fragment_main.xml (and actually put NOTHING in activity_main.xml).
Near the bottom of MainActivity.java there is a section that initializes the fragment_main.xml. And it is THERE that I need to gain access to the buttons and other objects of the UI for the fragment. Such as:
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Get access to the buttons
final Button buttonAvailableOptions = (Button)rootView.findViewById(R.id.buttonAvailableOptions);
return rootView;
}
}
Most of that, above, is automatically added by Android Studio. The part starting with "Get access to the button" is mine and is where you set up any access to or processing of the buttons and other UI objects.
The reason why findViewById() is failing to find the button is because setContentView() primes findViewById() to only look in the layout.xml file you gave to setContentView(), and your button is not located in R.layout.activity_main. If your button is located in the Fragment (which it appears to be) then you should be accessing and manipulating it from the Fragment, not the Activity. This ensures that your Activity and Fragment logic stay decoupled, allowing you to re-use the Fragment with different Activities.
You can use like this.
final Button buttonAvailableOptions = getActivity().findViewById(R.id.buttonAvailableOptions);