2

I have been working on an android app lately in which a new user has to type a certain key to login. By the time he inserts that key, it is saved in Shared Preferences of his phone so that he won't have to login again.

My problem is that I want to check if the user is new, in other words check if there is a value called "Key" in the Shared Preferences so that the app will lead him straight to the Main Menu.

I hope I explained the issue clearly.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
Vaggelis Manousakis
  • 292
  • 1
  • 5
  • 15

2 Answers2

2

you do this in two way first way

 SharedPreferences pref =getSharedPreferences("yourPrefName",MODE_PRIVATE);
 if(pref.contains("YourKey"){
// key is exist
}else{
//  key not  exist
}

second way
if you have any unique information like id for every user and id no possible to be some value like -1

so you can do this to check if user is login or not yet

SharedPreferences pref =getSharedPreferences("yourPrefName",MODE_PRIVATE);

 // getInt(key,defualtValue) method accept two value 
 // key : name key in sharefPrefrance
 // defualtValue: if the key does not exist the method will return this defualtValue 
 int id= pref.getInt("id",-1);

 if(id!=-1)
 // user is login and have id 
Mahmoud Abu Alheja
  • 3,343
  • 2
  • 24
  • 41
2

SharedPreferences has a

contains(String key)

method. Used it to check if entry with your given key exists.

SharedPreferences prefs = context.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE);
if(pref.contains("Key"){
  String deviceToken = prefs.getString("Key", null);
}else{
  // New User
}

or Use the

getAll()

method of android.content.SharedPreferences.

Map<String, ?> map = context.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE).getAll();
for (Map.Entry<String, ?> entry: prefsMap.entrySet()) {
    // entry.getValue().toString() will give the key. check it against the key that you want.
}

in Kotlin

val prefs = context?.getSharedPreferences("SharedPref_Name", Context.MODE_PRIVATE)
        if(prefs?.contains("Key")!!){
                    val deviceToken = prefs.getString("Key", null);
                }

or

 (context?.getSharedPreferences("",Context.MODE_PRIVATE))?.all?.forEach {
 //access key using it.key & value using it.value
 Log.d("Preferences values",it.key() + ": " + it.value()             

}

anoo_radha
  • 812
  • 1
  • 15
  • 34