Ads

Android Tutorial Day 4

Learning Objective: Let’s start exploring more fundamentals of Android. How to store some user logged-in value to track the user and its profile. We can use  Shared Preferences.

How to Create  Shared Preferences in Android Programming.

Sample Code to Write Data into Android using Shared Preferences.

FirstFragment Java Code

package com.at.mytestapplication.myapplication;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.at.mytestapplication.myapplication.databinding.FragmentFirstBinding;

public class FirstFragment extends Fragment {

    private FragmentFirstBinding binding;


    public static final String MyPREFERENCES = "MyPrefs" ;


    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        binding = FragmentFirstBinding.inflate(inflater, container, false);
        return binding.getRoot();

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        binding.buttonFirst.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences prefs = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                String mobile = prefs.getString("phoneKey", "-1");

                if(mobile.equals("-1"))
                {
                    Log.e("cs","New User is trying to access");

                    //this is for new users
                    NavHostFragment.findNavController(FirstFragment.this)
                            .navigate(R.id.action_FirstFragment_to_SecondFragment);


                }
                else
                {
                    Log.e("cs","Previously Logged in User");

                    //this is for logged in users
                    NavHostFragment.findNavController(FirstFragment.this)
                            .navigate(R.id.action_FirstFragment_to_SecondFragment);
                }




            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

SecondFragment Java Code

package com.at.mytestapplication.myapplication;

import static android.content.Context.TELEPHONY_SERVICE;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.navigation.fragment.NavHostFragment;

import com.at.mytestapplication.myapplication.databinding.FragmentSecondBinding;

public class SecondFragment extends Fragment {

    private FragmentSecondBinding binding;
    public static final String MyPREFERENCES = "MyPrefs" ;


    @Override
    public View onCreateView(
            LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState
    ) {

        View view = inflater.inflate(R.layout.fragment_second,
                container, false);

        Button btnlogin = (Button) view.findViewById(R.id.btnlogin);
        Button btnlogout = (Button) view.findViewById(R.id.btnlogout);

        EditText etmobile = (EditText) view.findViewById(R.id.etmobile);


        btnlogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                SharedPreferences sharedpreferences = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);


                String mobile =  etmobile.getText().toString();

                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString("phoneKey", mobile);
                editor.commit();

                Toast.makeText(getContext(), "Login Done", Toast.LENGTH_SHORT).show();

            }
        });

        btnlogout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                //Logout
                SharedPreferences sharedpreferences = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                sharedpreferences.edit().remove("phoneKey").commit();

                Toast.makeText(getContext(), "Logout Done", Toast.LENGTH_SHORT).show();

            }
        });

        return view;

    }

    public void onViewCreated(@NonNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

}

SecondFragment Layout Code

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".SecondFragment">

    <EditText
        android:id="@+id/etmobile"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btnlogin"
        android:text="Login"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


    <Button
        android:id="@+id/btnlogout"
        android:text="Logout"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>


</LinearLayout>
Ads