Question

In: Computer Science

Exercise 8-2 (work with menus) Exercise 8-3 (work with preferences) android studio

Exercise 8-2 (work with menus) Exercise 8-3 (work with preferences) android studio

Solutions

Expert Solution

So, let's talk about the menus first:

Menus are basically used to give various options to the user. It comes in the right of toolbar.

Attributes:

id Used to give ids to the menus so as to conncect it with front end
title Used to give title to the menus i.e the text you see
icon Used to give icons to the menus. Like setting icon
showAsAction Tells that how this item should be visible on the app bar
visible Tells whether this item is visible or not
enable Tells whether this item is enabled or not. Like if it disable user can't do action on this
checkable Tells whether this item can contains checkable box or not

menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:id="@+id/profile"
        android:title="My Profile" />
    <item
        android:id="@+id/logout"
        android:title="Logout" />
</menu>

So this is how a xml file of a menu looks like.

This xml file will create a menu with 2 options i.e My Profile and Logout.

MainActivity.java

// This function is used to create or inflate menu 
@Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
 /*we are taking the default MenuInflator 
then we are calling the inflate function by passing the Resource file and the menu which 
we are getting from the function onCreateOptionsMenu.
*/
        return super.onCreateOptionsMenu(menu);
    }


// This function is used to select options in the menu
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
// we have to pass the menu item which we are getting through the function parameter
//then by passing it into the switch we can perform function according to out need

        switch (item.getItemId()) {
            case R.id.logout: {
               //logout code here
                break;
            }
            case R.id.profile: {
                   //my profile code here
            }
        }

        return super.onOptionsItemSelected(item);
    }

Now let's talk about the prefrences.

Prefrences or Shared Prefrences are used to store data into key-value pairs.

These are used to store the preffered state of the application selected by the user like dark mode or light mode,

like to store whether the user is logged in or not, passwords and similiar type of data.

To store the prefrences you first have to call a function which is call by using current context i.e current activity.

function is getSharedPreferences

e.g this.getSharedPreferences or in case of fragment you will be usign context.

Now, this function will take 2 parameters i.e name(String) of prefrence and mode(Int) in which you want to call the method.

e.g this.getSharedPreferences("isLoggedIn",Context.MODE_PRIVATE)

Complete Code to store password of user:

//To open an editor for sharedprefrences which will store the values
SharedPreferences.Editor editor = getSharedPreferences("PasswordStore", Context.MODE_PRIVATE).edit();
//you can use a global string variable instead of "PasswordStore"

String pass = "12345"; //you can also take this from user using editText. 
editor.putString("Password", pass);//this will create a key-value pair with key = Password and value = 12345
editor.apply();//this will apply changes


/*Note : Instead of putString you can use putInt, putFloat, putStringSet(array of strings), putBoolean
putLong */
/* Then for editor we have clear() method to clear the editor*/

//Now if you want to fetch this password you can do it by:



SharedPreferences passwordPref = getSharedPreferences("PasswordStore", Context.MODE_PRIVATE);
//Note: You have to pass the exact name of preferences which you used while storing it

String password = passwordPref.getString("Password",null);
//Note : You have to pass the exact name of key which you used while storing it.
/* First parameter is key of preferences and other is default value i.e if you want to fetch the value
of that preference which you did not store it will give you the default value.

/*Note : Instead of getString you can use getInt, getFloat, getStringSet(array of strings), getBoolean
getLong  according to the value you stored*/
        

So, this was the explanation for the menus and preferences.
I hope I am able to make you understand, if yes then do give it a thumbs up .

It really helps :)


Related Solutions

