如何从数组中调用旧对象?

时间:2014-03-19 14:20:20

标签: android arrays

我将动态数据存储在作为记分板的Activity内的动态字符串数组(HoleScore)中,并且每次都可以最小化和打开。但是,当我从另一个活动回到此活动时,我无法访问之前存储的第一个对象。

e.g。

如果我来自hole_counter = 1,那么我可以看到HoleScore [1];

如果我来自hole_counter = 2,那么我看不到HoleScore [1],我只能看到HoleScore [2];

这意味着如果我来自hole_counter = 2,则第一个// Printing data of Each Hole -- !!!!!不打印任何内容。

这是我的代码:

package com.example.plusgolf;

import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;

public class ScoreBoard extends Activity 
{
    TextView hole_score, hole_score2;

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

        // Picking Data from OnCourse
        Bundle extras = getIntent().getExtras();
        // Get Stroke & Par Number from OnCourse
        int stroke = extras.getInt("stroke");
        int par_number = extras.getInt("par_number");

        // Calling Core
        final Core calling_core = (Core) getApplicationContext();
        // Get hole_counter from Core
        final int hole_counter = calling_core.getHoleCounter();
        // Get Holes from Core (Total Holes of the Game)
        final int holes = calling_core.getHoles();

        // Creating Array of String to Store Data of Each Hole
        String[] HoleScore = new String[holes];

        // Storing Hole Data in Array
        HoleScore[hole_counter] = "Hole "+ hole_counter + " = " + stroke + " / " + par_number;

        // Printing Data of each Hole -- !!!!!
        hole_score = (TextView) findViewById(R.id.hole_number1);
        hole_score.setText(HoleScore[1]);

        // Printing Data of each Hole
        hole_score2 = (TextView) findViewById(R.id.hole_number2);
        hole_score2.setText(HoleScore[2]);
    }
}

1 个答案:

答案 0 :(得分:0)

我刚刚找到了一种更好的方法来存储通过活动的这些数据:共享首选项。 每次打开第二个活动时都比发送Bundles好多了。

所以我建议使用共享偏好来传递您将使用超过1次活动的传递数据。

FirstActivity:

// Starting Shared Preferences
public static String filename = "MySharedData";
SharedPreferences mySharedData = getSharedPreferences(filename, 0);
// Editor
SharedPreferences.Editor editor = mySharedData.edit();
// Values to Send
editor.putInt("hole_" + hole_counter + "_stroke", stroke_counter);
editor.putInt("hole_"  + hole_counter + "_par" , par_number);
// Done Signal
editor.commit();

第二项活动:

// Starting Shared Preferences
public static String filename = "MySharedData";
SharedPreferences mySharedData = getSharedPreferences(filename, 0);

// Getting All Data Stored from First Activity
for (int i = 0; i <= length.that.you.need; i++)
{
    strokeArray[i] = mySharedData.getInt("hole_" + i + "_stroke", 0);
    parArray[i] = mySharedData.getInt("hole_" + i + "_par", 0);
}

PS:变量hole_counter的值是第二个Activity中的“i”之类的整数,我用它来识别每个具有 stroke par 的项目数据