gpt4 book ai didi

java - 如何将数组从 java android Activity 类传递到普通 java 类?

转载 作者:行者123 更新时间:2023-12-02 05:59:30 25 4
gpt4 key购买 nike

我是 java 新手,在类之间传递数组时遇到问题。我想将从主要 Activity 收集的数据传递给正在进行计算的另一个类。当我尝试将数组值打印到计算类中的调试日志时,出现错误“java.lang.NullPointerException:尝试从空数组中读取”

这是我的计算类:

package com.example.pokerholdemcalculator;

import android.util.Log;

public class CardHandling {
private int[] usedCards;
private MainActivity ma;

CardHandling() {
usedCards = new int[13];
ma = new MainActivity();
usedCards = ma.getPlayerCardContents();
}

public void printC () {
for (int i = 0; i < 13; i++) {
String card = Integer.toString(usedCards[i]);
Log.d("CARDS", card);
}
}
}

还有我的 MainActivity 类:

package com.example.pokerholdemcalculator;

import android.graphics.PorterDuff;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ViewFlipper;

public class MainActivity extends AppCompatActivity {
private ViewFlipper viewFlipper;
private boolean[] playerCardFlag;
private ImageButton[] playerCard;
private int[] playerCardContents;

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

playerCard = new ImageButton[13];
playerCardFlag = new boolean[13];
playerCardContents = new int[13];
}

public void testing (View v) {
printArr();
}

public void printArr() {
CardHandling ch = new CardHandling();
ch.printC();
}

public int[] getPlayerCardContents() {
return playerCardContents;
}

这是来自控制台的错误消息:

Caused by: java.lang.NullPointerException: Attempt to read from null array
at com.example.pokerholdemcalculator.MainActivity.getPlayerCardContents(MainActivity.java:70)
at com.example.pokerholdemcalculator.CardHandling.<init>(CardHandling.java:12)
at com.example.pokerholdemcalculator.MainActivity.printArr(MainActivity.java:64)
at com.example.pokerholdemcalculator.MainActivity.testing(MainActivity.java:60)

我尝试过以不同的方式初始化,但无法解决该错误。

最佳答案

这里的主要问题是您的 Activity 不能像这样引用:

ma = new MainActivity();
usedCards = ma.getPlayerCardContents();

你能做的就是在主 Activity 上启动类(class)

CardHandling ch = new CardHandling();
ch.usedCard = getPlayerCardContents();

MainActivity 扩展了 AppCompatActivity,这意味着您的 Activity 不是普通对象

关于java - 如何将数组从 java android Activity 类传递到普通 java 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55987172/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com