空指针异常 - Android片段中的按钮

时间:2016-04-14 22:24:33

标签: android android-fragments nullpointerexception

目前我正致力于Android中Fragment和Activity之间的沟通。我想在这里实现的是在Fragment中的按钮上设置onClickListener。然而,NPE发生,我不知道为什么。堆栈流程中有许多类似的问题,但我没有找到适合我的问题。以下是我的代码和logcat。已经被困在这里一段时间,希望有人可以帮助我!

logcat的:

> 04-14 17:53:02.163 15136-15136/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start activity
> ComponentInfo{com.example.ivylin.corewar/com.example.ivylin.corewar.assistantWidgets.WarriorBattleSelfScreen}:
> android.view.InflateException: Binary XML file line #7: Error
> inflating class fragment
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:144)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5221)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:  Caused by: android.view.InflateException: Binary XML file line #7: Error
> inflating class fragment
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:763)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.example.ivylin.corewar.assistantWidgets.WarriorBattleSelfScreen.onCreate(WarriorBattleSelfScreen.java:36)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5933)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:144) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5221) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void
> android.widget.Button.setOnClickListener(android.view.View$OnClickListener)'
> on a null object reference
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.example.ivylin.corewar.assistantWidgets.WarriorBattleFragment.onCreateView(WarriorBattleFragment.java:46)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Fragment.performCreateView(Fragment.java:2053)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:870)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1045)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.FragmentManagerImpl.addFragment(FragmentManager.java:1147)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2116)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Activity.onCreateView(Activity.java:5282)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:34)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.rInflate(LayoutInflater.java:806) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:504) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:414) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.view.LayoutInflater.inflate(LayoutInflater.java:365) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.example.ivylin.corewar.assistantWidgets.WarriorBattleSelfScreen.onCreate(WarriorBattleSelfScreen.java:36) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Activity.performCreate(Activity.java:5933) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.access$800(ActivityThread.java:144) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:102) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:135) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5221) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Native Method) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:372) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899) 
>     04-14 17:53:02.163 15136-15136/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

似乎logcat主要告诉按钮bOK为空。查看下面的详细代码。

我的片段:

public class WarriorBattleFragment extends Fragment implements  View.OnClickListener {
private RecyclerView recyclerView;
private WarriorBattleAdapter adapter;

EditText nP1;
EditText nP2;
Button bStart;
static private int click;

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

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) {
    View layout = inflater.inflate(R.layout.activity_warrior_self_battle_recyclerview, container, false);
    recyclerView = (RecyclerView) layout.findViewById(R.id.recycler_view);
    LinearLayoutManager layoutManager;

    bStart = (Button) recyclerView.findViewById(R.id.bOK);
    nP1 = (EditText) recyclerView.findViewById(R.id.nP1);
    nP2 = (EditText) recyclerView.findViewById(R.id.nP2);
    bStart.setOnClickListener(this);

    layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new WarriorBattleAdapter(getActivity());
    recyclerView.setAdapter(adapter);
    return layout;
}


@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bStart:
            if (UserInformation.selectedBW[0].equals("") && UserInformation.selectedBW[1].equals("")) {
                Toast.makeText(getActivity().getApplicationContext(), "Please Choose A Warrior", Toast.LENGTH_SHORT).show();
            } else {
                click++;
                if (click == 1) {
                    nP1.setText(UserInformation.selectedBW[0]);
                    adapter.setAdded(1);
                } else if (click == 2) {
                    bStart.setText("BATTLE!");
                } else if (click == 3) {
                    Toast.makeText(getActivity().getApplicationContext(), "WARRIOR FILES UPLOADING", Toast.LENGTH_SHORT).show();
                }
            }
            if (!UserInformation.selectedBW[0].equals("")) {
                Intent intent = new Intent(getActivity().getApplicationContext(), DemoDisplay.class);
                intent.putExtra("wName", UserInformation.selectedBW[0]);
                intent.putExtra("MODE", UserInformation.selectedBW[0]);
                startActivity(intent);

            } else {
                Toast.makeText(getActivity().getApplicationContext(), "Please select one warrior", Toast.LENGTH_SHORT).show();
            }
            break;
    }

}
}

我的活动:

