0

I am working on a registration form. It is the application's second page after the splash screen, which shows a login form and two buttons: login and signup. When we click on signup, it has a signup Form with two buttons: signup and exit.

When the user enters for first time he needs to login or signup, and when 'signup' is pressed, the registration process will start. The user has to provide a username, password, email address, and a mobile number. Once he fills in all this information, he can signin with the username and password.

All of this part is working fine, but my requirement is that after registration, the signup(activity) and login(activity) are deactivated once my application restarts with splash and MainActivity. So what do I have to do to make that work? Can any one help me with this?

How can I deactivate my LoginActivity and SignUpActivity which start with splashActivity and once register start with splash and main Activity again start with splash.

SplashActivity

public class SplashScreen extends Activity {
    private long splashDelay = 5000; //5 seconds

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        TimerTask task = new TimerTask()
        {

            @Override
            public void run() {
                finish();
                Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
                startActivity(mainIntent);
            }

        };

        Timer timer = new Timer();
        timer.schedule(task, splashDelay);
    }
}

Login:

public class LoginActivity extends Activity {

    Intent i;
    Button signin, signup;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        signin = (Button) findViewById(R.id.signin);
        signup = (Button) findViewById(R.id.signup);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        check = (CheckBox) findViewById(R.id.check);
        String Str_user = app_preferences.getString("username", "0");
        String Str_pass = app_preferences.getString("password", "0");
        String Str_check = app_preferences.getString("checked", "no");
        if (Str_check.equals("yes")) {
            editTextId.setText(Str_user);
            editTextP.setText(Str_pass);
            check.setChecked(true);
        }

    }

    public void Move_to_next() 
    {
        final Handler handle = new Handler();
        Runnable delay = new Runnable() {
            public void run() {
                startActivity(new Intent(LoginActivity.this, SplashActivity.class));
                finish();
            }
        };
        handle.postDelayed(delay,2000);

    }

    public void Move_next() 
    {
        startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
        finish();
    }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> 
    {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {

            super.onPreExecute();
            // Show progress dialog here
        }

        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://xxx/login1.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoginActivity.this, "login successfull", Toast.LENGTH_SHORT).show();
                Move_to_next();
            } else {
                Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }
Gray
  • 7,050
  • 2
  • 29
  • 52
UchihaSasuke
  • 363
  • 2
  • 23

7 Answers7

3

I would try this code here:

final Class<?> target;
boolean isUserLoggedIn = app_preferences.getBoolean("checked", false);
if(isUserLoggedIn) {
    target = MainActivity.class;
} else {
    target = Login.class;
}

TimerTask task = new TimerTask() {

    @Override
    public void run() {
        finish();
        Intent mainIntent = new Intent().setClass(SplashScreen.this, target);
        startActivity(mainIntent);
    }

};

Timer timer = new Timer();
timer.schedule(task, splashDelay);

By the way as already Ralph Pina noted you should avoid using splashscreens in general they are not very common on Android. However I would also suggest not to store any credientials in your app. Escpecially in stored preferences. They are plain xml files which can been read out on rooted devices. Better store a token like a session cookie somewhere in your app.

Community
  • 1
  • 1
rekire
  • 47,260
  • 30
  • 167
  • 264
2
setContentView(R.layout.splash_screen);
       pref = getSharedPreferences("ActivityPREF", Context.MODE_PRIVATE);
       Log.v("","onCreate is calling");
       if(pref.getBoolean("activity_executed", false))
       {
            Log.v("","Before if called");
           setContentView(R.layout.splash_screen);
            Log.v("","after if called");
            new Handler().postDelayed(csRunnable1, 3000);

       } 
       else 
       {
          new Handler().postDelayed(csRunnable2, 3000);  
           Editor ed = pref.edit();
           ed.putBoolean("activity_executed", true);
           ed.commit();

       }
   }

   Runnable csRunnable1=new Runnable() 
   {       
       @Override
       public void run() 
       {
            Intent intent = new Intent(SplashScreen.this, SplashActivity.class);
               startActivity(intent);
               finish();

       }
   };

   Runnable csRunnable2=new Runnable() 
    {      
       @Override
       public void run() 
       {
            Intent intent = new Intent(SplashScreen.this, LoginActivity.class);
               startActivity(intent);
               finish();

       }
   };

