TinyDB--Android-Shared-Preferences-Turbo icon indicating copy to clipboard operation
TinyDB--Android-Shared-Preferences-Turbo copied to clipboard

using getObject() method

Open demo-Ashif opened this issue 7 years ago • 3 comments

how to use ..

public Object getObject(String key, Class<?> classOfT){

    String json = getString(key);
    Object value = new Gson().fromJson(json, classOfT);
    if (value == null)
        throw new NullPointerException();
    return value;
}

this method.

demo-Ashif avatar Jan 09 '17 08:01 demo-Ashif

Hello, i had the same issue, after a couple of tries i found the solution. For example i have a class called UserReponse, so i called this method like this

tinyDB.getObject("user",UserResponse.class);

As i could understand, this method will return the object and this parameter will cast the object it returns to the object type u pass to it.

I hope I have helped.

MatUFV avatar Jan 17 '17 00:01 MatUFV

It's not what you are saying. 2nd argument is nothing but default argument. Please pass an object of the same class with some default value. It'll work. With this approach: tinyDB.getObject("user",UserResponse.class); it'll work only when you have set earlier some value for key "user" else it'll give NullPointerException.

NeoHimu avatar Jul 27 '18 23:07 NeoHimu

Simply update the method from

`public <T> T getObject(String key, Class<T> classOfT){

    String json = getString(key);
    Object value = new Gson().fromJson(json, classOfT);
    if (value == null)
        throw new NullPointerException();
    return (T)value;
}`

to `public <T> T getObject(String key, Class<T> classOfT){

    String json = getString(key);
    Object value = new Gson().fromJson(json, classOfT);
    if (value == null)
        return null;
    return (T)value;
}`

mudi256 avatar Jul 13 '20 19:07 mudi256