-2

我主要在這方面尋求澄清和建議。在我正在處理的應用程序中,我設置了一個用於處理一些基本控件和文本的片段,並將必要的XML從活動佈局文件移到碎片佈局文件中,而不做任何更改。然而,現在當我運行應用程序時,我得到一個NULLPOINTEREXCEPTION,並且它似乎是在我的GameStart活動的第19行中導致的,當我嘗試通過其ID設置textView時。我沒有改變ID,只把它移到了片段佈局文件中,所以我有兩個問題:片段TextView ID造成崩潰

1)究竟是什麼原因發生了,因爲在我解決之前發生了類似的事情,但我沒有看它是在參考文檔發生在Android開發者

2)如何解決這一問題

以下的任何建議的原因是GameStart活動,與logcat中的錯誤,並且有問題的XML文件。在此先感謝,我花了2個小時試圖找到答案。

編輯的文件/ logcat的BELOW

logcat的:

12-04 13:48:06.322  826-826/com.saphiric.simproject E/AndroidRuntime﹕ FATAL EXCEPTION: main 
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.saphiric.simproject/com.saphiric.simproject.GameStart}: java.lang.NullPointerException 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137) 
      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 
      at android.app.ActivityThread.access$600(ActivityThread.java:141) 
      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 
      at android.os.Handler.dispatchMessage(Handler.java:99) 
      at android.os.Looper.loop(Looper.java:137) 
      at android.app.ActivityThread.main(ActivityThread.java:5103) 
      at java.lang.reflect.Method.invokeNative(Native Method) 
      at java.lang.reflect.Method.invoke(Method.java:525) 
      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
      at dalvik.system.NativeStart.main(Native Method) 
    Caused by: java.lang.NullPointerException 
      at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109) 
      at com.saphiric.simproject.GameStart.<init>(GameStart.java:25) 
      at java.lang.Class.newInstanceImpl(Native Method) 
      at java.lang.Class.newInstance(Class.java:1130) 
      at android.app.Instrumentation.newActivity(Instrumentation.java:1061) 
      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128) 
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261) 
            at android.app.ActivityThread.access$600(ActivityThread.java:141) 
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256) 
            at android.os.Handler.dispatchMessage(Handler.java:99) 
            at android.os.Looper.loop(Looper.java:137) 
            at android.app.ActivityThread.main(ActivityThread.java:5103) 
            at java.lang.reflect.Method.invokeNative(Native Method) 
            at java.lang.reflect.Method.invoke(Method.java:525) 
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737) 
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
            at dalvik.system.NativeStart.main(Native Method) 

起始活性(當應用程序試圖啓動GameStart活動發生時的錯誤):

package com.saphiric.simproject; 

import android.content.Intent; 
import android.os.Bundle; 
import android.support.v7.app.ActionBar; 
import android.support.v7.app.ActionBarActivity; 
import android.view.View; 


public class TitleMenu extends ActionBarActivity { 

    public void startGame(View view){ 
     Intent gameStart = new Intent(this, GameStart.class); 
     startActivity(gameStart); 
    } 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     ActionBar actionBar = getSupportActionBar(); 
     actionBar.hide(); 
     setContentView(R.layout.activity_main_menu); 
    } 
} 

片段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"> 

    <!-- Relative layout to handle main interaction area --> 
    <RelativeLayout 
     android:id="@+id/relativeLayout" 
     android:layout_width="wrap_content" 
     android:layout_height="90dp" 
     android:layout_alignParentBottom="true" 
     android:background="@drawable/bg_text"> 

     <TextView 
      android:id="@id/storyText" 
      android:layout_width="wrap_content" 
      android:layout_height="match_parent" 
      android:layout_alignParentLeft="true" 
      android:layout_alignParentStart="true" 
      android:text="@string/story_opening_one" 
      android:textColor="@color/black" /> 

     <Button 
      android:id="@+id/advanceButton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_above="@id/controlsFragment" 
      android:layout_alignParentEnd="true" 
      android:layout_alignParentRight="true" 
      android:background="@drawable/button_advance" 
      android:onClick="advanceGame" /> 

     <Button 
      android:id="@+id/menuButton" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:layout_alignParentEnd="true" 
      android:layout_alignParentRight="true" 
      android:layout_below="@id/advanceButton" 
      android:background="@drawable/menu_button" /> 
    </RelativeLayout> 
</RelativeLayout> 

片段類:

package com.saphiric.simproject; 

import android.app.Fragment; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 

/** 
* Created by Saphiric on 12/4/14. 
*/ 
public class ControlsFragment extends Fragment { 

    /** 
    * Fragment Lifecycle Methods 
    */ 

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

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){ 
     // Inflates the layout resource for the fragment 
     return inflater.inflate(R.layout.controls_fragment, container, false); 
    } 

    @Override 
    public void onPause(){ 

    } 
} 