Try this code that will help you

A.Goutam
  • 3,422
  • 9
  • 42
  • 90
  • I have one more query when i install my app start login page but when i press back button it automatically start my app.can u help me. – UchihaSasuke Oct 04 '13 at 14:44
1

Splash pages are not recommended according to the Android Design Guidelines: http://developer.android.com/design/patterns/help.html. Why do you want to make a user wait 5 seconds to access your app?

I have commented your code with my feedback/answers.

Just use SharedPreferences. That is the easiest way:

public class SplashScreen extends Activity {
    private long splashDelay = 5000; //5 seconds

    private Activity splashScreen;
    private Intent intent;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_screen);

        splashScreen = this;

        // get your shared preferences stored in your app. If the username has been
        // set then this user has already logged in    
        SharedPreferences prefs = getSharedPreferences("name_for_file", 0);
        // return the username of null if none exists
        String username = prefs.getString("username", null);

        // if user has already logged in, just go to MainActivity
        if (username == null) {
             intent = new Intent(this, LoginActivity.class);
        } else {
             intent = new Intent(this, MainActivity.class);
        }

        TimerTask task = new TimerTask()
        {

            @Override
            public void run() {
                //finish(); <- you don't need to call finish, the OS takes care of that

                splashScreen.startActivity(intent);
            }

        };

        Timer timer = new Timer();
        timer.schedule(task, splashDelay);
    }
}


public class LoginActivity extends Activity {

    Intent i;
    Button signin, signup;
    CheckBox check;
    String name = "", pass = "";
    byte[] data;
    HttpPost httppost;
    StringBuffer buffer;
    HttpResponse response;
    HttpClient httpclient;
    InputStream inputStream;
    SharedPreferences app_preferences;
    List<NameValuePair> nameValuePairs;
    EditText editTextId, editTextP;
    Activity loginActivity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        loginActivity = this;
        signin = (Button) findViewById(R.id.signin);
        signup = (Button) findViewById(R.id.signup);
        editTextId = (EditText) findViewById(R.id.editTextId);
        editTextP = (EditText) findViewById(R.id.editTextP);
        // app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
        app_preferences = getSharedPreferences("name_of_file", 0);
        check = (CheckBox) findViewById(R.id.check);
        // if they got to this activity they are not logged in, so why are you
        // checking here?
        // the common pattern is to use null
        // String Str_user = app_preferences.getString("username", null);
        // String Str_pass = app_preferences.getString("password", null);
        // checked only has two states, use a boolean
        // boolean Str_check = app_preferences.getBoolean("checked", false);
        // if (Str_check)) {
        //    editTextId.setText(Str_user);
        //    editTextP.setText(Str_pass);
        //    check.setChecked(true);
        // }

