-1

Goodday, I'm trying to create a login and logout with my app. Here is what i do, In my login activityi add this

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login_layout);

    String Username = new SessionHandler().getUsername(this);
        if(!Username.toString().equals("")){
            Intent mainIntent = new Intent(Login_activity.this,MainActivity.class);
            startActivity(mainIntent);
        }
}

and here is my SessionHandler().getUsername()

  public String getUsername(Context context){
        sess_content = context.getSharedPreferences("LoginInfo", Context.MODE_PRIVATE); //1
        Username = sess_content.getString("Username", null); //2
        return Username;
    }

So, here is the problem when i already login i can pass the login activity and open main activity but when i logout then trying to open my app again . I get an error.

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.boby.helpdesk/com.example.boby.helpdesk.Login_activity}: java.lang.NullPointerException

this is how i set my SharedPreferences

public  void setSession(String name,String notelp,String alamat,String deskripsi,Context context){
    SharedPreferences.Editor editor = context.getSharedPreferences("LoginInfo", MODE_PRIVATE).edit();
    editor.putString("Username", name);
    editor.putString("NoTelp", notelp);
    editor.putString("Alamat", alamat);
    editor.putString("Deskripsi", deskripsi);
    editor.apply();
}
Boby
  • 1,131
  • 3
  • 20
  • 52

2 Answers2

2

Change code in onCreate method to below

String Username = new SessionHandler().getUsername(this);
        if(Username != null && !Username.isEmpty()){
            Intent mainIntent = new Intent(Login_activity.this,MainActivity.class);
            startActivity(mainIntent);
        }
Rajan Kali
  • 12,627
  • 3
  • 25
  • 37
0

change null to empty or as @rajan ks:

public String getUsername(Context context){
        sess_content = context.getSharedPreferences("LoginInfo", Context.MODE_PRIVATE); //1
        Username = sess_content.getString("Username", ""); //2
        return Username;
    }
D T
  • 3,522
  • 7
  • 45
  • 89