繁体   English   中英

返回额外的 onActivityResult 总是 null

[英]Return extras onActivityResult always 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);
}}

活动开始ToWiez.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,android.R.layout.simple_list_item_1, 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,android.R.layout.simple_list_item_1, 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你得到它作为一个字符串类型。 像这个data.getStringExtra("Player1Score") 这导致了一个问题。

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

我想我现在已经弄清楚了。 我正在尝试在单元化的 integer 上使用 =+。 所以最重要的是,当我定义我的 integer 时,它没有设置为 0。这是游戏的起点。 所有玩家的得分都应该是 0。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM