SlideShare a Scribd company logo
1 of 3
SharedPrefs.
Step1. Create a newAndroidProject.
Step2. Add the followingcode toyouractivityxml file.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/high_score_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/highscore_string"
android:textSize="24sp" />
<TextView
android:id="@+id/high_score_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@id/high_score_label"
android:layout_toRightOf="@id/high_score_label"
android:textSize="24sp" />
<TextView
android:id="@+id/game_score_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:textSize="50sp" />
<Button
android:id="@+id/reset_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="bottom"
android:padding="20dp"
android:text="@string/reset_string" >
</Button>
<Button
android:id="@+id/play_button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/reset_button"
android:padding="20dp"
android:text="@string/play_string" >
</Button>
</RelativeLayout>
Step3. Add the followingcode intoyour“values.xml file
<stringname="play_string">Play</string>
<string name="highscore_string">&quot;HighScore:&quot;</string>
<string name="reset_string">Reset</string>
Step4. Initialize viewresourcesand xml,addthiscode to On create function
final SharedPreferences prefs = getPreferences(MODE_PRIVATE);
setContentView(R.layout.main);
// High Score
final TextView highScore = (TextView) findViewById(R.id.high_score_text);
highScore.setText(String.valueOf(prefs.getInt(HIGH_SCORE, 0)));
//Game Score
final TextView gameScore = (TextView) findViewById(R.id.game_score_text);
gameScore.setText(String.valueOf("0"));
Step5. Add the Playbuttonlisteneragaininthe oncreate function
// Play Button
final Button playButton = (Button) findViewById(R.id.play_button);
playButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Random r = new Random();
int val = r.nextInt(1000);
gameScore.setText(String.valueOf(val));
// Get Stored High Score
if (val > prefs.getInt(HIGH_SCORE, 0)) {
// Get and edit high score
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HIGH_SCORE, val);
editor.commit();
highScore.setText(String.valueOf(val));
}
}
});
Step6. Add Resetbuttoncode againon create function
// Play Button
// Reset Button
final Button resetButton = (Button) findViewById(R.id.reset_button);
resetButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Set high score to 0
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(HIGH_SCORE, 0);
editor.commit();
highScore.setText(String.valueOf("0"));
gameScore.setText(String.valueOf("0"));
}
});
Step7. Done.

More Related Content

Similar to 1. shared pref

4.preference management
4.preference management 4.preference management
4.preference management maamir farooq
 
3. file external memory
3. file external memory3. file external memory
3. file external memorymaamir farooq
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design LibraryTaeho Kim
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgetsPrajyot Mainkar
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectJoemarie Amparo
 
android level 3
android level 3android level 3
android level 3DevMix
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談awonwon
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Joemarie Amparo
 
2. file internal memory
2. file internal memory2. file internal memory
2. file internal memorymaamir farooq
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in androidInnovationM
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and ContainerOum Saokosal
 
Android Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetAndroid Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetPrajyot Mainkar
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?Brenda Cook
 
android layouts
android layoutsandroid layouts
android layoutsDeepa Rani
 
Basics and different xml files used in android
Basics and different xml files used in androidBasics and different xml files used in android
Basics and different xml files used in androidMahmudul Hasan
 
Android Workshop
Android WorkshopAndroid Workshop
Android WorkshopJunda Ong
 

Similar to 1. shared pref (20)

4.preference management
4.preference management 4.preference management
4.preference management
 
3. file external memory
3. file external memory3. file external memory
3. file external memory
 
Support Design Library
Support Design LibrarySupport Design Library
Support Design Library
 
Android Tutorials : Basic widgets
Android Tutorials : Basic widgetsAndroid Tutorials : Basic widgets
Android Tutorials : Basic widgets
 
Android Development Made Easy - With Sample Project
Android Development Made Easy - With Sample ProjectAndroid Development Made Easy - With Sample Project
Android Development Made Easy - With Sample Project
 
Layouts in android
Layouts in androidLayouts in android
Layouts in android
 
android level 3
android level 3android level 3
android level 3
 
Data binding 入門淺談
Data binding 入門淺談Data binding 入門淺談
Data binding 入門淺談
 
Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1Android Development for Beginners with Sample Project - Day 1
Android Development for Beginners with Sample Project - Day 1
 
2. file internal memory
2. file internal memory2. file internal memory
2. file internal memory
 
How to use data binding in android
How to use data binding in androidHow to use data binding in android
How to use data binding in android
 
06. Android Basic Widget and Container
06. Android Basic Widget and Container06. Android Basic Widget and Container
06. Android Basic Widget and Container
 
Ap quiz app
Ap quiz appAp quiz app
Ap quiz app
 
Android Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection WidgetAndroid Tutorials - Powering with Selection Widget
Android Tutorials - Powering with Selection Widget
 
