返回额外的 onActivityResult 总是 null

问题描述

我正在构建我的第一个应用程序,但我遇到了在 onActivityResult 的意图中传递额外内容的问题。我试图寻找答案,但找不到合适的答案。据我所知,我遵循使用意图传递数据的“正常”结构,确保使用 setResult() 传递的意图而不是活动的意图。但我的知识非常有限,所以可能我只是忽略了一些明显的东西。

这款应用的理念是在纸牌游戏中跟踪分数。

我的应用目前包含 3 个活动。

  1. MainActivity 是用于填写玩家名称的主屏幕。
  2. StartToWiez 使用这些名称并创建一个记录分数的表格。
  3. 从此页面开始一个新活动 (StartRound),以根据用户的输入计算分数。
  4. 然后应将此分数传递回 StartToWiez 活动,并且 StartToWiez 活动应使用分数填充表格。

我尝试在 setResult() 中传递的意图的附加内容中传递一个包。我试着把分数作为意图的直接附加。两种方式我都会得到同样的错误。因此,返回的意图中似乎不存在返回的额外内容。但我不明白为什么不像 setResult() 意图有额外的东西。

错误:

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wiezen,PID: 7924
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null,request=1,result=-1,data=Intent { (has extras) }} to activity {com.example.wiezen/com.example.wiezen.StartToWiez}: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4976)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017)
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51)
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123)
    at android.os.Handler.dispatchMessage(Handler.java:107)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7710)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)
 Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
    at com.example.wiezen.StartToWiez.onActivityResult(StartToWiez.java:65)
    at android.app.Activity.dispatchActivityResult(Activity.java:8140)
    at android.app.ActivityThread.deliverResults(ActivityThread.java:4969)
    at android.app.ActivityThread.handleSendResult(ActivityThread.java:5017) 
    at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:51) 
    at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
    at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2123) 
    at android.os.Handler.dispatchMessage(Handler.java:107) 
    at android.os.Looper.loop(Looper.java:214) 
    at android.app.ActivityThread.main(ActivityThread.java:7710) 
    at java.lang.reflect.Method.invoke(Native Method) 
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950) 

活动:MainActivity.java

package com.example.wiezen;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {

//create a Bundle object
Bundle extras = new Bundle();
SharedPreferences sharedpreferences;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    sharedpreferences = getSharedPreferences("Settings",Context.MODE_PRIVATE);
}
/** Called when the user taps the Send button */
public void startToWiez(View view) {
    Intent intent = new Intent(this,StartToWiez.class);
    EditText player1Name = (EditText) findViewById(R.id.Player1Name);
    String player1NameText = player1Name.getText().toString();

    EditText player2Name = (EditText) findViewById(R.id.Player2Name);
    String player2NameText = player2Name.getText().toString();

    EditText player3Name = (EditText) findViewById(R.id.Player3Name);
    String player3NameText = player3Name.getText().toString();

    EditText player4Name = (EditText) findViewById(R.id.Player4Name);
    String player4NameText = player4Name.getText().toString();

    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString("PLAYER1_NAME",player1NameText);
    editor.putString("PLAYER2_NAME",player2NameText);
    editor.putString("PLAYER3_NAME",player3NameText);
    editor.putString("PLAYER4_NAME",player4NameText);
    editor.apply();

    startActivity(intent);
}}

Activity StartToWiez.java

package com.example.wiezen;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class StartToWiez extends AppCompatActivity {

Bundle extras;
SharedPreferences sharedpreferences;
Integer player1Score;
Integer player2Score;
Integer player3Score;
Integer player4Score;
Integer aantalRondes = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_to_wiez);
    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();
    sharedpreferences = getSharedPreferences("Settings",Context.MODE_PRIVATE);
    extras = intent.getExtras();
    // Capture the layout's TextView and set the string as its text
    TextView header1 = findViewById(R.id.Player1Header);
    TextView header2 = findViewById(R.id.Player2Header);
    TextView header3 = findViewById(R.id.Player3Header);
    TextView header4 = findViewById(R.id.Player4Header);
    header1.setText(sharedpreferences.getString("PLAYER1_NAME","Player 1"));
    header2.setText(sharedpreferences.getString("PLAYER2_NAME","Player 2"));
    header3.setText(sharedpreferences.getString("PLAYER3_NAME","Player 3"));
    header4.setText(sharedpreferences.getString("PLAYER4_NAME","Player 4"));
}

public void startRound(View view) {
    Intent intent = new Intent(this,StartRound.class);
    startActivityForResult(intent,1);


}

@Override
protected void onActivityResult(int requestCode,int resultCode,Intent data) {
    super.onActivityResult(requestCode,resultCode,data);
    if (resultCode == RESULT_OK) {
        aantalRondes++;

        TableLayout table = (TableLayout) StartToWiez.this.findViewById(R.id.tableLayout);
        // Inflate your row "template" and fill out the fields.
        TableRow row = (TableRow) LayoutInflater.from(StartToWiez.this).inflate(R.layout.tablerow,null);

        player1Score += data.getIntExtra("Player1Score",0);
        player2Score += data.getIntExtra("Player2Score",0);
        player3Score += data.getIntExtra("Player3Score",0);
        player4Score += data.getIntExtra("Player4Score",0);

        ((TextView) row.findViewById(R.id.player1Score)).setText(String.valueOf(player1Score));
        ((TextView) row.findViewById(R.id.player2Score)).setText(String.valueOf(player2Score));
        ((TextView) row.findViewById(R.id.player3Score)).setText(String.valueOf(player3Score));
        ((TextView) row.findViewById(R.id.player4Score)).setText(String.valueOf(player4Score));
        table.addView(row);

        if(aantalRondes == 4){
            TableRow row2 = (TableRow) LayoutInflater.from(StartToWiez.this).inflate(R.layout.line_after_4_rounds,null);
            table.addView(row2);
            aantalRondes = 0;
        }
    }
}

}

