大家好。这是我的项目。由于我是Java编程的初学者,我尝试使用不同类型的存储,现在是内部存储。我有一个接受用户名和密码的屏幕,保存时会保存一个文本文件david.txt。我进入第二个屏幕推送负载,信息从文本文件中提取并填充用户名和密码。内部存储项目
这是主要活动
public static final String TAG = "MainActivity";
EditText userName, password;
//... standard stuff
userName = (EditText) findViewById(R.id.userName);
password = (EditText) findViewById(R.id.password);
}
public void save (View view)
{
String text1 = userName.getText().toString(); // example: David
String text2 = password.getText().toString(); // Example: Vilma123
File file=null;
text1=text1+" "; // Adds space between username and password
FileOutputStream fileOutputStream=null;
try {
file=getFilesDir(); //Gets directory of stored file
fileOutputStream = openFileOutput("david", Context.MODE_PRIVATE);
fileOutputStream.write(text1.getBytes());
fileOutputStream.write(text2.getBytes());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
Log.d(TAG, e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, e.toString());
}
finally{
try {
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
Log.d(TAG, e.toString());
}
}
Toast.makeText(this, "Saved successfully"+file+" /david.txt", Toast.LENGTH_LONG).show();
}
代码这个伟大工程,是我推“转到B”按钮,激活了SecondActivity页面中的“负荷”的方法在屏幕上:见下文
EditText userName, password;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
userName = (EditText) findViewById(R.id.editText2);
password = (EditText) findViewById(R.id.editText4);
}
public void load (View view)
{
Log.d("david", "starting fileInputStream");
try {
FileInputStream fileInputStream = openFileInput("david.txt");
int read = -1; //-1 indicates file is empty
StringBuffer buffer = new StringBuffer();
while ((read = fileInputStream.read())!=-1);
{
buffer.append((char)read);
}
Log.d("david", buffer.toString());
String user = buffer.substring(0, buffer.indexOf(""));
String pass = buffer.substring(buffer.indexOf("")+1);
userName.setText(user);
password.setText(pass);
fileInputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(this, "Load successful", Toast.LENGTH_SHORT).show();
}
好的,这是它开心的地方。当我按下Load按钮时,它应该加载我在最后一个屏幕中输入的用户名和密码,但它没有加载。 此日志文件有一个0值
Log.d("david", buffer.toString());
而其.txt文件中有我放在信息。有人能帮我解决这个问题吗?我没有显示任何错误,所有Toasts都应该显示。
文件是昂贵的过程,使用偏好android有一种叫做偏好小机制数据存储的机制 – Sush
你可以以加密形式存储共享偏好的用户名和密码,这样任何人都无法读取它。 –
@sush请解释你的想法,我了解什么状态存储在共享首选项状态,然后回顾。所以最后有代码保存数据到一个确定的地方,并访问数据使用共享首选项 – user3324600