06 UI Layout
06 UI Layout06 UI Layout
06 UI Layout
 
Fragments: Why, How, What For?
Fragments: Why, How, What For?Fragments: Why, How, What For?
Fragments: Why, How, What For?
 
Chapter 5 - Layouts
Chapter 5 - LayoutsChapter 5 - Layouts
Chapter 5 - Layouts
 
android layouts
android layoutsandroid layouts
android layouts
 
Basics and different xml files used in android
Basics and different xml files used in androidBasics and different xml files used in android
Basics and different xml files used in android
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 

More from maamir farooq (20)

Ooad lab1
Ooad lab1Ooad lab1
Ooad lab1
 
Lesson 03
Lesson 03Lesson 03
Lesson 03
 
Lesson 02
Lesson 02Lesson 02
Lesson 02
 
Php client libray
Php client librayPhp client libray
Php client libray
 
Swiftmailer
SwiftmailerSwiftmailer
Swiftmailer
 
Lect15
Lect15Lect15
Lect15
 
Lec 7
Lec 7Lec 7
Lec 7
 
Lec 6
Lec 6Lec 6
Lec 6
 
Lec 5
Lec 5Lec 5
Lec 5
 
J query 1.7 cheat sheet
J query 1.7 cheat sheetJ query 1.7 cheat sheet
J query 1.7 cheat sheet
 
Assignment
AssignmentAssignment
Assignment
 
Java script summary
Java script summaryJava script summary
Java script summary
 
Lec 3
Lec 3Lec 3
Lec 3
 
Lec 2
Lec 2Lec 2
Lec 2
 
Lec 1
Lec 1Lec 1
Lec 1
 
Css summary
Css summaryCss summary
Css summary
 
Manual of image processing lab
Manual of image processing labManual of image processing lab
Manual of image processing lab
 
Session management
Session managementSession management
Session management
 
Data management
Data managementData management
Data management
 
Content provider
Content providerContent provider
Content provider
 

Recently uploaded

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxmarlenawright1
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxRamakrishna Reddy Bijjam
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...Amil baba
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfNirmal Dwivedi
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSAnaAcapella
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use CasesTechSoup
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 

Recently uploaded (20)

REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptxHMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
HMCS Vancouver Pre-Deployment Brief - May 2024 (Web Version).pptx
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
NO1 Top Black Magic Specialist In Lahore Black magic In Pakistan Kala Ilam Ex...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 

1. shared pref

  • 1. SharedPrefs. Step1. Create a newAndroidProject. Step2. Add the followingcode toyouractivityxml file. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" > <TextView android:id="@+id/high_score_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/highscore_string" android:textSize="24sp" /> <TextView android:id="@+id/high_score_text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignTop="@id/high_score_label" android:layout_toRightOf="@id/high_score_label" android:textSize="24sp" /> <TextView android:id="@+id/game_score_text" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:gravity="center" android:textSize="50sp" /> <Button android:id="@+id/reset_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_gravity="bottom" android:padding="20dp" android:text="@string/reset_string" > </Button> <Button android:id="@+id/play_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@id/reset_button" android:padding="20dp" android:text="@string/play_string" > </Button> </RelativeLayout> Step3. Add the followingcode intoyour“values.xml file
  • 2. <stringname="play_string">Play</string> <string name="highscore_string">&quot;HighScore:&quot;</string> <string name="reset_string">Reset</string> Step4. Initialize viewresourcesand xml,addthiscode to On create function final SharedPreferences prefs = getPreferences(MODE_PRIVATE); setContentView(R.layout.main); // High Score final TextView highScore = (TextView) findViewById(R.id.high_score_text); highScore.setText(String.valueOf(prefs.getInt(HIGH_SCORE, 0))); //Game Score final TextView gameScore = (TextView) findViewById(R.id.game_score_text); gameScore.setText(String.valueOf("0")); Step5. Add the Playbuttonlisteneragaininthe oncreate function // Play Button final Button playButton = (Button) findViewById(R.id.play_button); playButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Random r = new Random(); int val = r.nextInt(1000); gameScore.setText(String.valueOf(val)); // Get Stored High Score if (val > prefs.getInt(HIGH_SCORE, 0)) { // Get and edit high score SharedPreferences.Editor editor = prefs.edit(); editor.putInt(HIGH_SCORE, val); editor.commit(); highScore.setText(String.valueOf(val)); } } }); Step6. Add Resetbuttoncode againon create function // Play Button // Reset Button final Button resetButton = (Button) findViewById(R.id.reset_button);
  • 3. resetButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Set high score to 0 SharedPreferences.Editor editor = prefs.edit(); editor.putInt(HIGH_SCORE, 0); editor.commit(); highScore.setText(String.valueOf("0")); gameScore.setText(String.valueOf("0")); } }); Step7. Done.