In almost all our applications we are required to store application related user preferences or settings like favorites, language settings etc. Android provides a lot of options for storing data but the preference related settings can be easily stored and maintained using SharedPreferences class.
In this Android example, we will see how to store multiple or list of values in SharedPreferences under same key and retrieve values from it. To explain this concept, we display a list of items with favorites icon. When the list item is long pressed, the item is added to the favorites. When we say the item is added to the favorites, we actually store the list of items in shared preferences mapped to a key.
Android SharedPreferences class does not provide a way to store a List or ArrayList or any collection. In order to store a list (even array, set or any collection) under a key, we convert the list (or collection) to JSON format using Gson and store it as string . While retrieving we convert the JSON string back to list and return it.
In this Android SharedPreferences tutorial we will be doing the following,
- Create a separate SharedPreference utility class with methods to save, add, remove and get favorites from SharedPreferences.
- Display list of products in ListView in list fragment. When a list item is long pressed, it is added to favorites list stored in SharedPreferences.
- Add an Action bar favorite menu item icon to display all the stored favorite items in a ListView. FavoriteListFragment is used to display this ListView. When an item is long pressed in this ListView it is removed from favorites i.e.) removed from SharedPreferences.
Android Project
Create a new Android project and name it as SharedPreferencesFavorites .
Resources
colors.xml
Create a new file res/values/colors.xml and copy paste the following content.
|
1
2
3
4
5
6
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
resources
>
<
color
name
=
"transparent"
>
#00000000</color>
<
color
name
=
"product_list_item_bg"
>
#ffffff</color>
<
color
name
=
"view_divider_color"
>
#BABABA</color>
<
/
resources
>
|
strings.xml
Open res/values/strings.xml and edit to have the content as shown below.
|
1
2
3
4
5
6
7
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
resources
>
<
string
name
=
"app_name"
>
SharedPreferencesFavorites
<
/
string
>
<
string
name
=
"action_settings"
>
Settings
<
/
string
>
<
string
name
=
"hello_world"
>
Hello
world
!
<
/
string
>
<
string
name
=
"favorites"
>
Favorites
<
/
string
>
<
/
resources
>
|
strings_fav_msg.xml
Create a new file res/values/strings_fav_msg.xml and copy paste the following content. This file defines string messages related to favourites.
|
1
2
3
4
5
6
7
8
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
resources
>
<
string
name
=
"add_favr"
>
Added
to
Favorites
<
/
string
>
<
string
name
=
"remove_favr"
>
Removed
from
Favorites
<
/
string
>
<
string
name
=
"no_favorites_items"
>
No
Favorites
<
/
string
>
<
string
name
=
"no_favorites_msg"
>
Long
press
on
item
to
add
to
favorites
.
<
/
string
>
<
string
name
=
"favorites_remove_msg"
>
Long
press
on
item
to
remove
from
favorites
.
<
/
string
>
<
/
resources
>
|
Action Bar Menu Item (main.xml)
Open res/menu/main.xml and edit to have the content as shown below. When this menu item is clicked, it displays FavoriteListFragment.
|
1
2
3
4
5
6
7
8
|
<
menu
xmlns
:
android
=
"http://schemas.android.com/apk/res/android"
>
<
item
android
:
id
=
"@+id/menu_favorites"
android
:
icon
=
"@drawable/heart_red"
android
:
orderInCategory
=
"200"
android
:
showAsAction
=
"ifRoom|withText"
android
:
title
=
"@string/favorites"
/
>
<
/
menu
>
|
Layout Files
activity_main.xml
This layout file defines Framelayout which holds all fragments. Open res/layout/activity_main.xml and edit to have the content as shown below.
|
1
2
3
4
5
6
7
8
9
10
11
12
|
<
RelativeLayout
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"
tools
:
context
=
".MainActivity"
>
<
FrameLayout
android
:
id
=
"@+id/content_frame"
android
:
layout_width
=
"match_parent"
android
:
layout_height
=
"match_parent"
/
>
<
/
RelativeLayout
>
|
fragment_product_list.xml
This layout file defines a ListView which is used by ProductListFragment to display list of products.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
<
RelativeLayout
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
:
background
=
"#EDEDED"
>
<
ListView
android
:
id
=
"@+id/list_product"
android
:
layout_width
=
"fill_parent"
android
:
layout_height
=
"wrap_content"
android
:
divider
=
"@color/transparent"
android
:
dividerHeight
=
"10dp"
android
:
drawSelectorOnTop
=
"true"
android
:
footerDividersEnabled
=
"false"
android
:
padding
=
"10dp"
android
:
scrollbarStyle
=
"outsideOverlay"
>
<
/
ListView
>
<
/
RelativeLayout
>
|
product_list_item.xml
This file defines custom layout for ListView item which is used by ProductListAdapter .
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
<?
xml
version
=
"1.0"
encoding
=
"utf-8"
?>
<
RelativeLayout
xmlns
:
android
=
"http://schemas.android.com/apk/res/android"
android
:
layout_width
=
"fill_parent"
android
:
layout_height
=
"wrap_content"
android
:
background
=
"@color/product_list_item_bg"
android
:
descendantFocusability
=
"blocksDescendants"
>
<
RelativeLayout
android
:
id
=
"@+id/pdt_layout_item"
android
:
layout_width
=
"fill_parent"
android
:
layout_height
=
"wrap_content"
>
<
TextView
android
:
id
=
"@+id/txt_pdt_name"
android
:
layout_width
=
"wrap_content"
android
:
layout_height
=
"wrap_content"
android
:
padding
=
"6dp"
/
>
<
TextView
android
:
id
=
"@+id/txt_pdt_price"
android
:
layout_width
=
"wrap_content"
android
:
layout_height
=
"wrap_content"
android
:
layout_below
=
"@+id/txt_pdt_name"
android
:
padding
=
"6dp"
/
>
<
TextView
android
:
id
=
"@+id/txt_pdt_desc"
android
:
layout_width
=
"wrap_content"
android
:
layout_height
=
"wrap_content"
android
:
layout_below
=
"@+id/txt_pdt_price"
android
:
padding
=
"6dp"
/
>
<
ImageView
android
:
id
=
"@+id/imgbtn_favorite"
android
:
layout_width
=
"wrap_content"
android
:
layout_height
=
"wrap_content"
android
:
layout_alignBottom
=
"@+id/txt_pdt_desc"
android
:
layout_alignParentRight
=
"true"
android
:
layout_marginRight
=
"3dp"
android
:
background
=
"@null"
android
:
contentDescription
=
"@string/favorites"
/
>
<
/
RelativeLayout
>
<
View
android
:
layout_width
=
"match_parent"
android
:
layout_height
=
"1dp"
android
:
layout_below
=
"@+id/pdt_layout_item"
android
:
background
=
"@color/view_divider_color"
/
>
<
/
RelativeLayout
>
|
Source files
Product
In src folder, create a new class Product in the package com.androidopentutorials.spfavorites.beans . This class represents a Product displayed in the ListView.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
package
com
.
androidopentutorials
.
spfavorites
.
beans
;
public
class
Product
{
private
int
id
;
private
String
name
;
private
String
description
;
private
double
price
;
public
Product
(
)
{
super
(
)
;
}
public
Product
(
int
id
,
String
name
,
String
description
,
double
price
)
{
super
(
)
;
this
.
id
=
id
;
this
.
name
=
name
;
this
.
description
=
description
;
this
.
price
=
price
;
}
public
int
getId
(
)
{
return
id
;
}
public
void
setId
(
int
id
)
{
this
.
id
=
id
;
}
public
String
getName
(
)
{
return
name
;
}
public
void
setName
(
String
name
)
{
this
.
name
=
name
;
}
public
String
getDescription
(
)
{
return
description
;
}
public
void
setDescription
(
String
description
)
{
this
.
description
=
description
;
}
public
double
getPrice
(
)
{
return
price
;
}
public
void
setPrice
(
double
price
)
{
this
.
price
=
price
;
}
@
Override
public
int
hashCode
(
)
{
final
int
prime
=
31
;
int
result
=
1
;
result
=
prime *
result
+
id
;
return
result
;
}
@
Override
public
boolean
equals
(
Object
obj
)
{
if
(
this
==
obj
)
return
true
;
if
(
obj
==
null
)
return
false
;
if
(
getClass
(
)
!=
obj
.
getClass
(
)
)
return
false
;
Product
other
=
(
Product
)
obj
;
if
(
id
!=
other
.
id
)
return
false
;
return
true
;
}
@
Override
public
String
toString
(
)
{
return
"Product [id="
+
id
+
", name="
+
name
+
", description="
+
description
+
", price="
+
price
+
"]"
;
}
}
|
SharedPreference class
Create a new class SharedPreference in the package com.androidopentutorials.spfavorites.utils . This class defines methods to save, add, remove and get favorites from SharedPreferences.
Here we use Gson to convert List to JSON string in saveFavorites method and back again to List in getFavorites method.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
package
com
.
androidopentutorials
.
spfavorites
.
utils
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
Arrays
;
import
java
.
util
.
List
;
import
android
.
content
.
Context
;
import
android
.
content
.
SharedPreferences
;
import
android
.
content
.
SharedPreferences
.
Editor
;
import
com
.
androidopentutorials
.
spfavorites
.
beans
.
Product
;
import
com
.
google
.
gson
.
Gson
;
public
class
SharedPreference
{
public
static
final
String
PREFS_NAME
=
"PRODUCT_APP"
;
public
static
final
String
FAVORITES
=
"Product_Favorite"
;
public
SharedPreference
(
)
{
super
(
)
;
}
// This four methods are used for maintaining favorites.
public
void
saveFavorites
(
Context
context
,
List
<
Product
>
favorites
)
{
SharedPreferences
settings
;
Editor
editor
;
settings
=
context
.
getSharedPreferences
(
PREFS_NAME
,
Context
.
MODE_PRIVATE
)
;
editor
=
settings
.
edit
(
)
;
Gson
gson
=
new
Gson
(
)
;
String
jsonFavorites
=
gson
.
toJson
(
favorites
)
;
editor
.
putString
(
FAVORITES
,
jsonFavorites
)
;
editor
.
commit
(
)
;
}
public
void
addFavorite
(
Context
context
,
Product
product
)
{
List
<
Product
>
favorites
=
getFavorites
(
context
)
;
if
(
favorites
==
null
)
favorites
=
new
ArrayList
<
Product
>
(
)
;
favorites
.
add
(
product
)
;
saveFavorites
(
context
,
favorites
)
;
}
public
void
removeFavorite
(
Context
context
,
Product
product
)
{
ArrayList
<
Product
>
favorites
=
getFavorites
(
context
)
;
if
(
favorites
!=
null
)
{
favorites
.
remove
(
product
)
;
saveFavorites
(
context
,
favorites
)
;
}
}
public
ArrayList
<
Product
>
getFavorites
(
Context
context
)
{
SharedPreferences
settings
;
List
<
Product
>
favorites
;
settings
=
context
.
getSharedPreferences
(
PREFS_NAME
,
Context
.
MODE_PRIVATE
)
;
if
(
settings
.
contains
(
FAVORITES
)
)
{
String
jsonFavorites
=
settings
.
getString
(
FAVORITES
,
null
)
;
Gson
gson
=
new
Gson
(
)
;
Product
[
]
favoriteItems
=
gson
.
fromJson
(
jsonFavorites
,
Product
[
]
.
class
)
;
favorites
=
Arrays
.
asList
(
favoriteItems
)
;
favorites
=
new
ArrayList
<
Product
>
(
favorites
)
;
}
else
return
null
;
return
(
ArrayList
<
Product
>
)
favorites
;
}
}
|
ProductListAdapter
In src folder, create a new class ProductListAdapter in the package com.androidopentutorials.spfavorites.adapter . This is the custom list adapter class which displays product name, description, price and favorite icon.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
|
package
com
.
androidopentutorials
.
spfavorites
.
adapter
;
import
java
.
util
.
List
;
import
android
.
app
.
Activity
;
import
android
.
content
.
Context
;
import
android
.
view
.
LayoutInflater
;
import
android
.
view
.
View
;
import
android
.
view
.
ViewGroup
;
import
android
.
widget
.
ArrayAdapter
;
import
android
.
widget
.
ImageView
;
import
android
.
widget
.
TextView
;
import
com
.
androidopentutorials
.
spfavorites
.
R
;
import
com
.
androidopentutorials
.
spfavorites
.
beans
.
Product
;
import
com
.
androidopentutorials
.
spfavorites
.
utils
.
SharedPreference
;
public
class
ProductListAdapter
extends
ArrayAdapter
<
Product
>
{
private
Context
context
;
List
<
Product
>
products
;
SharedPreference
sharedPreference
;
public
ProductListAdapter
(
Context
context
,
List
<
Product
>
products
)
{
super
(
context
,
R
.
layout
.
product_list_item
,
products
)
;
this
.
context
=
context
;
this
.
products
=
products
;
sharedPreference
=
new
SharedPreference
(
)
;
}
private
class
ViewHolder
{
TextView
productNameTxt
;
TextView
productDescTxt
;
TextView
productPriceTxt
;
ImageView
favoriteImg
;
}
@
Override
public
int
getCount
(
)
{
return
products
.
size
(
)
;
}
@
Override
public
Product
getItem
(
int
position
)
{
return
products
.
get
(
position
)
;
}
@
Override
public
long
getItemId
(
int
position
)
{
return
0
;
}
@
Override
public
View
getView
(
int
position
,
View
convertView
,
ViewGroup
parent
)
{
ViewHolder
holder
=
null
;
if
(
convertView
==
null
)
{
LayoutInflater
inflater
=
(
LayoutInflater
)
context
.
getSystemService
(
Activity
.
LAYOUT_INFLATER_SERVICE
)
;
convertView
=
inflater
.
inflate
(
R
.
layout
.
product_list_item
,
null
)
;
holder
=
new
ViewHolder
(
)
;
holder
.
productNameTxt
=
(
TextView
)
convertView
.
findViewById
(
R
.
id
.
txt_pdt_name
)
;
holder
.
productDescTxt
=
(
TextView
)
convertView
.
findViewById
(
R
.
id
.
txt_pdt_desc
)
;
holder
.
productPriceTxt
=
(
TextView
)
convertView
.
findViewById
(
R
.
id
.
txt_pdt_price
)
;
holder
.
favoriteImg
=
(
ImageView
)
convertView
.
findViewById
(
R
.
id
.
imgbtn_favorite
)
;
convertView
.
setTag
(
holder
)
;
}
else
{
holder
=
(
ViewHolder
)
convertView
.
getTag
(
)
;
}
Product
product
=
(
Product
)
getItem
(
position
)
;
holder
.
productNameTxt
.
setText
(
product
.
getName
(
)
)
;
holder
.
productDescTxt
.
setText
(
product
.
getDescription
(
)
)
;
holder
.
productPriceTxt
.
setText
(
product
.
getPrice
(
)
+
""
)
;
/*If a product exists in shared preferences then set heart_red drawable
* and set a tag*/
if
(
checkFavoriteItem
(
product
)
)
{
holder
.
favoriteImg
.
setImageResource
(
R
.
drawable
.
heart_red
)
;
holder
.
favoriteImg
.
setTag
(
"red"
)
;
}
else
{
holder
.
favoriteImg
.
setImageResource
(
R
.
drawable
.
heart_grey
)
;
holder
.
favoriteImg
.
setTag
(
"grey"
)
;
}
return
convertView
;
}
/*Checks whether a particular product exists in SharedPreferences*/
public
boolean
checkFavoriteItem
(
Product
checkProduct
)
{
boolean
check
=
false
;
List
<
Product
>
favorites
=
sharedPreference
.
getFavorites
(
context
)
;
if
(
favorites
!=
null
)
{
for
(
Product
product
:
favorites
)
{
if
(
product
.
equals
(
checkProduct
)
)
{
check
=
true
;
break
;
}
}
}
return
check
;
}
@
Override
public
void
add
(
Product
product
)
{
super
.
add
(
product
)
;
products
.
add
(
product
)
;
notifyDataSetChanged
(
)
;
}
@
Override
public
void
remove
(
Product
product
)
{
super
.
remove
(
product
)
;
products
.
remove
(
product
)
;
notifyDataSetChanged
(
)
;
}
}
|
ProductListFragment
In src folder, create a new class ProductListFragment in the package com.androidopentutorials.spfavorites.fragment .
- This class displays list of products.
- On item long click it adds that product in favorites by saving it in SharedPreferences. If the same item is long clicked again it is removed from favorites.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
|
package
com
.
androidopentutorials
.
spfavorites
.
fragment
;
import
java
.
util
.
ArrayList
;
import
java
.
util
.
List
;
import
android
.
app
.
Activity
;
import
android
.
os
.
Bundle
;
import
android
.
support
.
v4
.
app
.
Fragment
;
import
android
.
view
.
LayoutInflater
;
import
android
.
view
.
View
;
import
android
.
view
.
ViewGroup
;
import
android
.
widget
.
AdapterView
;
import
android
.
widget
.
AdapterView
.
OnItemClickListener
;
import
android
.
widget
.
AdapterView
.
OnItemLongClickListener
;
import
android
.
widget
.
ImageView
;
import
android
.
widget
.
ListView
;
import
android
.
widget
.
Toast
;
import
com
.
androidopentutorials
.
spfavorites
.
R
;
import
com
.
androidopentutorials
.
spfavorites
.
adapter
.
ProductListAdapter
;
import
com
.
androidopentutorials
.
spfavorites
.
beans
.
Product
;
import
com
.
androidopentutorials
.
spfavorites
.
utils
.
SharedPreference
;
public
class
ProductListFragment
extends
Fragment
implements
OnItemClickListener
,
OnItemLongClickListener
{
public
static
final
String
ARG_ITEM_ID
=
"product_list"
;
Activity
activity
;
ListView
productListView
;
List
<
Product
>
products
;
ProductListAdapter
productListAdapter
;
SharedPreference
sharedPreference
;
@
Override
public
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
)
;
activity
=
getActivity
(
)
;
sharedPreference
=
new
SharedPreference
(
)
;
}
@
Override
public
View
onCreateView
(
LayoutInflater
inflater
,
ViewGroup
container
,
Bundle
savedInstanceState
)
{
View
view
=
inflater
.
inflate
(
R
.
layout
.
fragment_product_list
,
container
,
false
)
;
findViewsById
(
view
)
;
setProducts
(
)
;
productListAdapter
=
new
ProductListAdapter
(
activity
,
products
)
;
productListView
.
setAdapter
(
productListAdapter
)
;
productListView
.
setOnItemClickListener
(
this
)
;
productListView
.
setOnItemLongClickListener
(
this
)
;
return
view
;
}
private
void
setProducts
(
)
{
Product
product1
=
new
Product
(
1
,
"Dell XPS"
,
"Dell XPS Laptop"
,
60000
)
;
Product
product2
=
new
Product
(
2
,
"HP Pavilion G6-2014TX"
,
"HP Pavilion G6-2014TX Laptop"
,
50000
)
;
Product
product3
=
new
Product
(
3
,
"ProBook HP 4540"
,
"ProBook HP 4540 Laptop"
,
45000
)
;
Product
product4
=
new
Product
(
4
,
"HP Envy 4-1025TX"
,
"HP Envy 4-1025TX Laptop"
,
46000
)
;
Product
product5
=
new
Product
(
5
,
"Dell Inspiron"
,
"Dell Inspiron Laptop"
,
48000
)
;
Product
product6
=
new
Product
(
6
,
"Dell Vostro"
,
"Dell Vostro Laptop"
,
50000
)
;
Product
product7
=
new
Product
(
7
,
"IdeaPad Z Series"
,
"Lenovo IdeaPad Z Series Laptop"
,
40000
)
;
Product
product8
=
new
Product
(
8
,
"ThinkPad X Series"
,
"Lenovo ThinkPad X Series Laptop"
,
38000
)
;
Product
product9
=
new
Product
(
9
,
"VAIO S Series"
,
"Sony VAIO S Series Laptop"
,
39000
)
;
Product
product10
=
new
Product
(
10
,
"Series 5"
,
"Samsung Series 5 Laptop"
,
50000
)
;
products
=
new
ArrayList
<
Product
>
(
)
;
products
.
add
(
product1
)
;
products
.
add
(
product2
)
;
products
.
add
(
product3
)
;
products
.
add
(
product4
)
;
products
.
add
(
product5
)
;
products
.
add
(
product6
)
;
products
.
add
(
product7
)
;
products
.
add
(
product8
)
;
products
.
add
(
product9
)
;
products
.
add
(
product10
)
;
}
private
void
findViewsById
(
View
view
)
{
productListView
=
(
ListView
)
view
.
findViewById
(
R
.
id
.
list_product
)
;
}
@
Override
public
void
onItemClick
(
AdapterView
<?
>
parent
,
View
view
,
int
position
,
long
id
)
{
Product
product
=
(
Product
)
parent
.
getItemAtPosition
(
position
)
;
Toast
.
makeText
(
activity
,
product
.
toString
(
)
,
Toast
.
LENGTH_LONG
)
.
show
(
)
;
}
@
Override
public
boolean
onItemLongClick
(
AdapterView
<?
>
arg0
,
View
view
,
int
position
,
long
arg3
)
{
ImageView
button
=
(
ImageView
)
view
.
findViewById
(
R
.
id
.
imgbtn_favorite
)
;
String
tag
=
button
.
getTag
(
)
.
toString
(
)
;
if
(
tag
.
equalsIgnoreCase
(
"grey"
)
)
{
sharedPreference
.
addFavorite
(
activity
,
products
.
get
(
position
)
)
;
Toast
.
makeText
(
activity
,
activity
.
getResources
(
)
.
getString
(
R
.
string
.
add_favr
)
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
button
.
setTag
(
"red"
)
;
button
.
setImageResource
(
R
.
drawable
.
heart_red
)
;
}
else
{
sharedPreference
.
removeFavorite
(
activity
,
products
.
get
(
position
)
)
;
button
.
setTag
(
"grey"
)
;
button
.
setImageResource
(
R
.
drawable
.
heart_grey
)
;
Toast
.
makeText
(
activity
,
activity
.
getResources
(
)
.
getString
(
R
.
string
.
remove_favr
)
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
return
true
;
}
@
Override
public
void
onResume
(
)
{
getActivity
(
)
.
setTitle
(
R
.
string
.
app_name
)
;
getActivity
(
)
.
getActionBar
(
)
.
setTitle
(
R
.
string
.
app_name
)
;
super
.
onResume
(
)
;
}
}
|
FavoriteListFragment
In src folder, create a new class FavoriteListFragment in the package com.androidopentutorials.spfavorites.fragment .
- This fragment displays all the stored favorite items in a ListView. When an item is long pressed in this ListView it is removed from favorites i.e.) removed from SharedPreferences.
- This fragment is displayed when favorite icon in Action bar is clicked.
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
|
package
com
.
androidopentutorials
.
spfavorites
.
fragment
;
import
java
.
util
.
List
;
import
android
.
app
.
Activity
;
import
android
.
app
.
AlertDialog
;
import
android
.
content
.
DialogInterface
;
import
android
.
os
.
Bundle
;
import
android
.
support
.
v4
.
app
.
Fragment
;
import
android
.
view
.
LayoutInflater
;
import
android
.
view
.
View
;
import
android
.
view
.
ViewGroup
;
import
android
.
widget
.
AdapterView
;
import
android
.
widget
.
AdapterView
.
OnItemClickListener
;
import
android
.
widget
.
AdapterView
.
OnItemLongClickListener
;
import
android
.
widget
.
ImageView
;
import
android
.
widget
.
ListView
;
import
android
.
widget
.
Toast
;
import
com
.
androidopentutorials
.
spfavorites
.
R
;
import
com
.
androidopentutorials
.
spfavorites
.
adapter
.
ProductListAdapter
;
import
com
.
androidopentutorials
.
spfavorites
.
beans
.
Product
;
import
com
.
androidopentutorials
.
spfavorites
.
utils
.
SharedPreference
;
public
class
FavoriteListFragment
extends
Fragment
{
public
static
final
String
ARG_ITEM_ID
=
"favorite_list"
;
ListView
favoriteList
;
SharedPreference
sharedPreference
;
List
<
Product
>
favorites
;
Activity
activity
;
ProductListAdapter
productListAdapter
;
@
Override
public
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
)
;
activity
=
getActivity
(
)
;
}
@
Override
public
View
onCreateView
(
LayoutInflater
inflater
,
ViewGroup
container
,
Bundle
savedInstanceState
)
{
View
view
=
inflater
.
inflate
(
R
.
layout
.
fragment_product_list
,
container
,
false
)
;
// Get favorite items from SharedPreferences.
sharedPreference
=
new
SharedPreference
(
)
;
favorites
=
sharedPreference
.
getFavorites
(
activity
)
;
if
(
favorites
==
null
)
{
showAlert
(
getResources
(
)
.
getString
(
R
.
string
.
no_favorites_items
)
,
getResources
(
)
.
getString
(
R
.
string
.
no_favorites_msg
)
)
;
}
else
{
if
(
favorites
.
size
(
)
==
0
)
{
showAlert
(
getResources
(
)
.
getString
(
R
.
string
.
no_favorites_items
)
,
getResources
(
)
.
getString
(
R
.
string
.
no_favorites_msg
)
)
;
}
favoriteList
=
(
ListView
)
view
.
findViewById
(
R
.
id
.
list_product
)
;
if
(
favorites
!=
null
)
{
productListAdapter
=
new
ProductListAdapter
(
activity
,
favorites
)
;
favoriteList
.
setAdapter
(
productListAdapter
)
;
favoriteList
.
setOnItemClickListener
(
new
OnItemClickListener
(
)
{
public
void
onItemClick
(
AdapterView
<?
>
parent
,
View
arg1
,
int
position
,
long
arg3
)
{
}
}
)
;
favoriteList
.
setOnItemLongClickListener
(
new
OnItemLongClickListener
(
)
{
@
Override
public
boolean
onItemLongClick
(
AdapterView
<?
>
parent
,
View
view
,
int
position
,
long
id
)
{
ImageView
button
=
(
ImageView
)
view
.
findViewById
(
R
.
id
.
imgbtn_favorite
)
;
String
tag
=
button
.
getTag
(
)
.
toString
(
)
;
if
(
tag
.
equalsIgnoreCase
(
"grey"
)
)
{
sharedPreference
.
addFavorite
(
activity
,
favorites
.
get
(
position
)
)
;
Toast
.
makeText
(
activity
,
activity
.
getResources
(
)
.
getString
(
R
.
string
.
add_favr
)
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
button
.
setTag
(
"red"
)
;
button
.
setImageResource
(
R
.
drawable
.
heart_red
)
;
}
else
{
sharedPreference
.
removeFavorite
(
activity
,
favorites
.
get
(
position
)
)
;
button
.
setTag
(
"grey"
)
;
button
.
setImageResource
(
R
.
drawable
.
heart_grey
)
;
productListAdapter
.
remove
(
favorites
.
get
(
position
)
)
;
Toast
.
makeText
(
activity
,
activity
.
getResources
(
)
.
getString
(
R
.
string
.
remove_favr
)
,
Toast
.
LENGTH_SHORT
)
.
show
(
)
;
}
return
true
;
}
}
)
;
}
}
return
view
;
}
public
void
showAlert
(
String
title
,
String
message
)
{
if
(
activity
!=
null
&&
!
activity
.
isFinishing
(
)
)
{
AlertDialog
alertDialog
=
new
AlertDialog
.
Builder
(
activity
)
.
create
(
)
;
alertDialog
.
setTitle
(
title
)
;
alertDialog
.
setMessage
(
message
)
;
alertDialog
.
setCancelable
(
false
)
;
// setting OK Button
alertDialog
.
setButton
(
AlertDialog
.
BUTTON_POSITIVE
,
"OK"
,
new
DialogInterface
.
OnClickListener
(
)
{
public
void
onClick
(
DialogInterface
dialog
,
int
which
)
{
dialog
.
dismiss
(
)
;
// activity.finish();
getFragmentManager
(
)
.
popBackStackImmediate
(
)
;
}
}
)
;
alertDialog
.
show
(
)
;
}
}
@
Override
public
void
onResume
(
)
{
getActivity
(
)
.
setTitle
(
R
.
string
.
favorites
)
;
getActivity
(
)
.
getActionBar
(
)
.
setTitle
(
R
.
string
.
favorites
)
;
super
.
onResume
(
)
;
}
}
|
MainActivity
This is the main activity class.
- When the app starts, it begins a new FragmentTransaction and starts ProductListFragment.
- When an Action bar icon is clicked, it starts FavoriteListFragment.
- Proper back navigation of fragments on back key pressed is handled by overriding onBackPressed()
- It also handles fragment orientation changes and retains the state of the fragment by overriding onSaveInstanceState()
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
package
com
.
androidopentutorials
.
spfavorites
;
import
android
.
os
.
Bundle
;
import
android
.
support
.
v4
.
app
.
Fragment
;
import
android
.
support
.
v4
.
app
.
FragmentActivity
;
import
android
.
support
.
v4
.
app
.
FragmentManager
;
import
android
.
support
.
v4
.
app
.
FragmentTransaction
;
import
android
.
view
.
Menu
;
import
android
.
view
.
MenuItem
;
import
com
.
androidopentutorials
.
spfavorites
.
fragment
.
FavoriteListFragment
;
import
com
.
androidopentutorials
.
spfavorites
.
fragment
.
ProductListFragment
;
public
class
MainActivity
extends
FragmentActivity
{
private
Fragment
contentFragment
;
ProductListFragment
pdtListFragment
;
FavoriteListFragment
favListFragment
;
@
Override
protected
void
onCreate
(
Bundle
savedInstanceState
)
{
super
.
onCreate
(
savedInstanceState
)
;
setContentView
(
R
.
layout
.
activity_main
)
;
FragmentManager
fragmentManager
=
getSupportFragmentManager
(
)
;
/*
* This is called when orientation is changed.
*/
if
(
savedInstanceState
!=
null
)
{
if
(
savedInstanceState
.
containsKey
(
"content"
)
)
{
String
content
=
savedInstanceState
.
getString
(
"content"
)
;
if
(
content
.
equals
(
FavoriteListFragment
.
ARG_ITEM_ID
)
)
{
if
(
fragmentManager
.
findFragmentByTag
(
FavoriteListFragment
.
ARG_ITEM_ID
)
!=
null
)
{
setFragmentTitle
(
R
.
string
.
favorites
)
;
contentFragment
=
fragmentManager
.
findFragmentByTag
(
FavoriteListFragment
.
ARG_ITEM_ID
)
;
}
}
}
if
(
fragmentManager
.
findFragmentByTag
(
ProductListFragment
.
ARG_ITEM_ID
)
!=
null
)
{
pdtListFragment
=
(
ProductListFragment
)
fragmentManager
.
findFragmentByTag
(
ProductListFragment
.
ARG_ITEM_ID
)
;
contentFragment
=
pdtListFragment
;
}
}
else
{
pdtListFragment
=
new
ProductListFragment
(
)
;
setFragmentTitle
(
R
.
string
.
app_name
)
;
switchContent
(
pdtListFragment
,
ProductListFragment
.
ARG_ITEM_ID
)
;
}
}
@
Override
protected
void
onSaveInstanceState
(
Bundle
outState
)
{
if
(
contentFragment
instanceof
FavoriteListFragment
)
{
outState
.
putString
(
"content"
,
FavoriteListFragment
.
ARG_ITEM_ID
)
;
}
else
{
outState
.
putString
(
"content"
,
ProductListFragment
.
ARG_ITEM_ID
)
;
}
super
.
onSaveInstanceState
(
outState
)
;
}
@
Override
public
boolean
onCreateOptionsMenu
(
Menu
menu
)
{
getMenuInflater
(
)
.
inflate
(
R
.
menu
.
main
,
menu
)
;
return
true
;
}
@
Override
public
boolean
onOptionsItemSelected
(
MenuItem
item
)
{
switch
(
item
.
getItemId
(
)
)
{
case
R
.
id
.
menu_favorites
:
setFragmentTitle
(
R
.
string
.
favorites
)
;
favListFragment
=
new
FavoriteListFragment
(
)
;
switchContent
(
favListFragment
,
FavoriteListFragment
.
ARG_ITEM_ID
)
;
return
true
;
}
return
super
.
onOptionsItemSelected
(
item
)
;
}
public
void
switchContent
(
Fragment
fragment
,
String
tag
)
{
FragmentManager
fragmentManager
=
getSupportFragmentManager
(
)
;
while
(
fragmentManager
.
popBackStackImmediate
(
)
)
;
if
(
fragment
!=
null
)
{
FragmentTransaction
transaction
=
fragmentManager
.
beginTransaction
(
)
;
transaction
.
replace
(
R
.
id
.
content_frame
,
fragment
,
tag
)
;
//Only FavoriteListFragment is added to the back stack.
if
(
!
(
fragment
instanceof
ProductListFragment
)
)
{
transaction
.
addToBackStack
(
tag
)
;
}
transaction
.
commit
(
)
;
contentFragment
=
fragment
;
}
}
protected
void
setFragmentTitle
(
int
resourseId
)
{
setTitle
(
resourseId
)
;
getActionBar
(
)
.
setTitle
(
resourseId
)
;
}
/*
* We call super.onBackPressed(); when the stack entry count is > 0. if it
* is instanceof ProductListFragment or if the stack entry count is == 0, then
* we finish the activity.
* In other words, from ProductListFragment on back press it quits the app.
*/
@
Override
public
void
onBackPressed
(
)
{
FragmentManager
fm
=
getSupportFragmentManager
(
)
;
if
(
fm
.
getBackStackEntryCount
(
)
>
0
)
{
super
.
onBackPressed
(
)
;
}
else
if
(
contentFragment
instanceof
ProductListFragment
||
fm
.
getBackStackEntryCount
(
)
==
0
)
{
finish
(
)
;
}
}
}
|
Output
ProductListFragment screen
FavoriteListFragment screen
-
Shruti Goyal
-
zohain
-
-
Sadat Mohammad Akash
-
Mayank Langalia
-
Om Balakumar
-
Mohamed Abdiqadir Osman
-
-
Dušan Dimitrijević
-
Priyanka Patel
-
-
m33ts4k0z
-
Chuy David Garza Dovalina
-
-
FaisalHyder
-
FaisalHyder
-
khanZee
-
FaisalHyder
-
khanZee
-
FaisalHyder
-
engrkamal1
-
FaisalHyder
-
-
-
-
-
Maham Khan
-
David Pilco
-
Maham Khan
-
saad
-
-
-
vinod
-
Mohamed Abdiqadir Osman
-
Hillarie Kip
-
Jordan Adcock
-
-
Jordan Adcock
-
Jordan Adcock
-
Girl Candy (Girlcandy)
-
-
Love Songs
-
Girl Candy (Girlcandy)
-
Jordan Adcock
-
Andile Simelane
-
-
-
yilber esteban flor orozco
-
Aditya Narayan
-
Geethanjali Kondisetti
-
Kalpesh
-
Satria Junanda
-
Akash
-
kuldeep
-
Theerapong Piluk