How to use the sessions in android

Maintain session in Android 

           When you work with an application, you open it, do some changes, and then you close it. This is much like a Session. We can take a simple example of Sign Up, Sign In and Logout process.
           In Most of the cases if we want to enter any application we need to sign up first after that we can enter with the help of username and password. But after sign in / login if we close the application and reopen the home page it should not be asked again me to login because i have already login in the application. So after login my some information should be save locally in the application or it may save to server, and when i will reopen home page it will check whether the user's information save in or not, if saved that i will automatically login to application other wise application will ask for login.

Use the following code to implement it -
package com.example.androidsavestate;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends Activity {

Button login;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        login = (Button)findViewById(R.id.login);
        login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this, Home.class);
startActivity(i);
}
});
    }
    
    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
      // Save UI state changes to the savedInstanceState.
      // This bundle will be passed to onCreate if the process is
      // killed and restarted.
     
      savedInstanceState.putString("Username", "Dheeruapps");
      savedInstanceState.putString("Password", "123456789");
      // etc.
    }
    

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
      // Restore UI state from the savedInstanceState.
      // This bundle has also been passed to onCreate.

      String uname = savedInstanceState.getString("Username");
      String pass  = savedInstanceState.getString("Password");
      
      Toast.makeText(MainActivity.this, uname+" "+pass, 0).show();
      
    }
}

0 comments:

Post a Comment

My Instagram