gpt4 book ai didi

java - 从内部存储器读取数据

转载 作者:行者123 更新时间:2023-12-02 02:34:47 25 4
gpt4 key购买 nike

我正在 Android Studio 中使用 Java 为我正在从事展示位置的业务创建移动应用程序。我在尝试使用内部存储器存储数据时遇到了问题。

基本上,一旦用户单击“开始按钮”,我希望将用户在幕后的选择保存到文件中,然后在下一个屏幕上检索存储的选择。

这是我将数据写入文件的代码(似乎有效):

            int spinnerSelection = myspinner.getSelectedItemPosition();
int spinnerSelection2 = myspinner2.getSelectedItemPosition();
String q = quantity.getText().toString();
String d = duration.getText().toString();
String formattedtime = fmt.print(dateTime);
TextView endtime = findViewById(endtimetextView);


String file_name = "Records.txt";
File file = null;
FileOutputStream fileOutputStream = null;
try {
file = getFilesDir();
fileOutputStream = openFileOutput(file_name, MODE_PRIVATE);

fileOutputStream.write(spinnerSelection);
fileOutputStream.write(spinnerSelection2);
fileOutputStream.write(q.getBytes());
fileOutputStream.write(d.getBytes());
fileOutputStream.write(endtimecalc.getBytes());
fileOutputStream.write(formattedtime.getBytes());

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Toast.makeText(screen2.this, "SUCESSFULLY SAVED TO " + file, Toast.LENGTH_SHORT).show();

}
});

如果我需要更改任何代码(特别是我不确定这是否是保存已选择的微调器值的正确方法),请告诉我。

现在,为了将数据读入下一个屏幕,我刚刚遵循了一些不同的 YouTube 教程,但没有一个成功。

这是我尝试过的一些代码:

TextView DisplaySaved;

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

DisplaySaved = (TextView) findViewById(R.id.textView2);
}


public void read (View view) {

try {
FileInputStream fileInputStream = openFileInput("Record.txt");
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
StringBuffer buffer = new StringBuffer();
String lines;

while ((lines = bufferedReader.readLine()) !=null) {
buffer.append(lines+"\n");
}

DisplaySaved.setText(buffer.toString());

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

此外,有人知道如何每次创建一个新记录,而不是每次都实际覆盖同一个文件吗?只是我需要在每次创建记录时存储

如果有人能帮我纠正这个问题,那就太好了。

谢谢!

最佳答案

我不知道您是否绝对需要使用文件来存储这些信息,但是还有许多其他方法可以使用 Android Studio 将信息传递给新的 Activity。

你应该检查Intent类,你可以发送一个包含你的数据的Bundle!

关于java - 从内部存储器读取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46545196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com