        signin.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                 LoginTask login = new LoginTask();
                 login.execute();
            }
         });

         signup.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                 Intent intent = new Intent(this, SignUpActivity.class)
                 startActivity(intent);
            }
         });


    }

    // why are you sending them back to the splash?
    public void Move_to_next() 
    {
        final Handler handle = new Handler();
        Runnable delay = new Runnable() {
            public void run() {
                startActivity(new Intent(LoginActivity.this, SplashActivity.class));
                finish();
            }
        };
        //why are you making people wait?
        handle.postDelayed(delay,2000);

    }

    // This is never being called
    public void Move_next() 
    {
        startActivity(new Intent(LoginActivity.this, SignUpActivity.class));
        //finish(); <- the OS will do this
    }

    @SuppressLint("NewApi")
    private class LoginTask extends AsyncTask <Void, Void, String> 
    {
        @SuppressLint("NewApi")
        @Override
        protected void onPreExecute() 
        {

            super.onPreExecute();
            // Show progress dialog here
        }

        // best practice for android is to use HttpUrlConnection: 
        // http://android-developers.blogspot.com/2011/09/androids-http-clients.html
        // there is also AndroidHttpClient, which is the class google used in their
        // Google IO 2013 app. It is pretty clean. https://code.google.com/p/basic-http-client/
        /*
        AndroidHttpClient httpClient = new AndroidHttpClient("http://www.google.com");
        ParameterMap params = httpClient.newParams().add("q", "GOOG");
        httpClient.setMaxRetries(3);
        httpClient.get("/finance", params, new AsyncCallback() {
            public void onComplete(HttpResponse httpResponse) {
                System.out.println(httpResponse.getBodyAsString());
            }
            public void onError(Exception e) {
                e.printStackTrace();
            }
        });
        */
        @Override
        protected String doInBackground(Void... arg0) {
            try {
                httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://xxx/login1.php");
                // Add your data
                nameValuePairs = new ArrayList<NameValuePair>(2);
                nameValuePairs.add(new BasicNameValuePair("UserEmail", name.trim()));
                nameValuePairs.add(new BasicNameValuePair("Password", pass.trim()));
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                // Execute HTTP Post Request
                response = httpclient.execute(httppost);
                inputStream = response.getEntity().getContent();
                data = new byte[256];
                buffer = new StringBuffer();
                int len = 0;
                while (-1 != (len = inputStream.read(data))) {
                    buffer.append(new String(data, 0, len));
                }

                inputStream.close();
                return buffer.toString();
            } 
            catch (Exception e) 
            {
                e.printStackTrace();

            }
            return "";
        }

        @SuppressLint("NewApi")
        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            // Hide progress dialog here

            if (buffer.charAt(0) == 'Y') {
                Toast.makeText(LoginActivity.this, "login successful", Toast.LENGTH_SHORT).show();
                // don't send them back to the splash, they are logged in
                // save username and pass, and move forward
                SharedPreferences settings = loginActivity.getSharedPreferences("name_of_file", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("username", put whatever you get from server).commit();
                editor.putString("password", put whatever you get from server).commit();
                Intent intent = new Intent(loginActivity, WelcomeActivity.class);
                startActivity(intent);
            } else {
                Toast.makeText(LoginActivity.this, "Invalid Username or password", Toast.LENGTH_SHORT).show();
            }
        }
    }
