本文介绍了.getExtras()'对空对象的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在我的活动之间传递一些价值,以使游戏发挥作用。但是,当我尝试使用.getExtras()时,传递信息后的新活动始终返回null。

I am trying to pass a few values between my activities to make a game work. However, the new activity after passing the information always returns null when I try to .getExtras().

有什么想法吗?

代码:

package name.zerosum;

import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Spinner;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;

import java.util.ArrayList;


public class NewGameActivity extends AppCompatActivity {

    public Spinner players, bestOf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_game);

        players = (Spinner) findViewById(R.id.players);
        Integer[] items1 = new Integer[]{2, 3, 4, 5, 6, 7, 8, 9, 10};
        ArrayAdapter<Integer> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items1);
        players.setAdapter(adapter1);

        bestOf = (Spinner) findViewById(R.id.bestOf);
        Integer[] items2 = new Integer[]{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25};
        ArrayAdapter<Integer> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, items2);
        bestOf.setAdapter(adapter2);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_new_game, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    public void sendMessageStart(View view) {


        final RadioButton sign3 = (RadioButton) findViewById(R.id.radio3);
        final RadioButton sign5 = (RadioButton) findViewById(R.id.radio5);

        Button start = (Button) findViewById(R.id.startButton);

        start.setOnClickListener(new View.OnClickListener() {

            //int playerNum = Integer.valueOf(players.getSelectedItem().toString());
            //int games = Integer.valueOf(bestOf.getSelectedItem().toString());
            @Override
            public void onClick(View v) {

                ArrayList<Integer> players = new ArrayList<>();
                Bundle bundle = new Bundle();
                bundle.putInt("newPlayerNum", 1);
                bundle.putInt("numOfPlayers", 2);
                bundle.putInt("games", 1);
                bundle.putIntegerArrayList("players", players);

                if (sign3.isChecked()) {
                    Intent intentBundle = new Intent(NewGameActivity.this, ThreeSignGameActivity.class);
                    intentBundle.putExtras(bundle);
                    startActivity(intentBundle);
                }
                else if (sign5.isChecked()) {
                    Intent intentBundle = new Intent(NewGameActivity.this, FiveSignGameActivity.class);
                    intentBundle.putExtras(bundle);
                    startActivity(intentBundle);
                }
            }
        });
    }
}

XML:

<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:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="name.zerosum.NewGameActivity"
    android:background="#0169B2">

    <TextView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/newGamePlayers"
        android:id="@+id/textView4"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="20dp"
        android:layout_marginStart="20dp"
        android:layout_marginTop="30dp"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"
        android:textSize="40sp"
        />

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/players"
        android:layout_alignTop="@+id/textView4"
        android:layout_toRightOf="@+id/textView4"
        android:layout_toEndOf="@+id/textView4"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/newGameStyle"
        android:id="@+id/textView6"
        android:layout_marginTop="60dp"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"
        android:textSize="40sp"
        android:layout_below="@+id/textView4"
        android:layout_alignLeft="@+id/textView4"
        android:layout_alignStart="@+id/textView4" />

    <RadioGroup xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_below="@+id/textView6"
        android:layout_centerHorizontal="true"
        android:checkedButton="@+id/radio3"
        android:id="@+id/group">
        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio3"
            android:id="@+id/radio3"
            android:textColor="#ffffff"
            android:textStyle="bold"
            android:typeface="sans"
            android:textSize="20sp"/>

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio5"
            android:id="@+id/radio5"
            android:textColor="#ffffff"
            android:textStyle="bold"
            android:typeface="sans"
            android:textSize="20sp" />
    </RadioGroup>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/newGameBestOf"
        android:id="@+id/textView7"
        android:layout_below="@+id/textView6"
        android:layout_alignLeft="@+id/textView6"
        android:layout_alignStart="@+id/textView6"
        android:layout_marginTop="80dp"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"
        android:textSize="40sp"/>

    <Spinner
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bestOf"
        android:layout_alignTop="@+id/textView7"
        android:layout_toRightOf="@+id/textView7"
        android:layout_toEndOf="@+id/textView7"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"
        />

    <Button
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="@string/newGameButtonText"
        android:id="@+id/startButton"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:typeface="sans"
        android:textSize="30sp"
        android:onClick="sendMessageStart"/>