Android Studio Code: Provide a working android studio code i.e java and xml code for the...
Android Studio Code: Provide a working android studio code i.e java and xml code for the activity below: Develop an application that is capable to turn pages back and forth. Detailed Instructions: For the main activity, create a layout that represents a fictitious title and author. The activity should include a clickable button on the bottom right that allows you to go forward to the next activity. The next activity will simply be an image above simple text that can...
the code base you will be working with involves an Android application. (Android Studio) application name...
the code base you will be working with involves an Android application. (Android Studio) application name " SharingApp" In the application’s current state: A user of the app is able to create and edit a profile with a unique username and an email address. A user of the app is able to login and logout. An owner is able to record the items they own and wish to share. A bidder is able to place bids on items they wish...
How to get the vote count to display in another activity? This is for android studio...
How to get the vote count to display in another activity? This is for android studio with Java codes. private int yesVoteCount = 0;     private int noVoteCount = 0;     private int resetVotes = 0;     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);         // Use res ID to retrieve inflated objects and assign to variables         mYesButton = findViewById(R.id.yes_button);         mNoButton = findViewById(R.id.no_button);         mResetButton = findViewById(R.id.reset_button);         mSurveyQuestion = findViewById(R.id.survey_question);         mYesCount =...
IN ANDROID STUDIO, you will create a mortgage calculator appthat allows the user to enter...
IN ANDROID STUDIO, you will create a mortgage calculator app that allows the user to enter a purchase price, down-payment amount, and an interest rate.Based on these values, the app should calculate the loan amount (purchase price minus down payment) and display the monthly payment for 10, 20, and 30-year loans.Allow the user to select a custom loan duration (in years) by using a SeekBar and display the monthly payment for that custom loan duration.Assignment deliverables (all in a ZIP...
Android Studio. Java. Please create an application that -> An activity that allows user to enter...
Android Studio. Java. Please create an application that -> An activity that allows user to enter name, gender, date of birth, state of residence (selected from a pre-defined list: CA, AZ, NV, OR), email address and favorite website. This activity has a button "Show Data" that displays detail entered
Hi! I need it in android studio and in java Design a game app “BouncingBall ”...
Hi! I need it in android studio and in java Design a game app “BouncingBall ” in which the user’s goal is to prevent a bouncing ball from falling off the bottom of the screen. When the user presses the start button, a ball bounces off the top, left and right sides (the “walls”) of the screen. A horizontal bar on the bottom of the screen serves as a paddle to prevent the ball from hitting the bottom of the...
Hi! I need it in android studio and in java Design a game app “BouncingBall ”...
Hi! I need it in android studio and in java Design a game app “BouncingBall ” in which the user’s goal is to prevent a bouncing ball from falling off the bottom of the screen. When the user presses the start button, a ball bounces off the top, left and right sides (the “walls”) of the screen. A horizontal bar on the bottom of the screen serves as a paddle to prevent the ball from hitting the bottom of the...
Required information Exercise 8-33 & 8-34 (Static) (LO 8-2, 3) [The following information applies to the...
Required information Exercise 8-33 & 8-34 (Static) (LO 8-2, 3) [The following information applies to the questions displayed below.] The Matsui Lubricants plant uses the weighted-average method to account for its work-in-process inventories. The accounting records show the following information for a particular day. Beginning WIP inventory Direct materials $ 976 Conversion costs 272 Current period costs Direct materials 11,440 Conversion costs 6,644 Quantity information is obtained from the manufacturing records and includes the following. Beginning inventory 600 units (60%...
Create a mobile application using Android studio, for cinema tickets reservation. The application will be used...
Create a mobile application using Android studio, for cinema tickets reservation. The application will be used by the customers to book cinema tickets. Only users of 15 years old and above are allowed to book cinema tickets for a particular film. The user can book more than one ticket where ticket prices vary between 20 and 50 AED. Your app contains tree Activities. The first activity is a launching activity containing a logo and a button start. When the user...
android studio Begin a new app and create a Java class for products with data: productName,...
android studio Begin a new app and create a Java class for products with data: productName, productCode and price and use a file of objects to store product data and read back and display on screen. Do this by creating a simple form using EditTexts, buttons or ActionBar items and display output using an Alert.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT