我正在编写一个关于使用文件I / O登录的非常简单的示例:
public void onClickLogin(View v) throws FileNotFoundException
{
String username = "", password = "";
TextView nomeUtenteView = (TextView)findViewById(R.id.tUserName);
username = nomeUtenteView.getText().toString();
TextView passwordView = (TextView)findViewById(R.id.tPassword);
password = passwordView.getText().toString();
if (!findUser(username, password, false))
Toast.makeText(getApplicationContext(), "Account not exists", Toast.LENGTH_SHORT).show();
else {
Intent intent = new Intent(this, HomeActivity.class);
Bundle bundle = new Bundle();
bundle.putString("user", username);
intent.putExtras(bundle);
startActivity(intent);
}
}
public void onClickRegister(View v) {
String username = "", password = "";
TextView nomeUtenteView = (TextView)findViewById(R.id.tUserName);
username = nomeUtenteView.getText().toString();
TextView passwordView = (TextView)findViewById(R.id.tPassword);
password = passwordView.getText().toString();
try {
if (findUser(nomeUtente, password, true))
Toast.makeText(getApplicationContext(), "Username (" + username + ") already in use!", Toast.LENGTH_LONG).show();
else
{
String nomeFileAccounts = getApplicationContext().getFilesDir().getPath().toString() + "/" + getString(R.string.nomeFileAccounts);
FileWriter fileScrivi = new FileWriter(nomeFileAccounts, true);
fileScrivi.append(userName+" " + password + "\n");
fileScrivi.close();
Toast.makeText(getApplicationContext(), "New account registered. Wellcome, " + userName + "!", Toast.LENGTH_LONG).show();
}
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
boolean findUser(String userName, String psw, boolean userOnly)
{
String nomeFileAccounts = getApplicationContext().getFilesDir().getPath() + "/" + getString(R.string.nomeFileAccounts);
boolean userExists = false;
File f = new File(nomeFileAccounts);
if (f.exists()) {
try {
FileReader fileLeggi = new FileReader(nomeFileAccounts);
BufferedReader lettore = new BufferedReader(fileLeggi);
String rigaLetta = "";
String[] datiAccount = null;
while ((rigaLetta=lettore.readLine()) != null && !userExists)
{
datiAccount = rigaLetta.split(" ");
userExists = datiAccount[0].compareTo(userName) == 0;
if (!soloUser)
userExists = userExists && datiAccount[1].compareTo(psw)==0;
}
lettore.close();
fileLeggi.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
try {
f.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.PrintStack();
}
return userExists ;
}
这适用于Android Emulator,使用Eclipse的文件浏览器我可以在data / data / application /中看到用户的文件。
但是当我导出签名的apk并尝试我的Galaxy Note 3时,我尝试点击注册并工作,但登录点击让应用程序崩溃..出了什么问题?