应用程序强制停止访问应用程序专用的内部存储数据

时间:2014-08-09 07:51:32

标签: android

我正在创建一个存储用户名和密码的应用程序,并自动登录到wifi。我将这些数据存储在内部存储中。因此,为了测试数据是否已被永久写入,我制作了一个方法,在toast消息中显示用户名和密码。如果我在应用程序中并保存数据后,我点击显示按钮,它完美地显示数据。但是当我退出应用程序并重新打开后,我点击显示它强制关闭。

public class MyActivity extends Activity {

public Button save;
public Button show;
public EditText user;
public EditText pass;
String PRONTO = "PrivateData";
String un;
String pw;

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

    user = (EditText) findViewById(R.id.username);
    pass = (EditText) findViewById(R.id.password);
    save = (Button) findViewById(R.id.button);
    show = (Button) findViewById(R.id.test);

    save.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

            un = (String) user.getText().toString();
            pw = (String) pass.getText().toString();
            //Creating file for saving username and passwords
            FileOutputStream fos;
            try {
                fos = openFileOutput(PRONTO, Context.MODE_PRIVATE);
                fos.write(un.getBytes());
                fos.write(pw.getBytes());
                fos.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }



        }
    });
    show.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //for testing of storage of data
            FileInputStream fis;

            try {
                fis = openFileInput(PRONTO);
                fis.read(un.getBytes());
                fis.read(pw.getBytes());
                fis.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            //displaying the stored data to user
            Toast.makeText(getApplicationContext(), "Username and Password is" + un + " " + pw, Toast.LENGTH_SHORT).show();

        }
    });
}

}

1 个答案:

答案 0 :(得分:1)

重新打开你的应用程序后

String PRONTO ,String un ,String pw;null

将其声明在您的活动之外,如

String PRONTO="PrivateData";