I will try to explain this as best I can. (I'm still new with both Java and Android)
Issue:
I am trying to compare an incoming number string to a Contact object's number string by searching the arrayList.
Background:
I am able to load Contacts from an arrayList into different views (ListView, textView, etc) so I know the methods and objects are working. It's this new class (RingerService) that I'm having the issue with.
Design
I have an arrayList of contacts in a class named contactStorage. It works as intended for displaying different views:
//constructor with context to access project resources and instantiate from JSONfile to arrayList
private ContactStorage(Context appContext){
mAppContext = appContext;
mSerializer = new ContactJSONer(mAppContext, FILENAME);
try{
mContacts = mSerializer.loadContacts();
}catch (Exception e){
mContacts = new ArrayList<Contact>();
Log.e(TAG, "No contacts available, creating new list: ", e);
}
}
//get method to only return one instance from the constructor
public static ContactStorage get(Context c){
if (sContactStorage == null){
sContactStorage = new ContactStorage(c.getApplicationContext());
}
return sContactStorage;
}
//for ringer service to find matching number
public Contact getContactNumber(String number){
for (Contact c: mContacts){
if(c.getNumber().replaceAll("[^0-9]", "").equals(number))
return c;
}
return null;
}
when I call the get method above in the RingerService class below, that's when things break. To be specific, I am getting a NullPointerException on onCallStateChanged:
private Contact mContact;
private String number;
private Context mContext;
@Override
public void onCreate(){
mTelephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
mPhoneStateListener = new PhoneStateListener(){
// state change
@Override
public void onCallStateChanged(int state, String incomingNumber){
if (state == 1 ){
try{
mContact = ContactStorage.get(mContext).getContactNumber(incomingNumber);
number = mContact.getNumber();
Log.d(TAG, state+" received an incoming number: " + number);
}catch(Exception e){
Log.d(TAG, " exception: " + e);
}
} else {
Log.d(TAG, state+" number not found" + incomingNumber);
}
}
};
super.onCreate();
}
Troubeshooting:
1. I've removed the reference to number (number = mContact.getNumber();) - the program runs fine in that case. I can send a test call to the emulator and the log message displays correctly with the test number arg. I considered it could be the way in which the array searching works in getContactNumber class. Is it never finding a matching value, resulting in null?
2. I also thought that since this is a service, I'm somehow not getting the right context when calling the ContactStorage.get(Context c) method.
3. if I set my mContact reference and no number match was found, would mContact = null; still let the program run?