Matching phone number in HashMap : Android - android

I am doing an application where I need to store some numbers and when someone call on phone I need to check if incoming number is present in my database or not.
What I did
I stored phone numbers in shared preferences. Internally android uses Map for this purpose.
Problem:
Lets say I stored 9089889899 (10 digit phone number). Now if I get an incoming call from this number it may BroadcastReceiver having 09089889899 or +91-9089889899 number for the same.
So my problem is that if I stored a number into preferences then how can I match the incoming number is present in preferences or not.

I suggest that you use something like libphonenumber to handle the phone numbers independent of the format.
There is also some functions for formatting and comparing numbers in PhoneNumberUtils.

SharedPreferences settings;
settings = getSharedPreferences("PREF_NAME", Context.MODE_PRIVATE);
//for get sharepref
String phone = settings.getString("9089889899", 0);
//strPhone = has your broadcast receive number
if(strPhone.contains(phone)){
}else{
}

If you are using the mobile phone as key for the sharedpreference you can:
retrive all the values of your sharedpreference: see here
iterate through the key set : see here
for every key use the contains String method: see here
Edit: why are you not use a content provider?

You can try out the following code in your BroadCast Receiver.
here "abc" with the name of your Shared Perefence. Assuming that num here is the number you got from the Broadcast Receiver:
In the code, the last 10 digits are taken out and compared, as these are what stored in SharedPreference.
SharedPreferences sp = getSharedPreferences("abc",Context.MODE_PRIVATE);
HashMap< String, String>hMap = (HashMap<String, String>) sp.getAll();
String num = "+91-9089889899";
if( hMap.containsValue(num.substring(num.length()-10))){
System.out.println("number present");
}

here is the regex that will match all the phone formats
(((([0-9]){0,1})(([0-9]){10}))|([0-9]){10}|(\+([0-9]){1,2}([0-9]{10})))
first part matches 0 - 1231231234
second part matches 1231231234
last part +91 - 1231231234
update
actually this is much better
(((([0-9]){0,1})(([0-9]){10}))|(\+([0-9]){1,2}([0-9]{10})))

Related

Generate unique ID per user

I am developing a cross platform game for which I needs to generate unique identifier (User ID) for each user. I known some platform (Android or iOS) specific approaches to get device related identifiers but I am looking for a solution independent of the device identifiers.
User ID Requirements:
Independent of the device's platform
Offline implementation (no communication with any servers)
Without sign-up process
I have implemented one approach to create User IDs where I store the system time when the game was launched for the first time on the device.
I have following questions:
Are there any other approaches to generate User IDs (which will meet the above requirements)?
What are the common approaches to create unique identifiers with taking any information from the user?
Are there any third party plug-ins to implement User IDs?
I would appreciate any suggestions and thoughts on this topic.
EDIT:
There are lot of responses to use UUID/GUID. Generally, this approach looks fine but I am looking for a solution which can generate same User ID even if the user reinstall the game.
Have you looked at UUID from Java?
https://docs.oracle.com/javase/7/docs/api/java/util/UUID.html
EDIT: The following links might help using UUID for unique identifiers.
Best practices for permissions & Identifiers
Instance ID
When you say user id, are you talking about a public id such as an username, or a database id?
If you are talking about a database id, go for a GUID/UUID. T-sql for example have the NEWID() method that will return a GUID that doesn't exist in the database yet. I am sure that whichever database you go for you will find some way to use a GUID.
https://learn.microsoft.com/en-us/sql/t-sql/functions/newid-transact-sql
As per my opinion your System current time is the best method for generating Unique User Id.
For Android :
System.currentTimeMillis() returns you the unique 13 digit number which can be used as User Id.
But When you get current time in iOS then it is 10 digit number which generates. So you can multiply it by 1000 to make User Id platform Independent.
Happy Coding...
Assuming that your usernames are unique, you could simply takje the md5 hash of your usernames to get an unique ID (string). e.g. in php:
$userID = md5($username);
because m5 hash functions exist in nearly every programming language you should be able to use this ID on all possible plattforms.
And if you arer looking for a numeric ID, you even can calculate a qunique number from md5.
See represent md5-hash as an integer - stack question for more details
Just generate a long string of random characters. For example, generates a 10 long string of alphanumerics ...
private String GetId(){
String[] chars = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","0","1","2","3","4","5","6","7","8","9"};
StringBuilder s = new StringBuilder(10);
for(int i = 0;i<10;i++){
int pos = (int) (Math.random() * 62);
String c = "";
if (pos > chars.length-1){
pos = pos - chars.length;
c = chars[pos].toUpperCase();
}else{
c = chars[pos];
}
s.append(c);
}
return s.toString();
}

Compare phone number from database in different condition

I'm developing sms APP and want to receive sms from the specific numbers. But number can be changed sometime with country code as +923201234567 or sometime without country code 03201234567 how I can compare number from database? because don't know in which format number is saved in database(with country code or without country code)
public boolean isMember(String phone, long id){
String query = "SELECT * from members where phone = ? AND active = 1 AND gid = ?";
Cursor c = dbActions.rawQuery(query, new String[]{String.valueOf(phone), String.valueOf(id)});
return c.moveToFirst();
}
Suppose if the number is saved in database without country code 03201234567 then my requirement is to get true if I compare it with country code. +923201234567. Country code could be changed.
PhoneNumberUtils.compare(); is not useful because it not compare with database.
If you can't acquire the correct information always; then you need to look into heuristics.
Meaning: you could write your own comparisons; and when you encounter two numbers like:
03201234567
+923201234567
you can figure: their "tail" is equal; the only difference is that the first one starts with 0 (so no country code) and the second one with +92. So it might be reasonable to declare those two numbers to be equal.
So a "solution" would do things like "normalize" your input (remove all non-digit content; except for leading + signs); and to then make such "tail-bound" comparisons.
If that is "too" fuzzy; I guess then you should step back and describe the requirement that you actually try to resolve here. Why are you comparing numbers; and what do you intend to do with the output of that comparison?!
Normalize all of the phone numbers into the same format before you put them into the database. That way you can just do a normal db search.
The other thing I've done for phone numbers is to convert all letters into the appropriate number, then remove all non digits, then just compare the last 7 digits.

