【问题标题】:save calculator result and show them as a list using SharedPreferences保存计算器结果并使用 SharedPreferences 将它们显示为列表
【发布时间】:2023-03-21 16:33:02
【问题描述】:

我已经成功实现了一个带有历史活动的计算器,它将在列表视图中显示旧结果 但我面临的问题是第一行始终为空

https://imgur.com/a/jvXms

我尝试将默认字符串设为“旧计算”

>    String w = "Old Calculation";

但这没有用, 我的应用程序将结果保存在 SharedPreferences 中的多行字符串中,并通过意图将其传递给另一个活动

>SharedPreferences.Editor editor ; // saving shared preferences editor as MainAcitivty class attribute

在 onCreate 下,我将 String 值设置为 sharedpref

> SharedPreferences prefs = getPreferences(MODE_PRIVATE);
        w = prefs.getString("saved", null);

更新方法,其中我用字符串 s 更新结果字符串值(字符串 s 是计算结果)

>     public void update(String s){
        editor= getPreferences(MODE_PRIVATE).edit();
        w =     w
                + System.getProperty ("line.separator")
                + s
                + System.getProperty ("line.separator");
        editor.putString("saved", w);
        editor.apply();
    }

将 W 值传递给我将在 TextView 列表中显示结果的活动

>    public void History(View v){
        Intent myIntent = new Intent(MainActivity.this, History.class);
        myIntent.putExtra("message", w);
        startActivity(myIntent);
        overridePendingTransition(R.anim.anim_slide_in_left, 
        R.anim.anim_slide_out_left);
    }

历史活动

    public class History extends AppCompatActivity {
    TextView tv1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_history);
        String w ="Old calculation is showed here";
        tv1 = (TextView) findViewById(R.id.tv1);
        print(w);
    }

    public void print(String w) {
            Bundle bundle = getIntent().getExtras();
            w = bundle.getString("message");

            tv1.setMovementMethod(new ScrollingMovementMethod());

            tv1.setText(w);

    }
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        overridePendingTransition(R.anim.anim_slide_in_right, R.anim.anim_slide_out_right);
    }
    public void deleteAppData(View v) {
        try {
            // clearing app data
            String packageName = getApplicationContext().getPackageName();
            Runtime runtime = Runtime.getRuntime();
            runtime.exec("pm clear "+packageName);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【问题讨论】:

    标签: java android sharedpreferences calculator history


    【解决方案1】:

    当您从活动 A 存储数据并想从另一个活动中检索数据时,您必须使用SharedPreferences,如下所示:

    SharedPreferences prefs = getSharedPreferences(String, int);

    String 是 FileName,如 "result"
    int 是 Mode,如 MODE_PRIVATE
    例如见this link

    另外我wrote a simple code来帮你

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-02
      • 2014-06-17
      • 2018-07-24
      • 2013-12-18
      • 1970-01-01
      • 1970-01-01
      • 2022-07-04
      • 1970-01-01
      相关资源
      最近更新 更多