2016-11-19 35 views
0

所以我正在跟随教程,一切都很好,直到我跑了应用程序,并遇到此问题。每次我重新启动我的应用程序,我的活动将返回到LoginActivity而不是MainActivity。这里是我的代码Android共享偏好重新启动应用程序

会话管理器

SharedPreferences pref; 
SharedPreferences.Editor editor; 
Context _context; 

int PRIVATE_MODE = 0; 

private static final String PREF_NAME = "users"; 

private static final String IS_LOGIN = "IsLoggedIn"; 
//userID and userName 
public static final String KEY_USERNAME = "name"; 
// public static final String KEY_USERID = "userid"; 

//Constructor 
public SessionManager(Context context) { 
    this._context = context; 
    this.pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
    this.editor = pref.edit(); 
    this.editor.commit(); 
    this.editor.clear(); 
} 

public void createLoginSession(String username) { 
    editor.putBoolean(IS_LOGIN, true); 
    editor.putString(KEY_USERNAME, username); 
    editor.commit(); 
    // editor.putString(KEY_USERID, userID); 
} 

public void checkLogin() { 
    if (!this.isLoggedIn()) { 
     Intent i = new Intent(_context, SplashScreen.class); 
     i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); 
     this._context.startActivity(i); 
    } 
} 


public HashMap<String, String> getUserDetails() { 
    HashMap<String, String> user = new HashMap<>(); 
    user.put(KEY_USERNAME, pref.getString(KEY_USERNAME, null)); 
    return user; 
} 

public void logoutUser() { 
    editor.clear(); 
    editor.commit(); 
    Intent i = new Intent(_context, SplashScreen.class); 
    i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
    _context.startActivity(i); 
} 

public boolean isLoggedIn() { 
    return pref.getBoolean(IS_LOGIN, false); 
} 

登录活动

TextView register_link; 
Button btnLogin; 
EditText eTxtUsername, eTxtPassword; 
SessionManager session; 

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

    this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
    // 
    register_link = (TextView) findViewById(R.id.tv_register_link); 
    btnLogin = (Button) findViewById(R.id.buttonSignIn); 
    eTxtUsername = (EditText) findViewById(R.id.eTxt_username); 
    eTxtPassword = (EditText) findViewById(R.id.eTxt_password); 
    session = new SessionManager(getApplicationContext()); 
    // 
    final AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this); 

    Toast.makeText(this, "Login status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); 


    register_link.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent i = new Intent(LoginActivity.this, RegisterActivity.class); 
      LoginActivity.this.startActivity(i); 
     } 
    }); 

    btnLogin.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 

      final String username_ = eTxtUsername.getText().toString(); 
      final String password_ = eTxtPassword.getText().toString(); 

      if (isEmptyFields(username_, password_)) { 
       builder.setMessage("Please provide all fields") 
         .setNegativeButton("Retry", null) 
         .create() 
         .show(); 
      } else { 
       Response.Listener<String> responseListener = new Response.Listener<String>() { 
        @Override 
        public void onResponse(String response) { 
         try { 
          JSONObject jsonResponse = new JSONObject(response); 
          final boolean success = jsonResponse.getBoolean("success"); 

          if (success) { 
           final String userid_ = String.valueOf(jsonResponse.getInt("userid")); 

           session.createLoginSession(username_); 
           Toast.makeText(getApplicationContext(), "Login Success", 
             Toast.LENGTH_SHORT).show(); 
           Intent i = new Intent(getApplicationContext(), MainActivity.class); 
           i.putExtra("userId", userid_); 
           startActivity(i); 
           finish(); 
          } else { 
           builder.setMessage("Login Failed") 
             .setNegativeButton("Retry", null) 
             .create() 
             .show(); 
          } 
         } catch (JSONException e) { 
          e.printStackTrace(); 
         } 
        } 
       }; 

       LoginRequest loginRequest = new LoginRequest(username_, password_, responseListener); 
       RequestQueue queue = Volley.newRequestQueue(LoginActivity.this); 
       queue.add(loginRequest); 
      } 
     } 
    }); 
} 

static boolean isEmptyFields(String n1, String pw1) { 
    final boolean result; 

    if (n1.isEmpty() || pw1.isEmpty()) 
     result = true; 
    else 
     result = false; 

    return result; 
} 

主要活动