Changing Android Shared Preference Value from String to Int

I'm updating my Android app. The app retrieves data from my server and among that data is a user id. The user id is a number (Integer) but it arrives from the server as a string eg "1234". In the old version I then saved this user id as a string in my shared prefernces but now that I'm looking back at it I don't like this and want to save it as an Integer as it should be.
So far pretty simple. I just use putInt / getInt rather than putString / getString. The problem is that all the people currently using the app will have the value saved in their shared preferences as a string and then when they update the app the new version of the app will start to try to use getInt to get the value which the old version saved as a string.
What's the best way to avoid any errors because of this and ensure a smoothe transition between the two app versions?
Thanks.
Something like that in your onCreate:
try{
prefs.getInt("key", 0);
}catch (ClassCastException e){
Integer uid = Integer.parseInt(prefs.getString("key", null);
if(uid != null)
prefs.edit().putInt("key", uid).commit();
}
This is as simple as
int userid = Integer.parseInt( preferences.getString("userid", ""));
First of all convert you string user id into integer like,
int uid=Integer.parseInt("1234");//here is your string user id in place of 1234.
and then write uid into your shared preference with putExtra(key,intValue).
that's it.

Clearer Format Firebase Android retrieved data

When I retrieve my data it contains brackets { and unique id such as - JSDHGJDGJJSKA ... I want to make it cleaner and get rid of the brackets for e.g. my output is:
{-JfFQQRYnhiKeuN5ERGX={msg=Monday},-JfFQAhQQWIFAUuV1nD4={msg=this is test}}
I want to get rid of the brackets and the word msg and retrieve just one of the message at random.
I want my output to be if I pick up a random message:
Monday
if I pick up another at random
this is test
Any ideas on how to achieve this will be greatly appreciated.
This will retrieve a random message from the object you've shown in your question.
function getRandomMessage(data) {
if( !data ) { return null; }
var keys = Object.keys(data);
var randomKey = keys[ Math.floor(Math.random()*keys.length) ];
return data[randomKey];
}
Keep in mind that this assumes you have a small number of records. If you start getting into the thousands, you'll need a more robust solution than just grabbing the entire data set.
When I used this I was able to retrieve my data for eg. I save as Book -> title: "The book of death"
here is the code to retrieve the title:Retrieve data-
String title = (String) snapshot.child("title").getValue();
It worked after I used and I didnt used push since push creates its unique ID and its complex for my level to deal with it so I used:Saving data-
Map<String, Object> title= new HashMap<String, Object>();
title.put("title", "This is a working message");
f.child("Book").updateChildren(title);
and everything worked out. I hope it helps everyone who has having these issues. With update children you can use auto increment for your id.
are you getting data in string ? and If you are using string then it is easy , you can use the method of replace eg: yourString.replace("a","b")

can i store two or more values with same key using SharedPreferences in android?

can i store two or more values with same key using SharedPreferences in android? If no, please tell me how to store values of username, first name, password etc when many users register in registration app?
Ex:
person A registered with username="john12", first name="john" and DOB="06/06/2000".
person B registered with username="arun89", first name="arun" and DOB="08/11/1989".
Now, I want to store these values in SharedPreferences and retrieve them later. Is it possible using SharedPreferences? If not, Please tell me how to do in other way.
Thank you in advance.
I woud consider creating a JSONObject and add the fields you want to store as a key:value pair.
json.putString(key, value);
You can then store the json object in it's string representation with json.toString() and restore it later with
JSONObject jo = new JSONObject(jsonString);
String value = jo.getString(key);
JSONObject also offeres different data types beside strings.
It really depends on how much data you want to store. Depending on that I would choose SharedPreferences or a SQLite implementation.
You cannot store these values directly (as ones added latter will overwrite previously added) but you can always store Parcelable and put your data into it
For your case it is better use SQLIte database.But if you want to use shared preference it is still possible.You have to use a key with additional index to remember different user like
UserName1:arun
UserName2:john
You have to remember the total number of user.Then can maintain all of them.you can also use other data structure like hashmap to maintain data for the shared preference.
I dont't think it is possible, as you don't know the number of users.
You could try to separate the users with commas, but that's lame.
You should consider using SQLite database.
http://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html
Then you have to store a array List of user objects first create a class userInfo then create a array List type of userInfo then store the data in this list and put a serialize-able object in SharedPreferences.
You can also store them on a single key called "registers" as string. Concatenate each register to preference. Put ";" (or any other characther you want) between each register. Then parse the string and use the values.
Key: registers
Value: "username=john12, first name=john, DOB=06/06/2000;username=mike12, first name=mike, DOB=06/07/2012"
Using split method of String will give you a list of registers as String.
registers.split(";");
Splitting again with "," will give you properties of each register.

Categories

Resources