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

Create drop-down menu with image icons in Android

Hello devs! In this tutorial, we will be creating a drop-down menu on clicking a button in Android studio. Here is an image of how our menu is going to look: On clicking the hamburger icon, a vertical menu will appear with image icons of your choice. Above image is just to get an idea of what we are going to develop. Let's get started. Step 1: Open the layout file where you want the menu. Add the hamburger icon on an image button. <ImageButton android :layout_width= "50dp" android :layout_height= "50dp" android :src= "@drawable/ham" android :id= "@+id/ham" android :background= "#00000000" />  Note : #00000000 specifies 'transparent' background. Step 2: Add a vertical linear layout for the menu. Inside that, add nested linear layouts for horizontal rows. <LinearLayout android :layout_width= "wrap_content" android :layout_height= "wrap_content...

How to add buttons and its functionality dynamically using HTML,MySQL and PHP?

There are times when we wish to add button dynamically in a webpage based on the entries in the database. If that is true in your case, please read on. (This guide assumes you have the basic knowledge of HTML, PHP and MySQL.) Following are the steps one will need to apply to create buttons dynamically: 1. Use PHP to connect to the database. <?php  $db = mysqli_connect('localhost','root','','media') //root is the username and no password.  or die('Error connecting to MySQL server.'); ?> Here, 'media' is the database name and it is running on WAMP. 2. Use a while loop to fetch contents from the database.     For each entry add a Button.   <form method="POST">  <?php $query = "SELECT * FROM post"; mysqli_query($db, $query) or die('Error querying database.'); $result = mysqli_query($db, $query); while ($row = mysqli_fetch_array($result)) { $varid=$row['postID...

How to access Wamp (Apache) server from mobile?

WAMP is by default configured to permit access to only the machine on which it is running. So if you try to access it from your mobile or any other device on the network it will give you the following error : “Forbidden You don't have permission to access /phpmyadmin/ on this server.”     To solve this you need to grant permission. For that follow the following steps: 1. Click on the WAMP icon. 2. Click on Apache. 3. Open httpd-vhosts.conf 4. Change 'Require local' to 'Require all granted'. 5. Restart your server. Remember, when the server and the client are not the same device, you cannot access via localhost. You need the IP address of the device. For that follow the following steps: 1. Open Command Prompt. 2. Type ipconfig. 3. Read the IPv4 address under the Wireless LAN adapter Wi-Fi. 4. Use this address to access the files from the mobile browser. (Make sure you are connected to the same wireless network.) Example: 192.168.1.5/temp/index....