【发布时间】:2018-07-01 15:18:16
【问题描述】:
我正在 android studio 中创建一个项目。我的目标是:当我点击“加载”按钮时,我希望 edittextName + edittextPhone 字符串中的数据调用之前保存的数据,并在应用程序关闭并重新打开后将其显示出来
当我尝试运行我的项目时,我收到错误消息“array found, string required”
我相信我需要做的就是将[] 更改为get() 命令,但不知道要使用的正确语法。
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_favourite);
editTextName = (EditText) findViewById(R.id.nameText);
editTextPhone = (EditText) findViewById(R.id.phoneText);
file = new File(this.getFilesDir(), FILE_NAME);
}
public void save(View v) {
String data = editTextName.getText().toString() + "|" + editTextPhone.getText().toString();
try {
outputStream = new FileOutputStream(file);
outputStream.write(data.getBytes());
outputStream.close();
Toast.makeText(this, "Your Barcrawl has been saved!", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void load(View v) {
int length = (int) file.length();
byte[] bytes = new byte[length];
try {
inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
String data = new String(bytes);
editTextName.setText(data.split("\\|"[0])); // << problem
editTextPhone.setText(data.split("\\|"[1])); // << problem
Toast.makeText(getBaseContext(), "data loaded", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
我是android studio的新手,已经卡了一段时间了,请帮忙。
【问题讨论】:
-
您是否打算这样做:
editTextName.setText(data.split("\\|")[0])?String#split返回一个字符串数组。然后,您可以访问该数组中的元素。
标签: java android arrays string