NPE试图找到Android的碎片按钮ID时抛出 [英] NPE thrown when trying to Find Button ID in Android Fragment

查看:129
本文介绍了NPE试图找到Android的碎片按钮ID时抛出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此问题已多次坚持不管有多少次我重做这一点。据Android开发者,onCreateView过程中获得的ID在一个片段的视图层次的对象,所有的我凝视着放在这里的问题证实了这一点。但是由于某种原因,它总是检查我的设置,因此,我无法继续使用的按钮来上班期间返回null。该片段在该项目的决定事件被加载,每个事件都有不同的决策。因此,我想只使用一个片段和更改按钮文本为宜。不过,我似乎无法让他们不要返回null。我只是需要帮助找出我做错了就是造成NPE。

DecisionFragment.java:

 包com.saphiric.simproject.uimanipulation;进口android.app.Fragment;
进口android.os.Bundle;
进口android.util.Log;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.Button;进口com.saphiric.simproject.R;
进口com.saphiric.simproject.datacontrols.DataCore;公共类DecisionFragment扩展片段{    //活动/全局变量
    私有静态最后弦乐TAG =DecisionFragment;
    DataCore公司DataCore的= DataCore.getInstance();    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);    }    @覆盖
    公共查看onCreateView(LayoutInflater充气器,容器的ViewGroup,捆绑savedInstanceState){
        Log.i(TAG,开始:充气);        //获取句柄可扩展性的重要UI元素
        查看根= inflater.inflate(R.layout.fragment_decision,集装箱,FALSE);
        按钮buttonTrue =(按钮)root.findViewById(R.id.btnChoiceOne);
        按钮buttonFalse =(按钮)root.findViewById(R.id.btnChoiceTwo);
        如果(buttonTrue == NULL){
            的System.out.println(buttonTrue为空);
        }其他{
            的System.out.println(buttonTrue工作正常);
        }        Log.i(TAG,说完:充气);
        如果(根== NULL){
            Log.e(TAG,妈呀充气==空);
        }
        开关(dataCore.controller.getCurrentDecision()){
            案OPSDecision:
// buttonTrue.setText(R.string.ops_decision_one);
// buttonFalse.setText(R.string.ops_decision_two);
                打破;
            默认:
                的System.out.println(错误:没有决策集);
        }
        返回根;
    }    @覆盖
    公共无效onActivityCreated(捆绑savedInstanceState){
        super.onActivityCreated(savedInstanceState);    }
}

fragment_decision.xml:

 < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    的xmlns:工具=htt​​p://schemas.android.com/tool​​s
    机器人:layout_width =match_parent
    机器人:layout_height =90dp
    机器人:方向=横向
    机器人:weightSum =1.0
    工具:上下文=com.saphiric.simproject.uimanipulation.DecisionFragment>    <按钮
        机器人:ID =@ + ID / decisionOne
        机器人:layout_width =0dp
        机器人:layout_height =90dp
        机器人:layout_weight =5
        机器人:文字=@字符串/ defaul_btn
        安卓的onClick =cryingDecisionOne/>    <按钮
        机器人:ID =@ + ID / decisionTwo
        机器人:layout_width =0dp
        机器人:layout_height =90dp
        机器人:layout_weight =5
        机器人:文字=@字符串/ defaul_btn
        安卓的onClick =cryingDecisionTwo/>
< / LinearLayout中>

DayOne.java:

 包com.saphiric.simproject.activities;进口android.app.Activity;
进口android.app.FragmentManager;
进口android.app.FragmentTransaction;
进口android.os.Bundle;
进口android.view.View;
进口android.widget.ImageView;
进口android.widget.RelativeLayout;
进口android.widget.TextView;进口com.saphiric.simproject.R;
进口com.saphiric.simproject.datacontrols.DataCore;
进口com.saphiric.simproject.uimanipulation.ControlsFragment;
进口com.saphiric.simproject.uimanipulation.DecisionFragment;
/ **
 *创建者Saphiric上11/12/14。
 * /
公共类DayOne延伸活动{    / **
     *必要的活动变量
     * /
    ControlsFragment controlsFragment =新ControlsFragment();
    DecisionFragment decisionFragment =新DecisionFragment();
    DataCore公司DataCore的= DataCore.getInstance();    / **
     * Android的活性的方法
     *
     * @参数savedInstanceState是应用savedInstanceState
     * /
    @覆盖
    公共无效的onCreate(捆绑savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_day_one);        //初始化开幕故事文本
        //初始化在DataController类的dayProgress变量
        字符串storyStart = getResources()的getString(R.string.story_opening_one)。
        dataCore.controller.setCurrentText(storyStart);
        dataCore.controller.setCurrentDecision(OPSDecision);        //把手,片段管理
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        //在它的初始状态为活动的用户界面将添加ControlsFragment。
        fragmentTransaction.add(R.id.fragmentContainer,controlsFragment);
        fragmentTransaction.commit();
    }    @覆盖
    公共无效onResume(){
        super.onResume();    }    公共无效cryingDecisionOne(查看视图){        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());        //设置cryingDecision故事锁
        dataCore.locks.setCryingDecision(真);
        dataCore.controller.setCurrentDecision(HLSOne);        //删除的决定片段与片段控制取代它
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        //设置要拉到storyText文
        字符串决定= getResources()的getString(R.string.crying_decision_true)。
        dataCore.controller.setCurrentText(决定);        fragmentTransaction.replace(R.id.fragmentContainer,controlsFragment);
        fragmentTransaction.commit();
    }    公共无效cryingDecisionTwo(查看视图){        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());        //设置cryingDecision选择
        dataCore.locks.setCryingDecision(假);
        dataCore.controller.setCurrentDecision(HWSOne);        //删除的决定片段与片段控制取代它
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        //更新的currentText更新的故事视图
        字符串决定= getResources()的getString(R.string.crying_decision_false)。
        dataCore.controller.setCurrentText(决定);        fragmentTransaction.replace(R.id.fragmentContainer,controlsFragment);
        fragmentTransaction.commit();
    }    公共无效advanceGameFunction(查看视图){        串textUpdate;        //把手,片段管理
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();        //成于处理UI组件
        TextView的storyText =(的TextView)findViewById(R.id.storyText);
        RelativeLayout的gameStart =(RelativeLayout的)findViewById(R.id.gameStart);
        ImageView的charOne =(ImageView的)findViewById(R.id.char_one);
        ImageView的charTwo =(ImageView的)findViewById(R.id.char_two);
        ImageView的charThree =(ImageView的)findViewById(R.id.char_three);
        ImageView的charFour =(ImageView的)findViewById(R.id.char_four);        //增量DataController类数据变量
        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
        的System.out.println(dataCore.controller.getDayProgress());        //切换的情况下处理一天的进展
        开关(dataCore.controller.getDayProgress()){
            情况1:
                textUpdate = getResources()的getString(R.string.story_opening_two)。
                dataCore.controller.setCurrentText(textUpdate);
                storyText.setText(dataCore.controller.getCurrentText());
                打破;
            案例2:
                fragmentTransaction.replace(R.id.fragmentContainer,decisionFragment);
                fragmentTransaction.commit();
                打破;
            案例3:
                如果(dataCore.locks.getCryingDecision()){
                    storyText.setText(dataCore.controller.getCurrentText());                }其他{
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                打破;
            情况4:
                如果(dataCore.locks.getCryingDecision()){
                    textUpdate = getResources()的getString(R.string.ops_d1_line1)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }其他{
                    textUpdate = getResources()的getString(R.string.ops_d2_line1)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                打破;
            案例5://过渡到腿部受伤,如果现场哭泣的决策是真实的,走廊的场景,如果假
                如果(dataCore.locks.getCryingDecision()){
                    gameStart.setBackgroundResource(R.drawable.bg_gym_front);
                    textUpdate = getResources()的getString(R.string.hls_line1)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }其他{
                    gameStart.setBackgroundResource(R.drawable.bg_hallway);
                    textUpdate = getResources()的getString(R.string.hws_line1)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                打破;
            情况6:
                如果(dataCore.locks.getCryingDecision()){
                    textUpdate = getResources()的getString(R.string.hls_line2)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }其他{
                    textUpdate = getResources()的getString(R.string.hws_line2)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                打破;
            案例7:
                如果(dataCore.locks.getCryingDecision()){
                    charOne.setVisibility(View.VISIBLE);
                    textUpdate = getResources()的getString(R.string.hls_line3)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }其他{                }
                打破;
            案例8:
                如果(dataCore.locks.getCryingDecision()){
                    textUpdate = getResources()的getString(R.string.hls_line4)。
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }其他{                }
                打破;
            案例9:
                如果(dataCore.locks.getCryingDecision()){                }其他{                }
                打破;
            默认:
                的System.out.println(默认情况下,所谓的);
        }
    }
}


解决方案

您使用了错误的ID在你的code!在布局按钮具有ID decisionOne decisionTwo 但在你的code使用的是 btnChoiceOne btnChoiceTwo

要修复它替换这样的:

 按钮buttonTrue =(按钮)root.findViewById(R.id.btnChoiceOne);
按钮buttonFalse =(按钮)root.findViewById(R.id.btnChoiceTwo);

本在 DecisionFragment

 按钮buttonTrue =(按钮)root.findViewById(R.id.decisionOne);
按钮buttonFalse =(按钮)root.findViewById(R.id.decisionTwo);

This issue has persisted repeatedly no matter how many times I redo this. According to Android Developers, the ID to an object in the View Hierarchy of a fragment is obtained during onCreateView, and all of the questions I've pored over on here confirm this. However for some reason it ALWAYS returns null during the check I have setup and therefore I can not proceed to work with the buttons. The Fragment gets loaded during "decision events" in this project, and each event has different decisions. Thus I want to use just one fragment and change the button texts as appropriate. However I can not seem to get them not to return null. I just need help to figure out what I am doing wrong that is causing the NPE.

DecisionFragment.java:

package com.saphiric.simproject.uimanipulation;

import android.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;

public class DecisionFragment extends Fragment {

    // Activity/Global variables
    private static final String TAG = "DecisionFragment";
    DataCore dataCore = DataCore.getInstance();

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

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.i(TAG, "Begin: Inflate");

        // Gets handles to important UI elements for scalability
        View root = inflater.inflate(R.layout.fragment_decision, container, false);
        Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
        Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);


        if(buttonTrue == null){
            System.out.println("buttonTrue is null");
        } else {
            System.out.println("buttonTrue is working fine");
        }

        Log.i(TAG, "Finished: Inflate");
        if (root == null){
            Log.e(TAG, "omg Inflate == null");
        }
        switch (dataCore.controller.getCurrentDecision()){
            case "OPSDecision":
//                buttonTrue.setText(R.string.ops_decision_one);
//                buttonFalse.setText(R.string.ops_decision_two);
                break;
            default:
                System.out.println("ERROR: No decision set");
        }
        return root;
    }

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

    }
}

fragment_decision.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="90dp"
    android:orientation="horizontal"
    android:weightSum="1.0"
    tools:context="com.saphiric.simproject.uimanipulation.DecisionFragment">

    <Button
        android:id="@+id/decisionOne"
        android:layout_width="0dp"
        android:layout_height="90dp"
        android:layout_weight=".5"
        android:text="@string/defaul_btn"
        android:onClick="cryingDecisionOne"/>

    <Button
        android:id="@+id/decisionTwo"
        android:layout_width="0dp"
        android:layout_height="90dp"
        android:layout_weight=".5"
        android:text="@string/defaul_btn"
        android:onClick="cryingDecisionTwo"/>
</LinearLayout>

DayOne.java:

package com.saphiric.simproject.activities;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.saphiric.simproject.R;
import com.saphiric.simproject.datacontrols.DataCore;
import com.saphiric.simproject.uimanipulation.ControlsFragment;
import com.saphiric.simproject.uimanipulation.DecisionFragment;


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

    /**
     * Necessary activity variables
     */
    ControlsFragment controlsFragment = new ControlsFragment();
    DecisionFragment decisionFragment = new DecisionFragment();
    DataCore dataCore = DataCore.getInstance();

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

        // Initializes the opening story text
        // Initializes the dayProgress variable in DataController
        String storyStart = getResources().getString(R.string.story_opening_one);
        dataCore.controller.setCurrentText(storyStart);
        dataCore.controller.setCurrentDecision("OPSDecision");

        // Handles for fragment management
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // UI will add the ControlsFragment in it's starting state for that activity.
        fragmentTransaction.add(R.id.fragmentContainer, controlsFragment);
        fragmentTransaction.commit();
    }

    @Override
    public void onResume(){
        super.onResume();

    }

    public void cryingDecisionOne(View view) {

        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());

        // Sets cryingDecision Story Lock
        dataCore.locks.setCryingDecision(true);
        dataCore.controller.setCurrentDecision("HLSOne");

        // Removes the decision fragment and replaces it with the controls fragment
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Sets the text to be pulled to storyText
        String decision = getResources().getString(R.string.crying_decision_true);
        dataCore.controller.setCurrentText(decision);

        fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
        fragmentTransaction.commit();
    }

    public void cryingDecisionTwo(View view) {

        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());

        // Sets cryingDecision choice
        dataCore.locks.setCryingDecision(false);
        dataCore.controller.setCurrentDecision("HWSOne");

        // Removes the decision fragment and replaces it with the controls fragment
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Updates the currentText for updating the story view
        String decision = getResources().getString(R.string.crying_decision_false);
        dataCore.controller.setCurrentText(decision);

        fragmentTransaction.replace(R.id.fragmentContainer, controlsFragment);
        fragmentTransaction.commit();
    }

    public void advanceGameFunction(View view) {

        String textUpdate;

        // Handles for fragment management
        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

        // Obtains handles to UI components
        TextView storyText = (TextView) findViewById(R.id.storyText);
        RelativeLayout gameStart = (RelativeLayout) findViewById(R.id.gameStart);
        ImageView charOne = (ImageView) findViewById(R.id.char_one);
        ImageView charTwo = (ImageView) findViewById(R.id.char_two);
        ImageView charThree = (ImageView) findViewById(R.id.char_three);
        ImageView charFour = (ImageView) findViewById(R.id.char_four);

        // Increments the data variable in DataController
        dataCore.controller.setDayProgress(dataCore.controller.getDayProgress());
        System.out.println(dataCore.controller.getDayProgress());

        // Switch case for handling day progression
        switch (dataCore.controller.getDayProgress()) {
            case 1:
                textUpdate = getResources().getString(R.string.story_opening_two);
                dataCore.controller.setCurrentText(textUpdate);
                storyText.setText(dataCore.controller.getCurrentText());
                break;
            case 2:
                fragmentTransaction.replace(R.id.fragmentContainer, decisionFragment);
                fragmentTransaction.commit();
                break;
            case 3:
                if (dataCore.locks.getCryingDecision()) {
                    storyText.setText(dataCore.controller.getCurrentText());

                } else {
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                break;
            case 4:
                if (dataCore.locks.getCryingDecision()) {
                    textUpdate = getResources().getString(R.string.ops_d1_line1);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                } else {
                    textUpdate = getResources().getString(R.string.ops_d2_line1);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                break;
            case 5: // Transition to hurt leg scene if Crying Decision is true, hallway scene if false
                if (dataCore.locks.getCryingDecision()){
                    gameStart.setBackgroundResource(R.drawable.bg_gym_front);
                    textUpdate = getResources().getString(R.string.hls_line1);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }else{
                    gameStart.setBackgroundResource(R.drawable.bg_hallway);
                    textUpdate = getResources().getString(R.string.hws_line1);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                break;
            case 6:
                if(dataCore.locks.getCryingDecision()){
                    textUpdate = getResources().getString(R.string.hls_line2);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }else{
                    textUpdate = getResources().getString(R.string.hws_line2);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }
                break;
            case 7:
                if(dataCore.locks.getCryingDecision()){
                    charOne.setVisibility(View.VISIBLE);
                    textUpdate = getResources().getString(R.string.hls_line3);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }else {

                }
                break;
            case 8:
                if(dataCore.locks.getCryingDecision()){
                    textUpdate = getResources().getString(R.string.hls_line4);
                    dataCore.controller.setCurrentText(textUpdate);
                    storyText.setText(dataCore.controller.getCurrentText());
                }else{

                }
                break;
            case 9:
                if(dataCore.locks.getCryingDecision()){

                }else{

                }
                break;
            default:
                System.out.println("Default case called");
        }
    }
}

解决方案

You are using the wrong ids in your code! The buttons in your layout have the id decisionOne and decisionTwo but in your code you are using btnChoiceOne and btnChoiceTwo.

To fix it replace this:

Button buttonTrue = (Button) root.findViewById(R.id.btnChoiceOne);
Button buttonFalse = (Button) root.findViewById(R.id.btnChoiceTwo);

with this in your DecisionFragment:

Button buttonTrue = (Button) root.findViewById(R.id.decisionOne);
Button buttonFalse = (Button) root.findViewById(R.id.decisionTwo);

这篇关于NPE试图找到Android的碎片按钮ID时抛出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