将TextView添加到布局时的NullPointerExceptions

时间:2014-07-25 00:38:33

标签: java android android-layout

当我将一个TextView添加到LinearLayout时,我正在生成NullPointerExceptions。我在说这个......

public void loadPlayers() {
    LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
    TextView tv = new TextView(this);

    for (int i = 0; i < Game.getPlayers().length; i++) {
        tv.setText(String.valueOf(Game.getPlayers()[i]));
        tv.setPadding(8, 8, 8, 8);
        tv.setTextSize(20);
        tv.setBackgroundColor(0xD0D0D0);

        System.out.println("Got here!");

        lv.addView(tv);
    }
}

在onCreate结束时,我得到“来了!”印在我的控制台上。错误来自

lv.addView(tv);

但我不明白为什么这是一个问题。布局是否尚未加载?如果是这样,我该如何解决?下面是完整的活动,xml和日志。

MainActivity.java:

package com.example.lineupcreator;

import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;


public class MainActivity extends ActionBarActivity
        implements NavigationDrawerFragment.NavigationDrawerCallbacks {

    /* My Methods */

    /**
     * Adds a player, gets input from button
     * @return 
     */
    public void addPlayer(View view) {
        EditText editText = (EditText) findViewById(R.id.edit_message);
        String name = editText.getText().toString();

        LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
        TextView tv = new TextView(this);

        tv.setText(String.valueOf(name));
        tv.setPadding(8, 8, 8, 8);
        tv.setTextSize(20);
        tv.setBackgroundColor(0xD0D0D0);
        lv.addView(tv);// not InformationActivity.tv just write tv

        Game.newPlayer(name);
    }

    /**
     * Loads all of the players
     */
    public void loadPlayers() {
        LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
        TextView tv = new TextView(this);

        for (int i = 0; i < Game.getPlayers().length; i++) {
            tv.setText(String.valueOf(Game.getPlayers()[i]));
            tv.setPadding(8, 8, 8, 8);
            tv.setTextSize(20);
            tv.setBackgroundColor(0xD0D0D0);

            System.out.println("Got here!");

            lv.addView(tv);
        }
    }

    /* Prebuilt Methods */

    /**
     * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
     */
    private NavigationDrawerFragment mNavigationDrawerFragment;

    /**
     * Used to store the last screen title. For use in {@link #restoreActionBar()}.
     */
    private CharSequence mTitle;

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

        mNavigationDrawerFragment = (NavigationDrawerFragment)
                getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
        mTitle = getTitle();

        // Set up the drawer.
        mNavigationDrawerFragment.setUp(
                R.id.navigation_drawer,
                (DrawerLayout) findViewById(R.id.drawer_layout));

        /* My Code */
        Game.init();
        this.loadPlayers();
    }

    @Override
    public void onNavigationDrawerItemSelected(int position) {
        // update the main content by replacing fragments
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
                .commit();
    }

    public void onSectionAttached(int number) {
        switch (number) {
            case 1:
                mTitle = getString(R.string.title_section1);
                break;
            case 2:
                mTitle = getString(R.string.title_section2);
                break;
            case 3:
                mTitle = getString(R.string.title_section3);
                break;
        }
    }

    public void restoreActionBar() {
        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
        actionBar.setDisplayShowTitleEnabled(true);
        actionBar.setTitle(mTitle);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!mNavigationDrawerFragment.isDrawerOpen()) {
            // Only show items in the action bar relevant to this screen
            // if the drawer is not showing. Otherwise, let the drawer
            // decide what to show in the action bar.
            getMenuInflater().inflate(R.menu.main, menu);
            restoreActionBar();
            return true;
        }
        return super.onCreateOptionsMenu(menu);
    }

    @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.
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return 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;
        }

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            ((MainActivity) activity).onSectionAttached(
                    getArguments().getInt(ARG_SECTION_NUMBER));
        }
    }

}

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"
    tools:context="com.example.lineupcreator.MainActivity$PlaceholderFragment" >

    <EditText android:id="@+id/edit_message"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_toLeftOf="@+id/button"
        android:hint="@string/player_name" />

    <Button
        android:id="@+id/button"
        android:layout_width="64dp"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/edit_message"
        android:layout_alignParentRight="true"
        android:onClick="addPlayer"
        android:text="@string/add" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="wrap_content" 
        android:layout_below="@+id/edit_message" >

        <LinearLayout
            android:id="@+id/player_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/darker_gray"
            android:orientation="vertical" />

    </ScrollView>

</RelativeLayout>

日志:

