Android,为什么在根据findViewById分配其值时,此Button保持为null

时间:2014-01-06 19:40:20

标签: android nullpointerexception

我将Button变量的值分配给在我的XML布局中创建的按钮之一,我已经在XML中给出了一个合适的id按钮,并且在将值分配给Button时我会参考这个空。

此方法出现问题:

public void addListenerOnButtons() {


        updateInfoButton = (Button) findViewById(R.id.updateWalkInfoButton);

        updateInfoButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {

                Intent resultIntent = new Intent();
                resultIntent.putExtra("newName", "");
                resultIntent.putExtra("newSDesc", "");
                resultIntent.putExtra("newLDesc", "");
                setResult(RESULT_OK, resultIntent);
                finish();

            }

        });


    helpButton = (ImageButton) findViewById(R.id.helpButton);

    helpButton.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v){

            Intent intent = new Intent(context, HelpScreen.class);
            startActivity(intent);
        }
    });

}

updateInfoButton在此方法后仍为null,这会导致我的应用程序崩溃,此页面的XML如下所示:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/createScrollView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    tools:context=".EditWalksInfoActivity" >

    <RelativeLayout
        android:id="@+id/formLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/editWalkInfoHeaderTextView"
            style="@android:style/TextAppearance.Large"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:text="@string/editWalkInfoHeaderText"
            android:textColor="@color/light_gray" />

        <EditText
            android:id="@+id/editWalkNameEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editWalkTitleTextView"
            android:layout_marginTop="15dp"
            android:ems="6"
            android:hint="@string/createWalkNameHint"
            android:inputType="textPersonName"
            android:textColor="@color/light_gray" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/editWalkShortDescEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editWalkShortDescTextView"
            android:layout_marginTop="15dp"
            android:ems="6"
            android:hint="@string/createWalkShortDescHint"
            android:inputType="text"
            android:textColor="@color/light_gray" >

            <requestFocus />
        </EditText>

        <EditText
            android:id="@+id/editWalkLongDescEditText"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editWalkLongDescTextView"
            android:layout_marginTop="15dp"
            android:ems="6"
            android:hint="@string/createWalkLongDescHint"
            android:inputType="textMultiLine"
            android:textColor="@color/light_gray" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/updateWalkInfoButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/editWalkLongDescEditText"
            android:layout_centerHorizontal="true"
            android:layout_marginTop="15dp"
            android:text="@string/updateWalkInfoButtonText"
            android:textColor="@color/light_gray" />

        <TextView
            android:id="@+id/editWalkShortDescTextView"
            style="@android:style/TextAppearance.Medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_below="@+id/editWalkNameEditText"
            android:layout_marginLeft="18dp"
            android:layout_marginTop="15dp"
            android:text="@string/createWalkShortDescTextView"
            android:textColor="@color/light_gray" />

        <TextView
            android:id="@+id/editWalkTitleTextView"
            style="@android:style/TextAppearance.Medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editWalkShortDescTextView"
            android:layout_below="@+id/editWalkInfoHeaderTextView"
            android:layout_marginTop="15dp"
            android:text="@string/createWalkTitleTextView"
            android:textColor="@color/light_gray" />

        <TextView
            android:id="@+id/editWalkLongDescTextView"
            style="@android:style/TextAppearance.Medium"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editWalkShortDescTextView"
            android:layout_below="@+id/editWalkShortDescEditText"
            android:layout_marginTop="15dp"
            android:text="@string/createWalkLongDescTextView"
            android:textColor="@color/light_gray" />

        <ImageButton
            android:id="@+id/editWalkHelpButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/editWalkTitleTextView"
            android:layout_alignTop="@+id/editWalkInfoHeaderTextView"
            android:background="@color/black"
            android:contentDescription="@string/helpIconAltText"
            android:src="@drawable/help" />
    </RelativeLayout>

</ScrollView>