private Drawer result = null; 
private String userid; 
SessionManager session; 

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    final Button btn_showlist = (Button) findViewById(R.id.btn_showlist); 
    session = new SessionManager(this); 

    Toast.makeText(this, "Login status: " + session.isLoggedIn(), Toast.LENGTH_LONG).show(); 

    session.checkLogin(); 
    HashMap<String, String> user = session.getUserDetails(); 
    // userid = user.get(SessionManager.KEY_USERID); 
    String username = user.get(SessionManager.KEY_USERNAME); 

    //create drawer 
    new DrawerBuilder().withActivity(this).build(); 
    CreateDrawer(CreateAccountDrawer(), toolbar); 

    btn_showlist.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Intent i = new Intent(MainActivity.this, ListActivity.class); 
      startActivity(i); 
     } 
    }); 
} 

@Override 
protected void onResume() { 
    super.onResume(); 
    result.deselect(); 
} 

//CREATE DRAWER 
@Override 
protected void attachBaseContext(Context newBase) { 
    super.attachBaseContext(IconicsContextWrapper.wrap(newBase)); 
} 

private AccountHeader CreateAccountDrawer() { 

    AccountHeader headerResult = new AccountHeaderBuilder() 
      .withActivity(this) 
      .withSelectionListEnabledForSingleProfile(false) 
      .withHeaderBackground(R.drawable.header1) 
      .addProfiles(
        new ProfileDrawerItem().withName("New User").withIcon(getResources() 
          .getDrawable(R.drawable.profile)) 
      ) 
      .withOnAccountHeaderListener(new AccountHeader.OnAccountHeaderListener() { 
       @Override 
       public boolean onProfileChanged(View view, IProfile profile, boolean currentProfile) { 
        return false; 
       } 
      }) 
      .build(); 

    return headerResult; 

} 

private void CreateDrawer(AccountHeader header, Toolbar toolbar) { 

    PrimaryDrawerItem p_item1 = new PrimaryDrawerItem().withSetSelected(true).withIdentifier(1) 
      .withName(R.string.map).withIcon(FontAwesome.Icon.faw_map); 
    PrimaryDrawerItem p_item2 = new PrimaryDrawerItem().withIdentifier(2) 
      .withName(R.string.analyze_soil).withIcon(FontAwesome.Icon.faw_bullseye); 
    PrimaryDrawerItem p_item3 = new PrimaryDrawerItem().withIdentifier(3) 
      .withName(R.string.drawer_item_statistic).withIcon(FontAwesome.Icon.faw_line_chart); 
    // 
    SecondaryDrawerItem s_item1 = new SecondaryDrawerItem().withIdentifier(4) 
      .withName(R.string.drawer_item_app_settings).withIcon(FontAwesome.Icon.faw_cog); 
    SecondaryDrawerItem s_item2 = new SecondaryDrawerItem().withIdentifier(5) 
      .withName(R.string.drawer_item_account_settings).withIcon(FontAwesome.Icon.faw_cog); 
    SecondaryDrawerItem s_item3 = new SecondaryDrawerItem().withIdentifier(6) 
      .withName(R.string.logout).withIcon(FontAwesome.Icon.faw_sign_out); 

    //Create the drawer and remember the `Drawer` result object 
    result = new DrawerBuilder() 
      .withActivity(this) 
      .withAccountHeader(header) 
      .withToolbar(toolbar) 
      .addDrawerItems(
        p_item2, 
        p_item1, 
        p_item3, 
        new DividerDrawerItem(), 
        s_item1, 
        s_item2, 
        new DividerDrawerItem(), 
        s_item3 
      ) 
      .withOnDrawerItemClickListener(new Drawer.OnDrawerItemClickListener() { 
       @Override 
       public boolean onItemClick(View view, int position, IDrawerItem drawerItem) { 

        int clickedID = (int) drawerItem.getIdentifier(); 
        Intent i; 
        switch (clickedID) { 
         case 1: 
          drawerItem.withSetSelected(false); 
          i = new Intent(MainActivity.this, MapsActivity.class); 
          startActivity(i); 
          break; 
         case 2: 
          drawerItem.withSetSelected(false); 
          i = new Intent(MainActivity.this, AnalyzeSoilActivity.class); 
          startActivity(i); 
          break; 
         case 3: 
          drawerItem.withSetSelected(false); 
          i = new Intent(MainActivity.this, StatisticActivity.class); 
          startActivity(i); 
          break; 
         case 4: 
          drawerItem.withSetSelected(false); 
          i = new Intent(MainActivity.this, AppSettingActivity.class); 
          startActivity(i); 
          break; 
         case 5: 
          drawerItem.withSetSelected(false); 
          i = new Intent(MainActivity.this, AccountSettingActivity.class); 
          startActivity(i); 
          break; 
         case 6: 
          session.logoutUser(); 
          break; 
        } 
        return false; 
       } 
      }) 
      .build(); 
} 
+0

删除。它可能会活着 –

+0

重新开始并重新阅读。在构造函数中没有明确或提交。 http://www.androidhive.info/2012/08/android-session-management-using-shared-preferences/ –

+0

已经删除this.editor.clear();并重新开始。仍然是同样的问题。我也试图寻找共享首选的XML文件没有运气。卡住了这个问题。 – FritsJ

回答

0

他你好像你正在为每个活动创建会话实例。尝试创建单独的共享首选项类。在这里,当你调用构造函数

//Constructor 
public SessionManager(Context context) { 
    this._context = context; 
    this.pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
    this.editor = pref.edit(); 
    this.editor.commit(); 
    this.editor.clear(); 
} 

的editor.clear()被调用它,当你达到清除你的喜好主要活动

+0

也从您的构造函数 –

+0

中删除editor.clear()仍然无法正常工作。我用吐司来显示登录的状态,它显示为true,但每次我重新启动应用程序时,它都会返回登录活动。 – FritsJ

+0

你是否为共享偏好设置了单身课程? –

0

你必须改变你SessionManager构造如下图所示:

public SessionManager(Context context) { 
    this._context = context; 
    this.pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE); 
    this.editor = pref.edit(); 
    this.editor.commit(); 
} 

您在编辑器上调用了清除方法,因此每次运行MainActivity时,会话管理器都会首先读取共享的pref值,然后清除它们。这就像你正在清除值,然后你想要它的数据!

+0

仍然不工作兄弟。我用吐司来显示登录的状态,它显示为true,但每次我重新启动应用程序时,它都会返回登录活动。 – FritsJ

0

公共类MyPreferences实现AppConstants,VCardStorage {

private static final String TAG = "MyPreferences"; 
private static final String APP_PREFS = "my_prefs"; 

private static MyPreferences mPreferences; 
private SharedPreferences mPreferences; 
private Editor mEditor; 
private Context mContext; 


private MyPreferences(Context context) { 
    mContext = context; 
    mPreferences = context.getSharedPreferences(APP_PREFS, Context.MODE_PRIVATE); 
    mEditor = mPreferences.edit(); 
} 

public static MyPreferences getInstance(Context context) { 
    if (mPreferences == null) { 
     mPreferences = new MyPreferences(context); 
    } 
    return mPreferences; 
} 

public void removeKey(String key) { 
    mEditor.remove(key).apply(); 
} 

public void clear() { 
    mEditor.clear().commit(); 
    ciaoPreferences = null; 
} 

public AppState getAppState() { 
    String state = mPreferences.getString(PREFS_APP_STATE, AppState.INSTALLED.name()); 
    return AppState.valueOf(state); 
} 

public void setAppState(AppState state) { 
    mEditor.putString(PREFS_APP_STATE, state.name()).apply(); 
} 
+0

尝试使用这个单例类。它的工作原理和在我的应用程序中,我保持使用枚举值的应用程序状态,因为我在我的应用程序中有2-3个状态 –

+0

单例(虽然更好)不是解决方案。阅读我的答案后再次检查代码 –

0

每次我重新启动我的应用我的活动将只是回到LoginActivity代替MainActivity

大概是因为LoginActivity(或SplashActivity)是清单中设置的主要活动。

onCreate中没有代码可以在登录活动按钮单击之外启动MainActivity。实现SharedPreferences不仅仅是为你做。从构造`;

// top of onCreate 
super.onCreate(savedInstanceState); 
session = new SessionManager(getApplicationContext()); 
boolean loggedIn = session.isLoggedIn() 
Toast.makeText(this, "Login status: " + loggedIn, Toast.LENGTH_LONG).show(); 
if (loggedIn) { 
    // start MainActivity 
    finish(); // don't need this activity 
} else { 
    // load LoginActivity 
} 

而且从构造`this.editor.clear()除去

this.editor.clear(); 
+0

是的清单中的Splash Activity被设置为我的Launcher。已经尝试删除this.editor.clear();仍然存在问题 – FritsJ

+0

您没有阅读帖子的其余部分。 startActivity在哪里登录? –

+0

它在主要活动中。 – FritsJ