Search code examples
javaandroidlong-integerclasscastexception

force a variable to be 'long' type always


I have to save user id as long. i want to force save user id in long type of preference. what issue is if server assign me 22 as user id that is integer type. and i pass it to preference for saving. it saves under putInt method instead because the length of digit is short. and if i retrieve it it says integer can't cast be casted to long. below are overloaded methods in my prefrence util class that save user id.

public int read(String valueKey, int valueDefault) {
    return mPreferences.getInt(valueKey, valueDefault);
}

public void save(String valueKey, int value) {
    mEditor.putInt(valueKey, value);
    mEditor.commit();
} 

public long read(String valueKey, long valueDefault) {
    return mPreferences.getLong(valueKey, valueDefault);
}

public void save(String valueKey, long value) {
    mEditor.putLong(valueKey, value);
    mEditor.commit();
}

i want to save user id as long and retrieve it as same. what it does is, it predict user id to be integer because of length of digits maybe and save it under put mEditor.putInt(valueKey, value); .. hope you understand the frustration. what i could think of possible solution is that instead of passing value to these methods. i just save user id explicitly with putLong method .. or is there any other solution?


Solution

  • You could use enumerations instead of pure String objects:

    enum MyProperties{
      USER_ID{
        void save(long value, WhatEverTypeThisIs mEditor){
           mEditor.putLong(valueKey, longVal);
           mEditor.commit();
        }   
        long get( WhatEverOtherTypeThisIs mPreferences){
           return mPreferences.getLong(name(), valueDefault);
        }   
      },
      INT_PROPERTY{
        void save(long value, WhatEverTypeThisIs mEditor){
           mEditor.putInt(valueKey,(int) longVal);
           mEditor.commit();
        }   
        //needs cast to int at caller side
        long get( WhatEverOtherTypeThisIs mPreferences){
           return mPreferences.getInt(name(), valueDefault); 
        }   
     }; 
     abstract void save(long value, WhatEverTypeThisIs mEditor);
     abstract long get( WhatEverOtherTypeThisIs mPreferences);
    }
    

    Use:

       MyProperties.USER_ID.save(22,mEditor);
       long id22 = MyProperties.USER_ID.get(mPreferences);
       MyProperties.INT_PROPERTY.save(23,mEditor);
       int somValue23 = (int)MyProperties.INT_PROPERTY.get(mPreferences);