Skip to main content

Open the last opened activity in Android and save values. (Android Studio)


Hello devs!

This post is going to tell you a way to open the last opened activity in Android.
There are cases where we keep a login for the app and we need to use that login every time we open the app. However, you see in good apps, you don't need to login each time unless you logout. Following are the ways to achieve this:



1. Firebase Auth- this is the simplest way. However, if you don't want to use Firebase or have your own API, check out the next method.

2. SharedPreferences - Following is the way to make use of that:

1. In every activity you wish to open, add the following code.

@Override
protected void onPause() {
    super.onPause();

    SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString("lastActivity", getClass().getName());
    editor.commit();
}


This could be your MainActivity and your LoginActivity.

2. Next, create a class called as DispatcherClass with the following code-

public class DispatcherClass extends Activity {

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

        Class<?> activityClass;

        try {
            SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
            activityClass = Class.forName(
                    prefs.getString("lastActivity", DefaultActivity.class.getName()));
        } catch(ClassNotFoundException ex) {
            activityClass = LoginActivity.class;
        }

        startActivity(new Intent(this, activityClass));
        finish();
    }
}

Here the DefaultActivity could be your LoginActivity or MainActivity.

3. Now, we need to edit the AndroidManifest.xml file-
 Add the following activity-

<activity android:name=".activities.DispatcherClass">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>

</activity>

At the same time, remove the following from other activities(if present)-
  <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />

This tells the default opening activity.

4. (Optional) This is sufficient to get the functionality. But at times, we need to send values from one activity to another. We usually use .putExtra(key,value) and .getExtra(key) to do that. However, if you are using the above method, the app will crash as we are not actually passing from screens. In that case, you need to use SharedPreferences. Here's how you store data-

SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("key","value");
editor.commit();

And in order to remove that key, use-

SharedPreferences prefs = getSharedPreferences("X", MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.remove("key");
editor.apply();


That's all folks! Hope you find this useful.

Credits-https://stackoverflow.com/questions/2441203/how-to-make-an-android-app-return-to-the-last-open-activity-when-relaunched

Comments

Popular posts from this blog

Shake a view(edit text) on incorrect input at OTP,passwords,etc (Android)

Hello devs! This is another short tutorial to show how to shake an Edit text view if the input is incorrect. Note : The tutorial assumes that you have the basic knowledge about android development. It involves the following steps : 1. Create the Edit text and cast it inside the onCreate. EditText edittext=findViewById(R.id.edit_text); Recommended : https://github.com/GoodieBag/Pinview Optional - Put the edit text inside a dialog to take an input from the dialog. 2. Write an animation XML. Here is an example: ( shake.xml ) Courtesy : https://gist.github.com/simon-heinen/9795036 <? xml version = " 1.0 " encoding = " utf-8 " ?> < set xmlns : android = " http://schemas.android.com/apk/res/android " > < rotate android : duration = " 70 " android : fromDegrees = " -5 " androi...

Fix for eclipse oxygen icon not displaying in ubuntu.

There is a bug in the latest version of eclipse IDE. The icon is not displayed. If you are facing the same problem then I might have a fix for you. There are various reasons why this may occur. One of the problems is caused because icon of eclipse is not present in pixmaps folder. To add it simply copy the icon of eclipse into /use/share/pixmaps folder. Note: You need to have root access to do that.  Also, make sure the name of the icon is eclipse.xpm  For this, use the terminal to fire the command: sudo cp /eclipse_path/icon.xpm /usr/share/pixmaps/eclipse.xpm Here replace the eclipse_path with your eclipse folder path. E.g. /home/leena/eclipse/java-oxygen/eclipse/icon.xpm

Fix 'UNEXPECTED INCONSISTENCY; Run fsck manually' on Ubuntu

If you have the following Ubuntu error, I might have a fix for it. fsck from util-linux 2.26.2 /dev/sda1 contains a file system with errors, check forced. /dev/sda1: Inodes that were part of a corrupted orphan linked list found. /dev/sda1: UNEXPECTED INCONSISTENCY; RUN fsck MANUALLY.         (i.e., without -a or -p options) fsck exited with status code 4 The root filesystem on /dev/sda1 requires a manual fsck Busybox v1.22.1 (Ubuntu 1:1.22.0-15ubuntu1) built in shell (ash) Enter 'help' for a list of built-in commands. (initramfs) _ And believe me help command does nothing. Solution: Just fire a simple command to execute  fsck manually. fsck /dev/sda1 If some other filesystem is causing the error then mention that name after fsck. It will show some processing. If it asks any questions like Fix(y/n)? always enter y . In the end when (initramfs) reappears enter: reboot Well, that's all! It worked for me. Hope it works for ...