OneTime设置屏幕Android错误

时间:2015-04-06 10:15:50

标签: java android android-studio

我是Android开发的新手,并尝试制作一个第一次显示屏幕并要求用户设置密码的应用程序,并且在设置密码后,该屏幕永远不再显示。 我写了一个实现这个的基本代码,但是当在模拟器上运行我的应用程序时,会一次又一次地显示相同的设置屏幕。任何人都可以指出原因吗?

代码:

    package com.example.homeautomation.zigbeehomeauto;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;



public class SetupScreen extends ActionBarActivity {
View v ;
    public static final String PREFS_NAME = "MyPrefsFile";


    @Override
    protected void onCreate(Bundle savedInstanceState) {


        SharedPreferences check = getSharedPreferences(PREFS_NAME, 0);
        boolean hasLoggedIn = check.getBoolean("Name", false);


        if (hasLoggedIn) {
            Intent intent = new Intent();
            intent.setClass(SetupScreen.this, MainScreen.class);
            startActivity(intent);
            this.finish();
        }
        else {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_setup_screen);

        }


    }

        public void Send(View v) {
            SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
            SharedPreferences.Editor editor = settings.edit();


        EditText text = (EditText) findViewById(R.id.editText);
        String value = text.getText().toString();
        editor.putString("Name", "value");
        Intent intent = new Intent();
        intent.setClass(SetupScreen.this, MainScreen.class);
        startActivity(intent);
        this.finish();


    }
    }

1 个答案:

答案 0 :(得分:0)

在启动活动之前无法进行某些函数调用,您可以在那里调用getSharedPreferences(),而不是调用onCreate(); 或者,如果您希望每次在onResume();

中使用该值
SharedPreferences settings;

@Override
protected void onResume() //or in onCreate() as per your needs
{
    super.onResume();
    settings = getSharedPreferences(PREFS_NAME, 0);
}

希望这有帮助!