</RelativeLayout>

新活动代码:

package name.zerosum;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;

import java.util.ArrayList;
import java.util.List;

public class ThreeSignGameActivity extends AppCompatActivity {

    Bundle extras = getIntent().getExtras();

    ArrayList<Integer> players = extras.getIntegerArrayList("players");
    int currentPlayer = extras.getInt("newPlayerNum");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_three_sign_game);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_three_sign_game, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    //rock = 1
    //paper = 2
    //scissors = 3

    public void storeRock(View view) {
        players.add(1);
        if(currentPlayer == 1) {
            playNextGame();
        }
        else {
            winner(players);
        }
    }

    public void storePaper(View view) {
        players.add(2);
        if(currentPlayer == 1) {
            playNextGame();
        }
        else {
            winner(players);
        }
    }

    public void storeScissors(View view) {
        players.add(3);
        if(currentPlayer == 1) {
            playNextGame();
        }
        else {
            winner(players);
        }
    }

    public void playNextGame() {
        Bundle bundle = new Bundle();
        bundle.putInt("newPlayerNum", currentPlayer + 1);
        bundle.putIntegerArrayList("players", players);

        Intent intent = new Intent(this, ThreeSignGameActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void winner(List<Integer> players) {
        int player1 = players.get(0);
        int player2 = players.get(1);
        //rock = 1
        //paper = 2
        //scissors = 3
        if (player1 == 1){
            if(player2 == 1){tie();}
            else if (player2 == 2) {results(2);}
            else if (player2 == 3) {results(1);}
        }
        else if (player1 == 2){
            if(player2 == 1) {results(1);}
            else if (player2 == 2) {tie();}
            else if (player2 == 3) {results(2);}
        }
        else if (player1 == 3){
            if(player2 == 1) {results(2);}
            else if (player2 == 2) {results(1);}
            else if (player2 == 3){tie();}
        }
    }

    public void results (int winner) {
        Bundle bundle = new Bundle();
        bundle.putInt("winner", winner);

        Intent intent = new Intent(this, ResultsScreenActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void tie () {
        Bundle bundle = new Bundle();
        bundle.putInt("newPlayerNum",1);

        Intent intent = new Intent(this, Tie3Activity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }
}

错误:

10-17 18:29:57.706    8417-8417/name.zerosum E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: name.zerosum, PID: 8417
    java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{name.zerosum/name.zerosum.ThreeSignGameActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2322)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5696)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
            at name.zerosum.ThreeSignGameActivity.<init>(ThreeSignGameActivity.java:17)
            at java.lang.reflect.Constructor.newInstance(Native Method)
            at java.lang.Class.newInstance(Class.java:1572)
            at android.app.Instrumentation.newActivity(Instrumentation.java:1083)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2312)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2474)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1359)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:155)
            at android.app.ActivityThread.main(ActivityThread.java:5696)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1028)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:823)


推荐答案

移动

Bundle extras = getIntent().getExtras();

ArrayList<Integer> players = extras.getIntegerArrayList("players");
int currentPlayer = extras.getInt("newPlayerNum");

转换为 onCreate() getIntent()需要一个 Context ,该上下文在 onCreate()

into onCreate(). getIntent() needs a Context which isn't available before onCreate()

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_three_sign_game);

    // here
     Bundle extras = getIntent().getExtras();

     ArrayList<Integer> players = extras.getIntegerArrayList("players");
     int currentPlayer = extras.getInt("newPlayerNum");
}

这篇关于.getExtras()'对空对象的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:54