Android 我如何理解共享首选项文件是否存在
我编写了以下代码。但是当我按下按钮并重新启动程序时,我再次看到Android 我如何理解共享首选项文件是否存在,android,Android,我编写了以下代码。但是当我按下按钮并重新启动程序时,我再次看到没有file.xml文件的消息 File file = new File("/data/data/" + getPackageName() + "/shared_prefs/" + getPackageName()+ "file.xml"); if (file.exists()) Toast.makeText(getApplicationContext(), "There is the fil
没有file.xml文件的消息
File file = new File("/data/data/" + getPackageName() + "/shared_prefs/" + getPackageName()+ "file.xml");
if (file.exists())
Toast.makeText(getApplicationContext(), "There is the file.xml file", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(),"There is no the file.xml file",Toast.LENGTH_SHORT).show();
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedpreferences;
sharedpreferences = getApplicationContext().getSharedPreferences("file", MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("file","I am a file");
editor.commit();
}
});
当您存储首选项时,SharedReferences文件将自动创建,您直接访问它有什么原因吗?谢谢。上面代码的目的是,当我没有file.xml
时,我看到没有file.xml文件
消息,当我按下按钮时,我可以创建file.xml
,当我启动代码时,我看到有file.xml文件
消息。
if (file.exists())
Toast.makeText(getApplicationContext(), "There is the file.xml file", Toast.LENGTH_SHORT).show();
else
Toast.makeText(getApplicationContext(),"There is no the file.xml file",Toast.LENGTH_SHORT).show();
you can test the code in you project.
that "There is no the file.xml file" is a message. you can change it.
if(file.exists()){
Toast.makeText(getApplicationContext(), "There is not the file.xml file", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "There is the file.xml file", Toast.LENGTH_SHORT).show();
}