Question

Might be I am going to ask very silly question. Actually I am a .net developer and now switching to Android Development. I have a text view and I want to put text in it using setText().

My MainActivity.java:

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 txView = (TextView) findViewById(R.id.lblStatus);
        txView.setText("Status Test");
    }

and XML code is:

<TextView
            android:id="@+id/lblStatus"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tvStatusTag"
            android:layout_below="@id/lblImei" />

When I run this application it stops automatically.

Logcat:-

04-29 08:27:02.560 1649-1649/com.example.app 
E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: com.example.app, PID: 1649 
java.lang.RuntimeException: Unable to start activity 
ComponentInfo{com.example.app/com.example.app.MainActivity}: 
java.lang.NullPointerException at 
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) 
at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 
at dalvik.system.NativeStart.main(Native Method) 
Caused by: java.lang.NullPointerException 
at com.example.app.MainActivity.onCreate(MainActivity.java:27) 
at android.app.Activity.performCreate(Activity.java:5231) 
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087) 
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159) 
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245) 
at android.app.ActivityThread.access$800(ActivityThread.java:135) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5017) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515)

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
Was it helpful?

Solution 3

Simply I have deleted TextView component (lblStatus) from fragment_main.xml and made some changes at MainActivity.java. Code is as below

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 txView = new TextView(this);
        txView.setText("Status Text");
        setContentView(txView);
    }

And it is working quite batter.. than other answers because it is very simple :)

OTHER TIPS

try this

  1. You should declare and initialize the TextView in the Fragment
  2. Because your Activity instance state must be null cause you didn't save the Activity instance using onSaveInstanceState() method.
  3. You should add TextView component in fragment_main.xml.

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"
android:background="#e5e5e5"
tools:context="com.example.app.MainActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/textView"
    android:textColor="#FF0000"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

activity_main.xml

<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="com.example.app.MainActivity"
tools:ignore="MergeRootFrame" />

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.app.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

MainActivity.java

package com.example.app;

import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

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

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    /**
     * Declare TextView.
     */
    private TextView myText; 
    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container,
                false);

        /**
         * Inititlize.
         */
        myText = (TextView)rootView.findViewById(R.id.textView);
        return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        /**
         * Set Value for TextView.
         */
        myText.setText("I'm a TextView");
    }


}

}

Result is

result

CODE

     public class MainActivity extends ActionBarActivity
{
    TextView txView;
      @Override

      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);
         txView = (TextView) findViewById(R.id.lblStatus);
  check();
    }

     public void check()
     {
            if (savedInstanceState == null) {
              getSupportFragmentManager().beginTransaction()
                      .add(R.id.container, new PlaceholderFragment())
                      .commit();

               txView.setText("Status Test");
             }
            else
          {

          txView.setText("Status Test1");
         }
     }
      }

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"
    android:orientation="vertical"
      android:background="#FFE7DB"  >
<TextView
            android:id="@+id/lblStatus"
            android:layout_width="300dp"
            android:layout_height="wrap_content"
            android:layout_toRightOf="@id/tvStatusTag"
            android:layout_below="@id/lblImei" />

</RelativeLayout>

Ravi i think you are using appcompat library and 4.4 api level,so if i am right then you have two layouts file in layout folder one is simple activity xml and other one will be for fragment.xml.

and i think you are declaring this TextView in activity.xml not in Fragment xml file,so at run time you are getting null exception so declare this in Fragment.xml.

I triyed this edit code below and it is working fine for Set textview... (If you are trying to extends ActionBarActivity than you must import app_compact_v7 and android.support jar properly) Refresh your project build from project properties in eclipse if there is still showing error...

MainActivity.java :

 public class MainActivity extends Activity {       
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    TextView txView = (TextView) findViewById(R.id.lblStatus);
    txView.setText("Status Test");
}

}

activity_main.xml :

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:gravity="center"
      android:orientation="vertical" >

<TextView
    android:id="@+id/lblStatus"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello" />

  </LinearLayout>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top