public class WarriorBattleSelfScreen extends AppCompatActivity implements View.OnClickListener {
Button bBack;
Intent intent;
static int click;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // set to full screen
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_warrior_battle_self_screen);
    bBack = (Button) findViewById(R.id.bBack);

    // THIS PART IS FOR TEST
    UserInformation.empty = false;
    WarriorCardEntity imp = new WarriorCardEntity();
    imp.title = "Imp";
    imp.image = R.drawable.w9;
    UserInformation.dataContainer.put(0, imp);
    WarriorCardEntity rave = new WarriorCardEntity();
    rave.title = "Rave";
    rave.image = R.drawable.w10;
    UserInformation.dataContainer.put(1, rave);
    WarriorCardEntity lin = new WarriorCardEntity();
    lin.title = "lin";
    lin.image = R.drawable.w20;
    UserInformation.dataContainer.put(2, lin);

    bBack.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.bBack:
            finish();
            break;
    }
}
}
片段中的

XML:

activity_warrior_self_battle_recyclerview

<?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"
    android:fitsSystemWindows="true"
    android:screenOrientation="landscape"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_view"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_alignParentBottom="true">
        </android.support.v7.widget.RecyclerView>


        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="P1: "
            android:textSize="20sp"
            android:textColor="@color/white"
            android:id="@+id/tP1"
            />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/nP1"
            android:layout_toRightOf="@+id/tP1"
            android:hint="WARRIOR1"
            android:textColor="@color/white"
            android:textColorHint="@color/white"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="P2: "
            android:layout_marginLeft="400dp"
            android:textSize="20sp"
            android:textColor="@color/white"
            android:id="@+id/tP2"
            />
        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/nP2"
            android:layout_toRightOf="@+id/tP2"
            android:layout_alignParentRight="true"
            android:hint="WARRIOR2"
            android:textColor="@color/white"
            android:textColorHint="@color/white"/>

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OK"
            android:background="@drawable/button"
            android:textColor="@color/white"
            android:id="@+id/bOK"
            android:layout_marginRight="33dp"
            android:layout_marginEnd="33dp"
            android:layout_marginBottom="0dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />


    </RelativeLayout>
</RelativeLayout>

活动中的XML-- activity_warrior_battle_self_screen

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:screenOrientation="landscape"
    android:background="@drawable/background_gene">

    <fragment class="com.example.ivylin.corewar.assistantWidgets.WarriorBattleFragment"
        android:id="@+id/b_self_fragment"
        android:layout_width="match_parent"
        android:layout_height="320dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/Add"
        android:layout_toEndOf="@+id/Add"
        android:layout_marginLeft="30dp" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Back"
        android:background="@drawable/button"
        android:textColor="@color/white"
        android:id="@+id/bBack"
        android:layout_marginLeft="33dp"
        android:layout_marginStart="33dp"
        android:layout_marginBottom="20dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true" />

</RelativeLayout>

3 个答案:

答案 0 :(得分:1)

您在RecyclerView上呼叫findViewById()

您需要在根视图中调用它:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance) {
    View layout = inflater.inflate(R.layout.activity_warrior_self_battle_recyclerview, container, false);
    recyclerView = (RecyclerView) layout.findViewById(R.id.recycler_view);
    LinearLayoutManager layoutManager;


    //change to layout.findViewById():
    bStart = (Button) layout.findViewById(R.id.bOK); //modified
    nP1 = (EditText) layout.findViewById(R.id.nP1); //modified
    nP2 = (EditText) layout.findViewById(R.id.nP2); //modified
    bStart.setOnClickListener(this);

    layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false);
    recyclerView.setLayoutManager(layoutManager);
    adapter = new WarriorBattleAdapter(getActivity());
    recyclerView.setAdapter(adapter);
    return layout;
}

答案 1 :(得分:0)

是的,您对recyclerView.findViewById(R.id.bOK);的调用返回null。这是因为ViewGroup recyclerView中没有ID为'bOK'的按钮,您正在尝试使用findViewById()找到按钮。

在您的布局中,您可以立即打开和关闭RecyclerView标签:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentBottom="true">
</android.support.v7.widget.RecyclerView>

那可能只是偶然的。您应该关闭标签,直到按钮之后,如下所示 - 如果按钮应该在RecyclerView中:

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="OK"
            android:background="@drawable/button"
            android:textColor="@color/white"
            android:id="@+id/bOK"
            android:layout_marginRight="33dp"
            android:layout_marginEnd="33dp"
            android:layout_marginBottom="0dp"
            android:layout_alignParentBottom="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

</android.support.v7.widget.RecyclerView>

答案 2 :(得分:0)

您应该根据@Micha@Daniel

的答案在代码中进行修改

<强> BUT

日志描述了一个完全不同的问题 -

您已在android:screenOrientation="landscape"

中为父RelativeLayout设置了属性activity_warrior_self_battle_recyclerview.xml

那是不正确的 android:screenOrientation不是RelativeLayout的有效Android属性。