【问题标题】:android storing values in array or list without overwriteandroid将值存储在数组或列表中而不覆盖
【发布时间】:2015-02-04 19:11:12
【问题描述】:

我只是想知道是否有一种方法可以将数据保存到文本文件中而不会被覆盖。

目前我正在使用 sharedpreferences,它会覆盖数据,这没关系,但与此一致,我想要在某个地方记录值,然后再以列表或列的形式覆盖。

所以它是这样的: 60、65、70..等 这些值一个接一个地存储而不会被覆盖。我正在考虑在一个可以读取的文本文件中本地执行此操作。

我这样做是为了创建一个统计页面或类似的东西。

希望有人能帮我找到解决办法。

我的代码:

public class workout extends Activity {

    TextView weightresultText, newweightresultText, difficultyrating;
    Boolean male, strength;
    double newweight, newweight1;
    int weight, age;
    Button button, button4;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.workout);
        button = (Button) findViewById(R.id.button);
        button4 = (Button) findViewById(R.id.button4);

        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        weight = Integer.parseInt(sharedPreferences.getString("storedweight", "Your Weight"));
        age = Integer.parseInt(sharedPreferences.getString("storedage", "Your Age"));
        male = sharedPreferences.getBoolean("is_male", false);
        strength = sharedPreferences.getBoolean("is_strength", false);

        weightresultText = (TextView) findViewById(R.id.weightresultLabel);
        newweightresultText = (TextView) findViewById(R.id.newweightresultLabel);
        difficultyrating = (TextView) findViewById(R.id.difficultylevel);

         if (sharedPreferences.getBoolean("firstrun", true)) {AgeCalculation();

             sharedPreferences.edit().putBoolean("firstrun", false).commit();}


        AfterFirstLaunch();
    }

    public void SaveWeight(){
        savePreferences("storednewweight", (Double.toString(newweight)));
    }

//Should only happen on first launch.
    public void AgeCalculation() {
        if (strength == true){
        if (male == true && age >= 18) {
            newweight = (weight * 0.8);
            }
        if (male == true && age >= 30) {
            newweight = (weight * 0.6);
        }
        if (male == true && age >= 50) {
            newweight = (weight * 0.4);
        }
        if (male == true && age >= 70) {
            newweight = (weight * 0.2);
        }
        if (male == true && age > 80) {
            newweight = (weight * 0.1);
        }
        if (male == false && age >= 20 ){
            newweight = (weight * 0.3 );
                    }
        weightresultText.setText(Double.toString(newweight));
        SaveWeight();
            }}

    private void savePreferences(String key, String value) {
        SharedPreferences sharedPreferences = PreferenceManager
                .getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

// On every other launch, it is based on button, the newweight is saved and loaded each time.
    public void buttonClick1(){
    button.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            //this gets the current weight based on first time launch.
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            String newweight =  sharedPreferences.getString("storednewweight", "");

           newweight1 = Double.parseDouble(newweight);

            newweight1 = newweight1 + 5;
            //saves value into sharedpreference
            savePreferences("storednewweight", (Double.toString(newweight1)));
            //save to shared preference, and load value on new launch?
            //also store into local database for review later.
            difficultyrating.setText("1");
            button.setEnabled(false);
            button4.setEnabled(false);

           //save this data then on new launch it uses this figure.
            // so first time it creates then uses this figure for future.
        }

    });}

    public void buttonClick4(){
        button4.setOnClickListener(new View.OnClickListener() {
            public void onClick(View arg0) {

                //this gets the current weight based on first time launch.
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                String newweight =  sharedPreferences.getString("storednewweight", "");

                newweight1 = Double.parseDouble(newweight);

                newweight1 = newweight1 + 10;
                //saves value into sharedpreference
                //save to text file in array
                savePreferences("storednewweight", (Double.toString(newweight1)));

                difficultyrating.setText("2");
                button.setEnabled(false);
                button4.setEnabled(false);

                //save this data then on new launch it uses this figure.
                // so first time it creates then uses this figure for future.
            }

        });}

    //runs on every other launch
    public void AfterFirstLaunch(){

        buttonClick1();
        buttonClick4();
        //receive value on other launches and show on field.
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
        String newweight =  sharedPreferences.getString("storednewweight", "");
        weightresultText.setText(newweight);

    }



        }

【问题讨论】:

    标签: android arrays database list sharedpreferences


    【解决方案1】:

    对于这样的事情,您要存储多个类似数据的条目,您确实希望将 SQL 数据库与内容提供程序一起使用。您只需为每个条目创建新行。

    【讨论】:

    • 是的,我当时在想,但找不到任何好的教程来展示它,所以我正在考虑替代文本文件。数据库会更好,但不知道如何在我的代码中实现它。
    • @Bimal 你喜欢我分享一些关于 SQLite 的好教程
    • 是的,请先尝试文本文件方式,然后再尝试 sql 方式,这样我对两者都有很好的了解。
    【解决方案2】:

    要写入一个被覆盖的文本文件,请使用以下代码

    File sdCard = Environment.getExternalStorageDirectory();
    String path = sdCard.getAbsolutePath() + "/SO/";
    
    File dir = new File(path);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
    
        }
    }
    
    File logFile = new File(path + "filename.txt");
            if (!logFile.exists()) {
                logFile.createNewFile();
            }
    
            // BufferedWriter for performance, true to set append to file
    
            FileWriter fw = new FileWriter(logFile, true);
            BufferedWriter buf = new BufferedWriter(fw);
    
    
            buf.append("Message");
            buf.newLine();
            buf.flush();
    
    
            buf.close();
    

    确保您在AndroidManifest.xml 中定义了权限

    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    

    【讨论】:

    • 所以说,如果在我的代码中,按下按钮单击 1 并将值更改为 50,并且下一次按下按钮单击 4 并将值更改为 60,它会显示为 50、60 in文本文件?我是否也应该将您提供的代码放入其自己的类中并在共享首选项覆盖之前在每个按钮中调用它?很抱歉问了这么多时间,不想弄错。
    • 你会得到 50 和 60
    • 好的,我试试看是不是我想要的
    • 因此,使用您的代码,我到处都遇到错误,不知道为什么。未处理的异常:java.io.IOException
    • 您是否提供了path您的文件夹路径??
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-08
    • 1970-01-01
    • 2021-01-12
    • 2017-06-14
    • 1970-01-01
    • 2023-03-16
    • 2018-12-08
    相关资源
    最近更新 更多