Prerequisite
If you not understand this lecture Shared Preference in android studio.You should also read my previous lectures Popup Menu in android studio and Contextual Action mode in android studio . After reading these lecture you will also able to create Shared preference of your app.
Overview
Android provides many ways of storing data of an application. One of this way is called Shared Preferences. Shared Preferences allow you to save and retrieve data in the form of key value pair.Shared preference is API from android SDK to store and retrieve application preference.Shared preference store date persistently even user close the application or turn off the device But date saved.
Introduction
In this lecture well we describe how can create Shared Preference in android studio.And also describe what Shared preference in android.why we can use it.After Reading this lecture you will understand Shared preference in android And i hope you will create Shared preference of your application.
Description of Shared preference in android
Basically shared preference in android are used to save the state of an activity .In this lecture we describe what are the mechanism is used to save information in android.There is lot of mechanism is available to store information and data in android.You can use share preference API to store date and you can saves date into file and you can save date in sq-lite Database and you can save data remote server.So we create a simple application that demonstrate how can saved information using shared preference API.So we create a new project in android studio.Every project contain two file first is java class file and second is layout XML file.So open a layout .XML file and add a radio group inside the radio group you will add a radio button.After that add seek-bar and also define id of seek bar.In this example we are going to create a simple UI that includes only (Edit text) with Different attributes.And paste the following code into layout .XML file:
XML Layout
First of you will open a XML file of layout and set Linear Layout and add Edit text
Different property that are used in layout.xml file explain here
- warp_content warp_content means height and width similar to the text that are entered.
- Match_parent means height and width similar to parent.
- Radio group Radio button is used to create multipal-exclusion scope of radio button.
- Radio button Radio button allow to user to choice one option at a same time to set predefined options
- Button when button can be pressed, or clicked, by the user to perform an action
- Seek-bar Seek-bar is similarly to progress bar but provides facility to user it has a draggable slider that will allow the user to change the display control.
- Edit text The Edit Text control allows a user to enter text into an application
Code that are write in Layout. XML file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity" android:orientation="vertical" android:background="#000000" > <EditText android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Enter a message" android:textAppearance="?android:textAppearanceLarge" android:textColor="#FFFFFF" /> <EditText android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/message" android:background="#FFFFFF" android:textColor="#000000" android:gravity="top" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:textAppearance="?android:textAppearanceLarge" android:textColor="#FFFFFF" /> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:id="@+id/seek_bar" /> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Adjust font color" android:textAppearance="?android:textAppearanceLarge" android:textColor="#FFFFFF" /> <RadioGroup android:layout_width="match_parent" android:layout_height="wrap_content" android:background="#FFFFFF" android:layout_marginBottom="10dp" > <RadioButton android:id="@+id/id_red_color" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Red" android:onClick="changeColor" /> <RadioButton android:id="@+id/id_blue_color" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Blue" android:onClick="changeColor" /> <RadioButton android:id="@+id/id_green_color" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Green" android:onClick="changeColor" /> </RadioGroup> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save setting" android:layout_gravity="center_horizontal" android:onClick="saveSetting" android:background="#FFFFFF" android:textColor="#000000" android:layout_marginBottom="20dp" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="clear setting" android:layout_gravity="center_horizontal" android:onClick="clearSetting" android:background="#FFFFFF" android:textColor="#000000" android:layout_marginBottom="20dp" /> </LinearLayout>
Now you may open the Graphical layout editor to preview the User Interface you created of Shared preference in android.
Image may be NSFW.
Clik here to view.
Code that are write MainActivity. java class file.
So open a Main.java.class file.and create a object of Edit text. After that create other object of seek-bar and also initialize these two objects.In a seek-bar, there call back method is used.
- onProgressChanged
- onStartTrackingTouch
- onStopTrackingTouch
If the progress bar change then onProgressChanged method invoke.At beginning of seekbar onStartTrackingTouch method invoke.if user finished the seek-bar then onStopTrackingTouch method is invoke. After completing this step we define a on-click method in a Radio buttons when user select a Radio button option change the state of text.For change state of text we will use changeColor method inside the method we use a switch case statement and get the id that are define layout.XML file . In a switch case we will used three alternative. if user select first option then first condition or case will execute and change the color that are define if user select second option then second condition or case will execute and change the color that are define .if user select third option then third condition or case will execute and change the color that are define.
package com.example.bmw.shareraference; import android.content.SharedPreferences; import android.graphics.Color; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.util.TypedValue; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.SeekBar; import android.widget.Toast; public class MainActivity extends ActionBarActivity { EditText Message; SeekBar seekBar; float font_size; String font_color; String text_info; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Message=(EditText)findViewById(R.id.message); seekBar=(SeekBar)findViewById(R.id.seek_bar); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences( "MyPreferences", MainActivity.this.MODE_PRIVATE); // SharedPreferences sharedPreferences= MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), // MODE_PRIVATE); text_info = sharedPreferences.getString("Message","fffffffff"); Message.setText(text_info); font_size=sharedPreferences.getFloat("fontSize",25); font_color=sharedPreferences.getString("Color", "#03FF20"); Message.setTextSize( font_size); if(font_size==25) { seekBar.setProgress(0); } else{ seekBar.setProgress((int)font_size); } if (font_color.equals("Green")) { Message.setTextColor(Color.parseColor("#03FF20")); } else if (font_color.equals("Blue")){ Message.setTextColor(Color.parseColor("#03FF20")); } else if (font_color.equals("Red")){ Message.setTextColor(Color.parseColor("#FC0116")); } seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { Message.setTextSize(TypedValue.COMPLEX_UNIT_DIP,progress); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { font_size=Message.getTextSize(); } }); } public void changeColor(View View){ switch (View.getId()){ case R.id.id_red_color: Message.setTextColor(Color.parseColor("#FC0116")); font_color="Red"; break; case R.id.id_blue_color: Message.setTextColor(Color.parseColor("#F7FE2E")); font_color="Blue"; break; case R.id.id_green_color: Message.setTextColor(Color.parseColor("#03FF20")); font_color="Green"; break; } } public void saveSetting(View view){ Toast.makeText(MainActivity.this,"toast it",Toast.LENGTH_SHORT).show(); // SharedPreferences sharedPreferences= MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), // MODE_PRIVATE); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences( "MyPreferences", MainActivity.this.MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); editor.putFloat("fontSize",font_size); editor.putString("Color",font_color); editor.putString("Message",Message.getText().toString()); editor.commit(); } public void clearSetting(View view){ // SharedPreferences sharedPreferences= MainActivity.this.getSharedPreferences(getString(R.string.PREF_FILE), // MODE_PRIVATE); SharedPreferences sharedPreferences = MainActivity.this.getSharedPreferences( "MyPreferences", MainActivity.this.MODE_PRIVATE); SharedPreferences.Editor editor=sharedPreferences.edit(); editor.clear(); editor.commit(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
Run the Application
Image may be NSFW.
Clik here to view.
Thank you for reading this lecture Hope you got the idea.
The post Shared Preference in android studio appeared first on The Master World.