3

NullPointerException当我尝试设置/获取我的 EditText 时,我的应用程序会抛出一个错误。

似乎问题与我的setContentView()方法和未正确膨胀的 xml 布局有关。我相信我必须更改findViewByID我的 EditTexts,例如更改为view.findViewByID. 我已经试过了this.findViewByIDmViewPager.findViewByID但是我找不到错误..

我的部分代码:

private static ArrayList<String> roomList = new ArrayList<String>();
    private static ArrayList<String> deviceList = new ArrayList<String>();

    private static String project_name;
    private static String router_ip;
    private static String port;
    private static String device_name;
    private static String room_name;
    private static String datatype;
    private static String grpaddr;
    private static boolean status;

    private EditText et_project_name;
    private EditText et_router_ip;
    private EditText et_port;

    private Spinner spinner_dpt; 
    private CheckBox cb_checkStatus;
    private EditText et_device_name;
    private EditText et_groupaddress;
    private View textEntryView;

    private static final String[] items={"1.001 (Lichtschalter)", "5.001 (Dimmer/Jalousien)",
          "9.001 (Temperaturanzeige)", "1.008 (Jalousien)"};

    private SectionsPagerAdapter mSectionsPagerAdapter;
    private ViewPager mViewPager;

    private static ManualConfigDBAdapter dbHelper;

    /**
     * OnCreate
     * */ 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_project_manually);

        setup();
    }

    /**
     * Setup
     * */ 
    public void setup(){

        //DATABASE
        // Add project to Database
        dbHelper = new ManualConfigDBAdapter(this);
        dbHelper.open();

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the action bar.
        final ActionBar actionBar = getActionBar();
        // set the app icon as an action to go home
        actionBar.setDisplayHomeAsUpEnabled(true); 
        //enable tabs in actionbar
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding tab.
        // We can also use ActionBar.Tab#select() to do this if we have a reference to the
        // Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }


        //get the controls from the layout
        et_project_name = (EditText) findViewById(R.id.project_name);
        et_router_ip = (EditText) findViewById(R.id.router_ip);
        et_port = (EditText) findViewById(R.id.port);

        //Use a input filter for the input of the IP adress
        InputFilter[] filters = new InputFilter[1];
        filters[0] = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                if (end > start) {
                    String destTxt = dest.toString();
                    String resultingTxt = destTxt.substring(0, dstart) + source.subSequence(start, end) + destTxt.substring(dend);
                    if (!resultingTxt.matches ("^\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3}(\\.(\\d{1,3})?)?)?)?)?)?")) { 
                        return "";
                    } else {
                        String[] splits = resultingTxt.split("\\.");
                        for (int i=0; i<splits.length; i++) {
                            if (Integer.valueOf(splits[i]) > 255) {
                                return "";
                            }
                        }
                    }
                }
            return null;
            }
        };

        et_router_ip.setFilters(filters);

    }

和 LogCat:

02-16 20:09:25.755: E/AndroidRuntime(26658): FATAL EXCEPTION: main
02-16 20:09:25.755: E/AndroidRuntime(26658): java.lang.RuntimeException: Unable to start activity ComponentInfo{de.bertrandt.bertrandtknx/de.bertrandt.bertrandtknx.CreateProjectManually}: java.lang.NullPointerException
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread.access$600(ActivityThread.java:128)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.os.Handler.dispatchMessage(Handler.java:99)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.os.Looper.loop(Looper.java:137)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread.main(ActivityThread.java:4514)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at java.lang.reflect.Method.invokeNative(Native Method)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at java.lang.reflect.Method.invoke(Method.java:511)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at dalvik.system.NativeStart.main(Native Method)
02-16 20:09:25.755: E/AndroidRuntime(26658): Caused by: java.lang.NullPointerException
02-16 20:09:25.755: E/AndroidRuntime(26658):    at de.bertrandt.bertrandtknx.CreateProjectManually.setup(CreateProjectManually.java:152)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at de.bertrandt.bertrandtknx.CreateProjectManually.onCreate(CreateProjectManually.java:75)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.Activity.performCreate(Activity.java:4562)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1053)
02-16 20:09:25.755: E/AndroidRuntime(26658):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1934)
02-16 20:09:25.755: E/AndroidRuntime(26658):    ... 11 more
02-16 20:09:25.770: D/dalvikvm(26658): GC_CONCURRENT freed 396K, 4% free 14704K/15303K, paused 2ms+3ms

