问题
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().
Any thoughts?
Code:
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>
New Activity Code:
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);
}
}
Error:
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)
回答1:
Move
Bundle extras = getIntent().getExtras();
ArrayList<Integer> players = extras.getIntegerArrayList("players");
int currentPlayer = extras.getInt("newPlayerNum");
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");
}
回答2:
Wait until onCreate
to get the intent. Your trying to getIntent()
when the class is instantiated instead of when the Activity is active.
Then just assign the values found to a field and other methods inside that class can access the field.
来源:https://stackoverflow.com/questions/33192284/getextras-on-a-null-object-reference