07-24 17:30:48.274: D/ActivityThread(22173): handleBindApplication:com.example.lineupcreator
07-24 17:30:48.274: D/ActivityThread(22173): setTargetHeapUtilization:0.75
07-24 17:30:48.274: D/ActivityThread(22173): setTargetHeapMinFree:2097152
07-24 17:30:48.548: I/System.out(22173): Got here!
07-24 17:30:48.548: D/AndroidRuntime(22173): Shutting down VM
07-24 17:30:48.548: W/dalvikvm(22173): threadid=1: thread exiting with uncaught exception (group=0x418f1ce0)
07-24 17:30:48.555: E/AndroidRuntime(22173): FATAL EXCEPTION: main
07-24 17:30:48.555: E/AndroidRuntime(22173): Process: com.example.lineupcreator, PID: 22173
07-24 17:30:48.555: E/AndroidRuntime(22173): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.lineupcreator/com.example.lineupcreator.MainActivity}: java.lang.NullPointerException
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2215)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2265)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread.access$800(ActivityThread.java:145)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1206)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.os.Handler.dispatchMessage(Handler.java:102)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.os.Looper.loop(Looper.java:136)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread.main(ActivityThread.java:5144)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at java.lang.reflect.Method.invokeNative(Native Method)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at java.lang.reflect.Method.invoke(Method.java:515)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at dalvik.system.NativeStart.main(Native Method)
07-24 17:30:48.555: E/AndroidRuntime(22173): Caused by: java.lang.NullPointerException
07-24 17:30:48.555: E/AndroidRuntime(22173):    at com.example.lineupcreator.MainActivity.loadPlayers(MainActivity.java:64)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at com.example.lineupcreator.MainActivity.onCreate(MainActivity.java:96)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.Activity.performCreate(Activity.java:5231)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-24 17:30:48.555: E/AndroidRuntime(22173):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2169)
07-24 17:30:48.555: E/AndroidRuntime(22173):    ... 11 more
07-24 17:35:48.735: I/Process(22173): Sending signal. PID: 22173 SIG: 9

编辑:

在我看来,四元数是在正确的道路上,但他的解决方案不起作用。我还试图创建一个TextViews数组,如下所示,但这也没有用。

public void loadPlayers() {
    LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);
    TextView[] tv = new TextView[Game.getPlayers().length];

    for (int i = 0; i < Game.getPlayers().length; i++) {
        tv[i] = new TextView(this);
        tv[i].setText(String.valueOf(Game.getPlayers()[i]));
        tv[i].setPadding(8, 8, 8, 8);
        tv[i].setTextSize(20);
        tv[i].setBackgroundColor(0xD0D0D0);

        System.out.println("Got here!");

        lv.addView(tv[i]);
    }
}

更新

我尝试从addPlayer而不是onCreate调用loadPlayers,它完美无缺。从onCreate

调用loadPlayers时会产生唯一的问题

3 个答案:

答案 0 :(得分:0)

好的,错误是你正在尝试从主活动中扩展一个布局组件,但是你正在给片段充气,因此,你的主要布局没有显示在你的屏幕上,是顶部的片段布局。你需要搬家

<LinearLayout
            android:id="@+id/player_list"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@android:color/darker_gray"
            android:orientation="vertical" />

到片段布局。

如果这不起作用,请告诉我。

答案 1 :(得分:0)

我不认为你可以多次向父母添加相同的视图。您需要将新TextView的实例化移动到for循环中。

您的loadPlayers函数应如下所示:

public void loadPlayers() {
    LinearLayout lv = (LinearLayout) findViewById(R.id.player_list);

    for (int i = 0; i < Game.getPlayers().length; i++) {
        TextView tv = new TextView(this);
        tv.setText(String.valueOf(Game.getPlayers()[i]));
        tv.setPadding(8, 8, 8, 8);
        tv.setTextSize(20);
        tv.setBackgroundColor(0xD0D0D0);

        System.out.println("Got here!");

        lv.addView(tv);
    }
}

希望这会有所帮助,如果不是你可能会有更大的问题=(

答案 2 :(得分:0)

Caused by: java.lang.NullPointerException
    at com.example.lineupcreator.MainActivity.loadPlayers(MainActivity.java:64)

您收到NullPointerException的原因是因为您试图从LinearLayout Fragment中获取Activity中夸大的public void loadPlayers() { LinearLayout lv = (LinearLayout) findViewById(R.id.player_list); // R.id.player_list is not inside activity_main.xml // lv is null ... lv.addView(tv[i]); // NullPointerException } } ,特别是这些行:

Fragment

解决此问题的一种方法是将所有逻辑移到onActivityCreated(Bundle savedInstanceState)

PlaceholderFragment中添加onCreate(),并将@Override public void onActivityCreated (Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); /* My Code */ Game.init(); this.loadPlayers(); } 中的两行移至此处。这是为了确保在已经设置活动后调用代码。

loadPlayers()

然后在PlaceholderFragment内移动findViewById()。但是,Fragment内没有onCreateView()。相反,您必须初始化Fragment中的视图。不要忘记在LinearLayout lv; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_main, container, false); lv = (LinearLayout) rootView.findViewById(R.id.player_list); return rootView; }

中声明变量
Fragment

最后,Context使用Activity中的this。虽然您可以使用Activity中的Context来引用其Fragment,但在getActivity()中您不能。相反,请使用public void loadPlayers() { // LinearLayout lv = (LinearLayout) findViewById(R.id.player_list); TextView tv; for (int i = 0; i < Game.getPlayers().length; i++) { tv = new TextView(getActivity()); tv.setText(String.valueOf(Game.getPlayers()[i].getName())); tv.setPadding(8, 8, 8, 8); tv.setTextSize(20); tv.setBackgroundColor(0xD0D0D0); lv.addView(tv); } }

{{1}}