Ralph Pina
  • 761
  • 7
  • 16
  • Splash screens for the sole purpose of branding or displaying help are not recommended, but to hide essential loading, it is ok: http://developer.android.com/training/articles/perf-anr.html#Reinforcing – FunkTheMonk Oct 03 '13 at 13:13
  • @FunkTheMonk check out Android Design in Action, http://www.youtube.com/watch?v=pEGWcMTxs3I, see minute 23:30. Poor onboarding (including splash screens) is the #2 Android design anti-pattern. They mention other ways to do branding. ActionBar icon, color hues, etc. This one talks about onboarding specifically, so it goes into more detail about splash screens: http://www.youtube.com/watch?v=LhzAr9reu_4, see minute 1:30. Splash screens is the first thing they talk about. If your marketing/PM person is pushing you on this, I would point them to those videos and the Android Design Guidelines. – Ralph Pina Oct 03 '13 at 13:42
  • i have implement it in my splash screen it open my page but my login stop working..:( – UchihaSasuke Oct 03 '13 at 13:55
  • @ChandanKumar yeah, I had a couple of bugs. I was calling this, getSharedPreferences, and startActivity insider the TaskTimer, which is not an activity. The fix above should run. – Ralph Pina Oct 03 '13 at 14:05
  • @RalphPina where i have to use sharedprefrence. right now i have 4 activity SplashActivity, LoginActivity, SignUpActivity MainActivity .First when my app load .it start with SplashScreen -> login or Signup-> MainActivity but i wanted to include sharedpreference in my code so when i get login which work like this SplashScreen -> MainActivity. – UchihaSasuke Oct 03 '13 at 14:27
  • @ChandanKumar I would use SharedPreference in whatever activity you need to get or set user/password/phone/whatever. You can get it from any activity by calling getSharedPreferences("name_of_file_you_are_saving_to, 0). The 0 says it is private to your app, so no one outside of that can touch it. getSharedPreferences(String name, int mode) is in Context and android.app.Activity is subclass of android.content.Context. – Ralph Pina Oct 03 '13 at 15:36
  • @ChandanKumar the one caviat with SharedPreferences is that reading/writing is expensive. So if you are doing it a TON, and saving a BUNCH of data, just use SQLite. You can use ORMLite or greenDAO to make this easier on you, but if you are just saving a couple of fields and reading/writing a couple of times, SharedPreferences is the best way. – Ralph Pina Oct 03 '13 at 15:38
  • @RalphPina I am using SQlite for some data but i have need to connect with PHP and Its first time i hear about ORMLite or GreenDAO can you refer some link on this topic. – UchihaSasuke Oct 04 '13 at 14:06
  • Difference between greenDao and ORMLite: http://stackoverflow.com/questions/13680954/green-dao-vs-orm-lite-vs-active-android. ORMLite: http://ormlite.com/, greenDao: http://greendao-orm.com/ – Ralph Pina Oct 04 '13 at 14:59
0

once the signin/ sign up is done save it in SharedPreferences.put a boolian flag as true and save in SharedPreferences. on the splash screen check this flag. if its true go to mainactivity else go to signup activity.

null pointer
  • 5,874
  • 4
  • 36
  • 66
0

In android you need to store the value of any variable(boolean or whatever u feel comfortable) in persistence storage like either database or in sharedpreference and check this value before launch the activity if value is true means user is already signup and if the value is false means you need to display the login or siginup activity again.

Edit check the value of that variable before launch

SplashActivity

public class SplashScreen extends Activity {
private long splashDelay = 5000; //5 seconds

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_screen);

    TimerTask task = new TimerTask()
    {

        @Override
        public void run() {
            finish();
// someBoolean  which is stored sharedprefs in your second or login activity
if(someBoolean = true)
Intent mainIntent = new Intent().setClass(SplashScreen.this, LoginActivity.class);
            startActivity(mainIntent)
Vivek Bajpai
  • 1,617
  • 1
  • 19
  • 35
0

Once the login/signup is success you can set a boolean value in a SharedPreferences and that you can check in your splash screen and decide which screen has to show.

Rajiv Ratan
  • 129
  • 4
0

You can use shared preference for show SignIn and SignUp Once.

This is My Splash Screen Code.

public class Splash extends Activity {

SessionManage sm;
Context _context;
Thread timer= new Thread(){
    public void run(){
        try{
            sleep(2000);
        }catch(InterruptedException axe){
            axe.printStackTrace();
        }finally{
            sm= new SessionManage(_context);
            startActivity(sm.checkLogin());

        }

    }
        };

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash);
    this._context= getApplicationContext();

timer.start();

}

This is my Session Manager Class

public class SessionManage {
SharedPreferences share;
public static final String filename= "data";
SharedPreferences.Editor editor;
Context _context;
String sname,semail;
ArrayList<String> BookArray;
Set<String> set;
@SuppressLint("CommitPrefEdits")
public SessionManage(Context context){
    this._context= context;
    share = _context.getSharedPreferences(filename, 0);
    editor = share.edit();

}

public void login(String lname, String lemail){
    this.sname= lname;
    this.semail= lemail;

    editor.putString("name", lname);
    editor.putString("email", lemail);

    editor.commit();
}

public Intent checkLogin(){
    Intent vs;

    semail= share.getString("email", "Guest");
     if (semail.equalsIgnoreCase("Guest")){
         vs= new Intent(_context, Login.class );
     }
     else{
         vs= new Intent(_context, Populer.class );
     }
     return vs;
}

This is code of login button click in Login Activity.

    sm= new SessionManage(getApplicationContext());
        vs= new Intent(getApplicationContext(), Populer.class);
        sm.login(sname, semail);
   }
AmmY
  • 1,821
  • 1
  • 20
  • 31