-6

I Have Created an app. after successful login i get redirected to another activity i.e my main activity but when i close the app i have to login again.. i want to stay logged in unless i click on logout button..how can i do this? p.s i have used php database to hold login information and background worker for redirecting to another activity. please help..i have to submit my project in a 3 days time...thanks in advance :D

Login Page:-

import android.R.string;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.opengl.ETC1;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;


public class login extends Activity {


    SharedPreferences prefs;//new line
    EditText UsernameEt, PasswordEt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        prefs = PreferenceManager.getDefaultSharedPreferences();//new line
        UsernameEt = (EditText)findViewById(R.id.etUserNamez);
        PasswordEt = (EditText)findViewById(R.id.etPasswordz);
        if(prefs.getBoolean("locked", false)){//new line
              Intent intent = new Intent(context,Main.class);//new line
              startActivity(intent);//new line
             }//new line
    }

public void OnLogin(View view) {
    String username = UsernameEt.getText().toString();
    String password = PasswordEt.getText().toString();
    String type = "login";
    BackgroundWorker backgroundWorker = new BackgroundWorker(this);
    backgroundWorker.execute(type, username, password);
}

}

BackGroundWorker Activity:-

package com.project.v_app;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;

public class BackgroundWorker extends AsyncTask<String, Void, String> {
    Context context;
    AlertDialog alertDialog;
    BackgroundWorker (Context ctx){
        context = ctx;
    }
    @Override
    protected String doInBackground(String... params) {
        String type = params[0];
        String login_url = "http://192.168.0.103/login.php";
        if(type.equals("login"))
        {
            try {
                String user_name = params[1];
                String password = params[2];
                URL url = new URL(login_url);
                HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("POST");
                httpURLConnection.setDoOutput(true);
                httpURLConnection.setDoInput(true);
                OutputStream outputStream = httpURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
                        +URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
                bufferedWriter.write(post_data);
                bufferedWriter.flush();
                bufferedWriter.close();
                outputStream.close();
                InputStream inputStream = httpURLConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
                String result="";
                String line="";
                while((line = bufferedReader.readLine())!=null)
                {
                    result +=line;
                }
                bufferedReader.close();
                inputStream.close();
                httpURLConnection.disconnect();
                return result;
            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onPreExecute() {
    alertDialog = new AlertDialog.Builder(context).create();
    alertDialog.setTitle("Login Status");
    }

    @Override
    protected void onPostExecute(String result) {
        if(result!=null && result.equals("Login Not Success")){
        alertDialog.setMessage(result);
        alertDialog.show();
        }
        if(result!=null && result.equals("Login Success")){
            prefs.edit().putBoolean("locked", true).commit();//new line
            Intent intent = new Intent(context,Main.class);
            context.startActivity(intent);
            }
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
    }

}

Main Activity:-

package com.project.v_app;

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;

public class Main extends Activity {

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

        Button tt=(Button) findViewById(R.id.loginbutton);
         tt.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, timetable.class));
            }
        });

         Button uc= (Button) findViewById(R.id.button2);
         uc.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, upcoming.class));
            }
        });

         Button rem= (Button) findViewById(R.id.button3);
         rem.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, reminder.class));
            }
        });

         Button ev= (Button) findViewById(R.id.button4);
         ev.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, events.class));
            }
        });

         Button news= (Button) findViewById(R.id.button5);
        news.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, news.class));
            }
        });

         Button fb= (Button) findViewById(R.id.button6);
         fb.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                startActivity(new Intent(Main.this, feedback.class));
            }
        });


    }
}
sushildlh
  • 8,986
  • 4
  • 33
  • 77
