尝试getText时获取空指针错误

时间:2014-04-03 16:06:04

标签: android

我是Android新手,所以请原谅我的无知。我试过搜索论坛,但一直没能找到任何东西让这个工作。我试图使用.getText()。toString()(见下文),但得到一个java.lang.NullPointerException错误。我更改了我的setContentView,以便查看fragment_main.xml,但仍然为我的不同组件返回null。这个目标非常简单,只是为了改变TextView上的文本,因为我刚刚开始。任何帮助将不胜感激。

package com.example.app;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.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.os.Build;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

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

        Button changeTxt = (Button) findViewById(R.id.btnChangeText);
        final TextView textView = (TextView) findViewById(R.id.txtMessage);

        changeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = textView.getText().toString();

                if (text.contains("World")) {
                    textView.setText("Hello Android!");
                }
                else {
                    textView.setText(("Hello World!"));
                }
            }
        });
    }


    public void onStart(){
        super.onStart();
    }

    public void onResume(){
        super.onResume();
    }

    public void onPause(){
        super.onPause();
    }

    public void onStop(){
        super.onStop();
    }

    public void onDestroy(){
        super.onDestroy();
    }

    @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 {

        public PlaceholderFragment() {
        }

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

这是xml:

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Large Text"
        android:id="@+id/txtMessage"
        android:layout_gravity="center_horizontal" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Change Text"
        android:id="@+id/btnChangeText"
        android:layout_gravity="center_horizontal" />
</LinearLayout>

Fllo,更新代码:

XML fragment_main.xml

<LinearLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <FrameLayout
        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/txtMessage1"
        android:layout_gravity="center_horizontal" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Change Text"
            android:id="@+id/btnChangeText1"
            android:layout_gravity="center" />
    </FrameLayout>
</LinearLayout>

主要活动

package com.example.app;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.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.os.Build;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_main);

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


    }


    public void onStart(){
        super.onStart();
    }

    public void onResume(){
        super.onResume();
    }

    public void onPause(){
        super.onPause();
    }

    public void onStop(){
        super.onStop();
    }

    public void onDestroy(){
        super.onDestroy();
    }

    @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 {

        public PlaceholderFragment() {
        }

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

            Button changeTxt = (Button) findViewById(R.id.btnChangeText);
            final TextView textView = (TextView) findViewById(R.id.txtMessage);

            changeTxt.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view)
                {
                    String text = textView.getText().toString();

                    if (text.contains("World"))
                    {
                        textView.setText("Hello Android!");
                    }
                    else
                    {
                        textView.setText(("Hello World!"));
                    }
                }
            });

            return rootView;
        }
    }

}

1 个答案:

答案 0 :(得分:2)

出现 NullPointerException ,因为您的ActivityFragment似乎有相同的布局:

 // Activity
 setContentView(R.layout.fragment_main);

 // Fragment
 View rootView = inflater.inflate(R.layout.fragment_main, container, false);
 return rootView;  

您需要检查您的观看次数(TextView&amp; Button)是否在正确的布局中,而不是另外(我猜activity_main)。

两个解决方案:

  • fragment_main内的观点复制/移至activity_main并更改setContentView(R.layout.activity_main)

  • 或者让你的观点在fragment_main中,并使用以下代码在Fragment中找到你的观点,如下所示:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        Button changeTxt = (Button) rootView.findViewById(R.id.btnChangeText);
        final TextView textView = (TextView) rootView.findViewById(R.id.txtMessage);
    
        changeTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String text = textView.getText().toString();
    
                if (text.contains("World")) {
                    textView.setText("Hello Android!");
                }
                else {
                    textView.setText(("Hello World!"));
                }
           }
        });
        return rootView;
    }
    

希望这会有所帮助。


更新:

1。移除fragment_main中的 FrameLayout 。创建一个名为activity_main的新布局,并将 FrameLayout 添加到其中(使用 id ):

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    android:id="@+id/container" />

2。将onCreate方法中的此布局设置为 Activity ,如:

// onCreate method Activity
setContentView(R.layout.activity_main); 

3。然后,删除 Fragment 声明中的static,这应该是:

public class PlaceholderFragment ... { } 

4。最后,当您尝试在onCreateView方法中查找ID元素时, 始终 膨胀视图用作:

rootView.findViewById(R.id.some_id_example);  

瞧!这应该现在有效。