XML 文件 activity_create_project_manually:

<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/black" >

    <RelativeLayout
        android:id="@+id/project_save_text"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:background="@color/black"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="10dp"
            android:text="@string/project_name"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/project_name"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView2"
            android:ems="10"
            android:hint="@string/project_name_hint" >
        </EditText>

        <TextView
            android:id="@+id/textView4"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/project_name"
            android:layout_marginTop="10dp"
            android:text="@string/router_ip"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/router_ip"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView4"
            android:digits="0123456789."
            android:ems="10"
            android:hint="@string/router_adress_info"
            android:inputType="numberDecimal|phone" />

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_alignParentLeft="true"
            android:contentDescription="@string/placeholder"
            android:src="@drawable/bertrandtlogoinv" />

        <TextView
            android:id="@+id/info_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/imageView1"
            android:layout_alignParentLeft="true"
            android:gravity="center"
            android:text="@string/info_settings"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:textSize="16dp" />

        <ImageView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/ImageView1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_above="@+id/info_text"
            android:layout_alignParentLeft="true"
            android:contentDescription="@string/placeholder"
            android:paddingBottom="2dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="2dp"
            android:scaleType="fitXY"
            android:src="@color/ics_blue" />

        <ImageView
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/ImageView01"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignTop="@+id/imageView1"
            android:contentDescription="@string/placeholder"
            android:paddingBottom="2dp"
            android:paddingLeft="5dp"
            android:paddingRight="5dp"
            android:paddingTop="2dp"
            android:scaleType="fitXY"
            android:src="@color/ics_blue" />


        <TextView
            android:id="@+id/textView3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/router_ip"
            android:layout_marginTop="10dp"
            android:text="@string/Port"
            android:textAppearance="?android:attr/textAppearanceMedium" />

        <EditText
            android:id="@+id/port"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/textView3"
            android:digits="0123456789"
            android:ems="10"
            android:hint="@string/port_hint"
            android:inputType="number"
            android:maxLength="5" />

    </RelativeLayout>

</RelativeLayout>

XML 文件设置_手动:

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".CreateProjektManually" />

以下行引发错误:

et_router_ip.setFilters(filters);

所有三个 EditText 字段的值是null如果我在调试模式下检查它们。

4

2 回答 2

2

要使用视图寻呼机创建 3 个不同的片段,您应该:

1)使用视图寻呼机和视图寻呼机适配器创建 FragmentActivity。

public class FragmentActivity extends FragmentActivity
{
    private FragmentAdapter adapter;
    private ViewPager pager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment);     
        adapter = new FragmentAdapter(getSupportFragmentManager());
        pager = (ViewPager) findViewById(R.id.pager);
        pager.setAdapter(adapter);
   }

2)用静态实例创建3个片段

public final class Fragment1 extends Fragment
{   
    public static Fragment1 newInstance() {
        return new Fragment1();
    }

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        LinearLayout layout = new LinearLayout(getActivity());
// your fragment xml view
        return view;
    }
}

3)用它填充视图寻呼机适配器;

public class FragmentAdapter extends FragmentPagerAdapter

{    
    public InstallFragmentAdapter(FragmentManager fm) {
        super(fm);
    }
    @Override
    public Fragment getItem(int position) {     
        switch (position) {
            case 0:
                return Fragment1.newInstance();
            case 1:
                return Fragment2.newInstance();
            case 2:
                return Fragment3.newInstance();
        }
        return null;
    }
}
于 2012-10-18T06:16:30.797 回答
0

您应该在 onCreateView 而不是 onCreate 中设置您的 contentview 并调用 setup()。

于 2013-10-09T08:43:19.360 回答