活动:StartRound.java

package com.example.wiezen;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.Spinner;
import android.widget.TextView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;

public class StartRound extends AppCompatActivity {


SharedPreferences sharedpreferences;
Spinner gameType;
Spinner troef;
Spinner aantalSlagen;
ArrayAdapter<String> adapter;
ArrayAdapter<String> adapterTroef;
ArrayAdapter<String> adapterAantalSlagen;
CheckBox player1;
CheckBox player2;
CheckBox player3;
CheckBox player4;
CheckBox player1Win;
CheckBox player2Win;
CheckBox player3Win;
CheckBox player4Win;
Boolean[] winners = new Boolean[4];


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_start_round);
    // Get the Intent that started this activity and extract the string
    Intent intent = getIntent();

    //get the shared prefs that store player names
    sharedpreferences = getSharedPreferences("Settings",Context.MODE_PRIVATE);

    //set player names for the checkboxes
    player1 = findViewById(R.id.player1Checkbox);
    player2 = findViewById(R.id.player2Checkbox);
    player3 = findViewById(R.id.player3Checkbox);
    player4 = findViewById(R.id.player4Checkbox);
    player1.setText(sharedpreferences.getString("PLAYER1_NAME","defaultValue"));
    player2.setText(sharedpreferences.getString("PLAYER2_NAME","defaultValue"));
    player3.setText(sharedpreferences.getString("PLAYER3_NAME","defaultValue"));
    player4.setText(sharedpreferences.getString("PLAYER4_NAME","defaultValue"));

    player1Win = findViewById(R.id.player1Win);
    player2Win = findViewById(R.id.player2Win);
    player3Win = findViewById(R.id.player3Win);
    player4Win = findViewById(R.id.player4Win);

    //set the game type dropdown values for the spinner
    gameType = (Spinner) findViewById(R.id.gameType);
    adapter = new ArrayAdapter<String>(StartRound.this,android.R.layout.simple_list_item_1,getResources().getStringArray(R.array.typeSpel));
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    gameType.setAdapter(adapter);

    //set the game type dropdown values for the spinner
    troef = (Spinner) findViewById(R.id.troef);
    adapterTroef = new ArrayAdapter<String>(StartRound.this,getResources().getStringArray(R.array.troef));
    adapterTroef.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    troef.setAdapter(adapterTroef);

    //set the game type dropdown values for the spinner
    aantalSlagen = (Spinner) findViewById(R.id.aantalSlagen);
    adapterAantalSlagen = new ArrayAdapter<String>(StartRound.this,getResources().getStringArray(R.array.aantalSlagen));
    adapterAantalSlagen.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    aantalSlagen.setAdapter(adapterAantalSlagen);

    //on change of game type spinner do something
    gameType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parentView,View selectedItemView,int position,long id) {

        }


        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

    // using finsih()
    Button closeButton = (Button) findViewById(R.id.calculateScore);
    closeButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            winners[0] = player1Win.isChecked();
            winners[1] = player2Win.isChecked();
            winners[2] = player3Win.isChecked();
            winners[3] = player4Win.isChecked();
            Boolean[] players = new Boolean[4];
            players[0] = player1.isChecked();
            players[1] = player2.isChecked();
            players[2] = player3.isChecked();
            players[3] = player4.isChecked();
            int[] score = new int[4];

            Integer behaaldAantalSlagen = (Integer) Integer.parseInt(aantalSlagen.getSelectedItem().toString());
            String gametypetest = gameType.getSelectedItem().toString();

            switch(gametypetest) {
                //algorithm to define the score based on the gametype. score is added to the array score
            }
            Intent returnIntent = getIntent();
            returnIntent.putExtra("Player1Score",score[0]);
            returnIntent.putExtra("Player2Score",score[1]);
            returnIntent.putExtra("Player3Score",score[2]);
            returnIntent.putExtra("Player4Score",score[3]);
            setResult(RESULT_OK,returnIntent);
            StartRound.this.finish();
        }
    });

}

}

解决方法

returnIntent 中,您将 Player1Score 作为 int 传递。因为 score 是一个 int 数组。

onActivityResult 中,您将其作为 String 类型获取。像这样data.getStringExtra("Player1Score")。这导致了一个问题。

您需要将其作为 int only.like data.getIntExtra("Player1Score") 获取。然后不需要解析它,因为它已经是 int

,

我想我现在已经想通了。我正在尝试在未初始化的整数上使用 =+。所以最重要的是,当我定义我的整数时,它没有设置为 0。这是游戏的起点。所有玩家的得分应为 0。

因此,当在整数上使用 += 时,它抱怨的不是意图或数据,而是您无法添加到空值整数的事实。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...