的manifest.xml

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="22" />

    <permission
        android:name="xxxxxx".MAPS_RECEIVE"
        android:protectionLevel="signature" />

    <!-- Accessing camera hardware -->
    <!-- putting android.hardware.camera prevents non-camera devices using this app -->
    <uses-feature android:name="android.hardware.camera" />
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="xxxxxx".MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:logo="@drawable/ic_launcher"
        android:theme="@style/AppTheme" >
        <uses-library
            android:name="com.google.android.maps"
            android:required="true" />

        <activity
            android:name="xxxxxx.StartScreen"
            android:label="@string/app_name"
            android:screenOrientation="landscape" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="xxxxxx.CreateWalkActivity"
            android:label="@string/title_activity_create_walk"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="xxxxxx.HelpScreen"
            android:label="@string/title_activity_help_screen"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="xxxxxx.WalkRecording"
            android:label="@string/title_activity_walk_recording"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="xxxxxx.CreateNewPOIActivity"
            android:label="@string/title_activity_create_new_poi"
            android:screenOrientation="landscape" >
        </activity>

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="AIzaSyBriHozWKei0lNm0XP2SR3hz8GW790L1eA" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />

        <activity
            android:name="xxxxxx.ConfrimUploadActivity"
            android:label="@string/title_activity_confrim_upload"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="xxxxxx.ServerResponse"
            android:label="@string/title_activity_server_response"
            android:screenOrientation="landscape" >
        </activity>
        <activity
            android:name="xxxxxx.EditWalksInfoActivity"
            android:label="@string/title_activity_edit_walks_info" >
        </activity>
    </application>

</manifest>

这是logcat输出:

01-06 19:09:27.640: E/AndroidRuntime(6958): FATAL EXCEPTION: main
01-06 19:09:27.640: E/AndroidRuntime(6958): Process: dcs.aber.ac.uk.cs211.group02, PID: 6958
01-06 19:09:27.640: E/AndroidRuntime(6958): java.lang.RuntimeException: Unable to start activity ComponentInfo{dcs.aber.ac.uk.cs211.group02/dcs.aber.ac.uk.cs211.group02.EditWalksInfoActivity}: java.lang.NullPointerException
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.os.Handler.dispatchMessage(Handler.java:102)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.os.Looper.loop(Looper.java:136)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread.main(ActivityThread.java:5017)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at java.lang.reflect.Method.invokeNative(Native Method)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at java.lang.reflect.Method.invoke(Method.java:515)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at dalvik.system.NativeStart.main(Native Method)
01-06 19:09:27.640: E/AndroidRuntime(6958): Caused by: java.lang.NullPointerException
01-06 19:09:27.640: E/AndroidRuntime(6958):     at dcs.aber.ac.uk.cs211.group02.EditWalksInfoActivity.addListenerOnButtons(EditWalksInfoActivity.java:78)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at dcs.aber.ac.uk.cs211.group02.EditWalksInfoActivity.onCreate(EditWalksInfoActivity.java:30)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.Activity.performCreate(Activity.java:5231)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
01-06 19:09:27.640: E/AndroidRuntime(6958):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
01-06 19:09:27.640: E/AndroidRuntime(6958):     ... 11 more

编辑:

订购方法:

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_walks_info);
        context = this;
        locateUIElements();
        addListenerOnButtons();
        Bundle bundle = getIntent().getBundleExtra("Walk info");
        if (bundle != null){

            name = bundle.getString("walkTitle");
            sDesc = bundle.getString("walkSDesc");
            lDesc = bundle.getString("walkLDesc");
            setEditTextValues();

        }

    }

5 个答案:

答案 0 :(得分:4)

您的问题中的问题是您的XML中没有id/helpButton

helpButton = (ImageButton) findViewById(R.id.helpButton);

<ImageButton
        android:id="@+id/editWalkHelpButton"

R.id.helpButton可能来自其他资源文件,因此它是有效的标识符。

您看到的后续问题是因为生成的R.java和二进制XML文件中的标识符不同步。在编辑布局XML文件和使用@+id标识符重新排序元素时,这是一个常见问题。解决方案是清理和重建项目。

答案 1 :(得分:2)

您可能尝试在活动视图层次结构膨胀之前获取按钮。在Activity.setContentView。

之后调用addListenerOnButtons方法
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // call sequence is important
    setContentView(R.layout.your_layout);
    addListenerOnButtons();
}

希望这有帮助。

答案 2 :(得分:1)

这里有一个潜在的灾难:

  

updateInfoButton =(Button)findViewById(R.id.updateWalkInfoButton);

有可能在代码执行时,View还没有准备好但是非常高,并且保持空引用,确保在执行setContentView之后将代码移动到某处,也可以在setContentView之后的onCreate中或之后的某处视图已设置...

问候!

答案 3 :(得分:0)

是否设置了错误的上下文? activity_edit_walks_info是您发布的ScrollView Layout XML的名称吗?因为XML中定义的上下文是EditWalksInfoActivity

此外,addListenerOnButtons()中的updateInfoButton是全局设置的吗?如果是这样,你可以发布定义的地方吗?

答案 4 :(得分:0)

解决这个问题的方法是简单地清理项目:

日食中的

转到:

项目&gt;干净,似乎解决了许多关于应用程序与其资源不同步的问题。

特别感谢用户:laalto的建议。