GameStart活動:

package com.saphiric.simproject; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.DialogInterface; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.TextView; 

/** 
* Created by Saphiric on 11/12/14. 
*/ 
public class GameStart extends Activity{ 

    /** 
    * Necessary activity variables 
    */ 
    protected int clickCount = 0; 
    TextView storyText = (TextView) findViewById(R.id.storyText); 

    /** 
    * Sets up and alert dialogue builder for making decisions 
    * This will need to be revised during production 
    */ 
    AlertDialog.Builder decisionTime = new AlertDialog.Builder(getApplicationContext()); 

    /** 
    * Handles advancing non character based conversations at the beginning 
    * of the story. 
    * If the player decides to investigate the scream, then the app loads the appropriate activity, and the same with the 
    * decision to leave the scene. 
    */ 
    public void advanceGame(View view){ 

     clickCount = clickCount + 1; // Increments clickCount by 1 per click 

     if (clickCount == 1){ 
      storyText.setText(R.string.story_opening_two); 
     } else if(clickCount == 2){ 
      decisionTime.setTitle("Decision Time!"); // Sets the title for the decision box 
      decisionTime.setCancelable(false); // Sets it so that the decision can not be cancelled. 
      decisionTime.setPositiveButton("Investigate",new DialogInterface.OnClickListener() { // Sets up the positive button 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 

       } 
      }); 
      decisionTime.setNegativeButton("Leave the scene.",new DialogInterface.OnClickListener() { // Sets up the negative button 
       @Override 
       public void onClick(DialogInterface dialog, int which) { 

       } 
      }); 
     } 
    } 

    /** 
    * Android activity methods 
    * @param savedInstanceState is the apps savedInstanceState 
    */ 
    @Override 
    public void onCreate(Bundle savedInstanceState){ 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_game_start); 
    } 
} 

GameStart佈局XML:

<?xml version="1.0" encoding="utf-8"?> 
<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="@drawable/bg_school_gate" 
    android:orientation="vertical"> 

    <fragment 
     android:id="@+id/controlsFragment" 
     android:name="com.saphiric.simproject.ControlsFragment" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     tools:layout="@layout/controls_fragment" /> 

</RelativeLayout> 
+2

可能重複[什麼是空指針異常,以及如何解決它?](http://stackoverflow.com/questions/218384/what-is-a-null-pointer-exception-and-how )(**與小sugettion - 另一個問題與過早的findViewById調用**) – Selvin 2014-12-04 17:47:23

回答

0

不,你沒有任何片段這裏,閱讀更多的How to use fragments

但這不是你的問題,它應該像你這樣做。 唯一的問題是您在構造函數中調用了findViewById,或者甚至在此之前。

findViewById只適用於您有UI的情況,所以您必須在setContentViewonCreate後執行所有UI初始化!

TextView storyText; 
... 
@Override 
public void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_game_start); 
    storyText = (TextView) findViewById(R.id.storyText); 
} 

也不要忘記調用show()decisionTime

+0

謝謝你的例子和意見=) – Saphiric 2014-12-04 18:06:00

0

TextView storyText = (TextView) findViewById(R.id.storyText);

這個你設置你的內容查看後,只應調用。 最終的結果應該是:

TextView storyText; 

再上的onCreate

setContentView(R.layout.activity_game_start); 
storyText = (TextView) findViewById(R.id.storyText); 
0

1)發生這種情況的原因是該視圖在您嘗試獲取其引用時尚未實例化。

2)如何解決它:如果你有Fragment,那麼你應該在Fragment.onCreateView()方法中得到它的View的引用。然後,您可以設置ActivityFragment對話,以便根據需要對View進行任何更改。

+0

非常感謝你,我甚至沒有想到這一點。我是一個相當新的程序員,所以我傾向於過度思考。我確實有一個問題,但關於爲什麼它沒有工作,因爲沒有被實例化。在將storyText Id移入片段XML文件之前,該代碼正在工作,自從片段設置以來我根本沒有對其進行修改。這可能是我爲什麼不想移動到我厭倦的地方去獲得它的參考。任何想法爲什麼? – Saphiric 2014-12-04 18:04:07

+0

@ sin8292我在想你之前的佈局也有一個R.id.storyText元素,所以你得到了那個參考。對此的線索是storyText xml中缺少「+」。 – 2014-12-04 18:17:57

+0

它似乎不是,我在設置內容視圖後移動了對TextView引用的嘗試,仍然以相同的方式崩潰。更新LogCat併爲此特定問題中涉及的其餘文件添加代碼。我真的很感謝這個幫助。 – Saphiric 2014-12-04 18:49:12