我是Android开发的新手。我想将用户输入作为double值,然后将其传递给下一个活动,然后将其与另一个值相加,但我无法传递它。 当将这个名为wins的双数组传递给活动2时,我收到一个错误。错误是:不兼容的类型。 必需:找到java.util.ArrayList:double []
Activity 1
public void btnAdd_OnClick(View v)
{
{
if (txtWinnings.getText().toString().isEmpty()) {
displayToast("Please enter an amount");
}else{
double winning =
Double.parseDouble(txtWinnings.getText().toString());
if(winning > 0) {
winnings.add(winning);
txtWinnings.setText("");
txtWinnings.setHint("You have added " + (winnings.size()) +
" tournament winnings");
} else {
displayToast("You must enter an amount more than 0");
}
}
}
}
public void btnClear_OnClick(View v)
{
if(winnings.size() < 0)
{
displayToast("You have no winnings to clear");
}else {
winnings.clear();
displayToast("Cleared");
}
}
public void btnSummary_OnClick(View v)
{
{
if(winnings.size() > 0)
{
Intent i = new Intent(this, SummaryActivity.class);
i.putExtra("winnings", winnings);
startActivity(i);
}else{
displayToast("You must enter at least one amount of winnings");
}
}
}
public void displayToast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
Activity 2
public class SummaryActivity extends AppCompatActivity {
ArrayList<Double> winnings = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_summary);
setTitle("Summary");
TextView lblTournaments = (TextView) findViewById(R.id.txtAverage);
TextView lblTotal = (TextView) findViewById(R.id.txtTotal);
TextView lblMax = (TextView) findViewById(R.id.txtMax);
TextView lblMin = (TextView) findViewById(R.id.txtMin);
TextView lblAverage = (TextView) findViewById(R.id.txtAverage);
Intent i = getIntent();
winnings = i.getDoubleArrayExtra("winnings");
}
}
答案 0 :(得分:0)
winnings
是ArrayList<Double>
。您不能像在此行那样为double[]
指定它:
winnings = i.getDoubleArrayExtra("winnings");
您可以将double[]
转换为List<Double>
,如下所示:
List<Double> winnings = Arrays.stream(i.getDoubleArrayExtra("winnings"))
.mapToObj(d-> d)
.collect(Collectors.toList());
使用流有点矫枉过正,但学习流程是值得的。
编辑:
Stream
可能无法使用(请参阅评论)。如果没有Stream
,您可以手动清空winnings
集合,然后迭代数组以再次填充它:
double[] array = i.getDoubleArrayExtra("winnings");
winnings.clear();
for(double winning : array) {
winnings.add(winning);
}