ksax95
  • 19
  • 1
  • 4
  • you can do it using shared preferences.see this http://androidexample.com/Android_Session_Management_Using_SharedPreferences_-_Android_Example/index.php?view=article_discription&aid=127&aaid=147 – Rooban May 04 '16 at 04:10
  • Possible duplicate of [How to keep android applications always be logged in state?](http://stackoverflow.com/questions/12744337/how-to-keep-android-applications-always-be-logged-in-state) – KishuDroid May 04 '16 at 04:20
  • @ksax95 are you there ?? – sushildlh May 08 '16 at 11:19
  • and put these 2 line in your logout button ...... `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(); prefs.edit().putBoolean("locked", false).commit();` that is all now it is all set. Enjoy coding ......... – sushildlh May 08 '16 at 11:40
  • use `this` insead of `context`...... – sushildlh May 08 '16 at 11:42
  • prefs cannot be resolved in background worker @SushilKumar – ksax95 May 08 '16 at 11:45
  • create this line in your background worker .... `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences();` inside PostExecute() method ...... – sushildlh May 08 '16 at 11:49
  • pass in `backgroundWorker.execute(this,type, username, password);` in this method – sushildlh May 08 '16 at 11:57
  • app crashes when i click on logout button @SushilKumar – ksax95 May 08 '16 at 11:57
  • `doInBackground(Context context,String... params)` put argument inside it.. and inside this method just do `this.context=context;` – sushildlh May 08 '16 at 12:01
  • does any problem ? – sushildlh May 08 '16 at 12:11
  • session is created but app crashes when i click on logout button Logout Button Code : TextView tv = (TextView) findViewById(R.id.textView1); tv.setOnClickListener(new OnClickListener(){ public void onClick(View v){ SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(null); prefs.edit().putBoolean("locked", false).commit(); startActivity(new Intent(Main.this,login.class)); } – ksax95 May 08 '16 at 12:12
  • use `this` instead of `null` in this line `SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(null); ` – sushildlh May 08 '16 at 12:15
  • The method getDefaultSharedPreferences(Context) in the type PreferenceManager is not applicable for the arguments (new View.OnClickListener(){}) – ksax95 May 08 '16 at 12:16
  • where is your logout Activity just post it – sushildlh May 08 '16 at 12:17
  • logout button is working now..but when i click back button it goes to the main activity without asking username and password – ksax95 May 08 '16 at 12:20
  • why he asked you username you are log in.When you logout then he asked you username and password – sushildlh May 08 '16 at 12:24
  • done thanks a lot :D @SushilKumar – ksax95 May 08 '16 at 12:26
  • add after this line `startActivity(intent);//new line` in you login and Background wroker `finish();` in login anctivity and `context.finish();` in BackGround class so when you log in and press back button it close you app; – sushildlh May 08 '16 at 12:27
  • close the question .............. – sushildlh May 08 '16 at 12:31

1 Answers1

0

You can Use SharedPreferences. Take a Boolean Value and set it to true when you login. And after you click on Logout set it to False. Redirect the pages after your splash screen accordingly.

You can create a sperate class of sharedPreferences. Eg :

 public class CustomSharedPreferences {
  public CustomSharedPreferences(Context context) {
    // TODO Auto-generated constructor stub
    prefs = getMyPreferences(context);
    this._context = context;
    prefs = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = prefs.edit();
}


private static SharedPreferences getMyPreferences(Context context) {
    return context.getSharedPreferences(Util.APP_PREFERENCES,
            Context.MODE_PRIVATE);
}


public boolean isLogin() {
    return prefs.getBoolean("isLogin", false);
}

public void setIsLogin(boolean isLogin) {
    this.isLogin = isLogin;
    editor.putBoolean("isLogin", isLogin).commit();
}         
}

//SplashScreenActivity

public class SplashScreenActivity extends AppCompatActivity {

private CustomSharedPreferences customSharedPreferences;

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


    customSharedPreferences = new CustomSharedPreferences(getApplicationContext());

    new Handler().postDelayed(new Runnable() {
        // Using handler with postDelayed called runnable run method
        @Override
        public void run() {
            Intent i;
            if (customSharedPreferences.isLogin()) {
                i = new Intent(SplashScreenActivity.this, MainActivity.class);
            } else {
                i = new Intent(SplashScreenActivity.this, LoginActivity.class);
            }
            startActivity(i);
            finish();
        }
    }, 5 * 1000); // wait for 5 seconds
}    
}

//LoginActivity

  public class LoginActivity{

    //Object of CustomSharedPreferences Class
    customSharedPreferences = new CustomSharedPreferences(getApplicationContext());

 //After Clicking the Login Button
   customSharedPreferences.setIsLogin(true);
    }
AmeyaG
  • 176
  • 1
  • 1
  • 10