有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java意图传递数据未成功

我正在制作一个游戏的得分列表,我使用了下面的代码将scoretime传递给ScoreActivity,但我不知道为什么它只显示默认的数字“1”

long timeSpent = System.currentTimeMillis() - initialTime;
timeSpent = (long) (timeSpent / 1000.0);
int apple = (int)timeSpent;
Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
scoreIntent.putExtra("score",apple);

AlertDialog alertDialog = new AlertDialog.Builder(GameActivity.this).create();
alertDialog.setTitle("Game Over!");
alertDialog.setMessage(" Total time " + String.valueOf(timeSpent));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE,"Exit", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        Intent i =new Intent(getContext(), ScoreActivity.class);
        getContext().startActivity(i);
    }

在计分活动中

TextView myText;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_score);
    myText = (TextView)findViewById(R.id.text444);
    Intent scoreIntent = getIntent();
    int rating = scoreIntent.getIntExtra("score", 1);
    String str = Integer.toString(rating);
    myText.setText(rating);
}

共 (2) 个答案

  1. # 1 楼答案

    你需要在这里传递你的价值

    Intent i =new Intent(getContext(),   ScoreActivity.class);
     i.putExtra("score",Apple);
    getContext().startActivity(i); 
    
  2. # 2 楼答案

    它显示默认值,因为您创建了一个意图并在其中添加了额外内容

    Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
    scoreIntent.putExtra("score",apple);
    

    没错,但当你开始活动时,你使用了另一个意图

    Intent i =new Intent(getContext(), ScoreActivity.class);
    getContext().startActivity(i);
    

    而且apple的值不在新的intent i中,因此解决方案是将您的intent scoreIntent设置为final,您可以通过onClick()方法访问它,如:

    final Intent scoreIntent = new Intent(GameActivity.this,ScoreActivity.class);
    scoreIntent.putExtra("score",apple);
    

    onClick()开始,你这样做

    getContext().startActivity(scoreIntent );