How to store class object in android sharedPreference? - android

I would like to store class object in android sharedpreference. I did some basic search on that and I got some answers like make it serializable object and store it but my need is so simple. I would like to store some user info like name, address, age and boolean value is active. I made one user class for that.
public class User {
private String name;
private String address;
private int age;
private boolean isActive;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean isActive) {
this.isActive = isActive;
}
}
Thanks.

Download gson-1.7.1.jar from this link: GsonLibJar
Add this library to your android project and configure build path.
Add the following class to your package.
package com.abhan.objectinpreference;
import java.lang.reflect.Type;
import android.content.Context;
import android.content.SharedPreferences;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private final Context context;
private final SharedPreferences preferences;
private final SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>(){}
.getType();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "abhan";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context,
String namePreferences, int mode) {
if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context,
namePreferences, mode);
}
return complexPreferences;
}
public void putObject(String key, Object object) {
if (object == null) {
throw new IllegalArgumentException("Object is null");
}
if (key.equals("") || key == null) {
throw new IllegalArgumentException("Key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
}
else {
try {
return GSON.fromJson(gson, a);
}
catch (Exception e) {
throw new IllegalArgumentException("Object stored with key "
+ key + " is instance of other class");
}
}
} }
Create one more class by extending Application class like this
package com.abhan.objectinpreference;
import android.app.Application;
public class ObjectPreference extends Application {
private static final String TAG = "ObjectPreference";
private ComplexPreferences complexPrefenreces = null;
#Override
public void onCreate() {
super.onCreate();
complexPrefenreces = ComplexPreferences.getComplexPreferences(getBaseContext(), "abhan", MODE_PRIVATE);
android.util.Log.i(TAG, "Preference Created.");
}
public ComplexPreferences getComplexPreference() {
if(complexPrefenreces != null) {
return complexPrefenreces;
}
return null;
} }
Add that application class in your manifest's application tag like this.
<application android:name=".ObjectPreference"
android:allowBackup="false"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
....your activities and the rest goes here
</application>
In Your Main Activity where you wanted to store value in Shared Preference do something like this.
package com.abhan.objectinpreference;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
private final String TAG = "MainActivity";
private ObjectPreference objectPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
objectPreference = (ObjectPreference) this.getApplication();
User user = new User();
user.setName("abhan");
user.setAddress("Mumbai");
user.setAge(25);
user.setActive(true);
User user1 = new User();
user1.setName("Harry");
user.setAddress("London");
user1.setAge(21);
user1.setActive(false);
ComplexPreferences complexPrefenreces = objectPreference.getComplexPreference();
if(complexPrefenreces != null) {
complexPrefenreces.putObject("user", user);
complexPrefenreces.putObject("user1", user1);
complexPrefenreces.commit();
} else {
android.util.Log.e(TAG, "Preference is null");
}
}
}
In another activity where you wanted to get the value from Preference do something like this.
package com.abhan.objectinpreference;
import android.app.Activity;
import android.os.Bundle;
public class SecondActivity extends Activity {
private final String TAG = "SecondActivity";
private ObjectPreference objectPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
objectPreference = (ObjectPreference) this.getApplication();
ComplexPreferences complexPreferences = objectPreference.getComplexPreference();
android.util.Log.i(TAG, "User");
User user = complexPreferences.getObject("user", User.class);
android.util.Log.i(TAG, "Name " + user.getName());
android.util.Log.i(TAG, "Address " + user.getAddress());
android.util.Log.i(TAG, "Age " + user.getAge());
android.util.Log.i(TAG, "isActive " + user.isActive());
android.util.Log.i(TAG, "User1");
User user1 = complexPreferences.getObject("user", User.class);
android.util.Log.i(TAG, "Name " + user1.getName());
android.util.Log.i(TAG, "Address " + user1.getAddress());
android.util.Log.i(TAG, "Age " + user1.getAge());
android.util.Log.i(TAG, "isActive " + user1.isActive());
} }
Hope this can help you. In this answer I used your class for the reference 'User' so you can better understand. However we can not relay on this method if you opted to store very large objects in preference as we all know that we have limited memory size for each app in data directory so that if you are sure you have only limited data to store in shared preference you can use this alternative.
Any suggestions on this implement are most welcome.

the other way is to save each property by itself..Preferences accept only primitive types, so you can't put a complex Object in it

You can use the global class
public class GlobalState extends Application
{
private String testMe;
public String getTestMe() {
return testMe;
}
public void setTestMe(String testMe) {
this.testMe = testMe;
}
}
and then Locate your application tag in nadroid menifest, and add this into it :
android:name="com.package.classname"
and you can set and get the data from any of your activity by using the following code.
GlobalState gs = (GlobalState) getApplication();
gs.setTestMe("Some String");</code>
// Get values
GlobalState gs = (GlobalState) getApplication();
String s = gs.getTestMe();

You could just add some normal SharedPreferences "name", "address", "age" & "isActive" and simply load them when instantiating the class

Simple solution of how to store login value in by SharedPreferences.
You can extend the MainActivity class or other class where you will store the "value of something you want to keep". Put this into writer and reader classes:
public static final String GAME_PREFERENCES_LOGIN = "Login";
Here InputClass is input and OutputClass is output class, respectively.
// This is a storage, put this in a class which you can extend or in both classes:
//(input and output)
public static final String GAME_PREFERENCES_LOGIN = "Login";
// String from the text input (can be from anywhere)
String login = inputLogin.getText().toString();
// then to add a value in InputCalss "SAVE",
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
Editor editor = example.edit();
editor.putString("value", login);
editor.commit();
Now you can use it somewhere else, like other class. The following is OutputClass.
SharedPreferences example = getSharedPreferences(GAME_PREFERENCES_LOGIN, 0);
String userString = example.getString("value", "defValue");
// the following will print it out in console
Logger.getLogger("Name of a OutputClass".class.getName()).log(Level.INFO, userString);

Related

Android Xamarin: not able to read from SharedPreferences

I am getting the default text and not the actual text saved when trying to access a shared preference. I have tested that it returns true when saving so I am pretty sure the problem is in reading from the preference file.
The preference class
public class SaveWarningMessage : Activity
{
private ISharedPreferences myPref;
private ISharedPreferencesEditor myPrefEditor;
private Context myContext;
public void MyAppPref(Context context)
{
this.myContext = context;
myPref = PreferenceManager.GetDefaultSharedPreferences(myContext);
myPrefEditor = myPref.Edit();
}
public void SaveString(string text)
{
myPrefEditor.PutString("warning text", text);
var returnValue = myPrefEditor.Commit();
}
public string GetString()
{
return myPref.GetString("warning text", "could not get pref");
}
}
}
The class saving the preference:
string warningText = Intent.GetStringExtra("warningText");
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
classInstans.SaveString(warningText);
The class reading from the preference:
Context mContext = Android.App.Application.Context;
SaveWarningMessage classInstans = new SaveWarningMessage();
classInstans.MyAppPref(mContext);
string message = classInstans.GetString();
Personally I would not subclass it from Activity(?) and use the .actor to instance your ISharedPreferences, along with a few other changes you end up with this example.
Example:
public class SaveWarningMessage
{
public const string WARNINGTEXT = "warning text";
ISharedPreferences myPref;
public SaveWarningMessage(Context context)
{
myPref = PreferenceManager.GetDefaultSharedPreferences(context);
}
public void SaveString(string text)
{
var myPrefEditor = myPref.Edit();
myPrefEditor.PutString(WARNINGTEXT, text);
if (!myPrefEditor.Commit())
{
Log.Error("SomeTag", $"Saving {text} to Pref:{WARNINGTEXT} failed");
}
// Or replace the Commit & check of return the following
// if you do not care about checking the return value
// myPrefEditor.Apply();
}
public string GetString()
{
return myPref.GetString(WARNINGTEXT, "could not get pref");
}
}
Then you can you it like this:
string warningText = "SomeStringToSave";
SaveWarningMessage classInstans = new SaveWarningMessage(Application.Context);
classInstans.SaveString(warningText);
SaveWarningMessage classInstans2 = new SaveWarningMessage(Application.Context);
string message = classInstans2.GetString();
Log.Debug("SO", message);

How to get values from shared preference and check it using if

Hi I'm using user login screen. In that I'm using shared preferences to store the user details and store whether the user is logged in or not. I'm using splash screen and in that splash activity I checked a value from sharedpreference to know whether the user is already logged in or not.If the user logged in,then after splash it will go to dashboard otherwise it goes to login screen.But i am getting null pointer error.please help me.
My shared prefrence class is:
public class Userloginsession {
public static final String IS_User_login = "isuserloggedin";
// {"did":"1","drivername":"arul ji","dusername":"PIKDRIVER01","logid":"79"}
//Driver Login details
//From DRIVER
public static final String IS_SNO = "sno";
public static final String IS_USERNAME = "userloginname";
public static final String IS_USERPASSWORD = "userloginpassword";
//
public static final String IS_EMP_ID = "emp_id";
//
//From Json Driver
public static final String IS_FIRST_NAME = "first_name";
public static final String IS_LAST_NAME = "last_name";
public static final String IS_IMAGE = "image";
static SharedPreferences user_details;
// Editor Reference for sharedpref
SharedPreferences.Editor user_details_editor;
public Userloginsession(final Context applicationContext) {
// create sharedpreff file "driverSession" for DRIVERLOGINACTIVITY
user_details = applicationContext.getSharedPreferences("usersession",0);
//Edit pfeff file
user_details_editor = user_details.edit();
user_details_editor.apply();
}
public static boolean isuserLoggedIn() {
return user_details.getBoolean(IS_User_login, false);
}
public void createuserLogin(String passwordp, String username, String SNO, final String EMP_ID, final String FIRST_NAME, final String LAST_NAME, final String Image) {
user_details_editor.putBoolean(IS_User_login, true);
user_details_editor.putString(IS_USERNAME, username);
user_details_editor.putString(IS_USERPASSWORD, passwordp);
user_details_editor.putString(IS_SNO, SNO);
user_details_editor.putString(IS_EMP_ID, EMP_ID);
user_details_editor.putString(IS_FIRST_NAME, FIRST_NAME);
user_details_editor.putString(IS_LAST_NAME, LAST_NAME);
user_details_editor.putString(IS_IMAGE, Image);
user_details_editor.commit();
}
public HashMap<String, String> isGetuserDetails() {
// Use hashmap to store user credentials
final HashMap<String, String> userdetailsmap = new HashMap<>();
// Driv pass
userdetailsmap.put(IS_USERNAME, user_details.getString(IS_USERNAME, null)); // Driv Pass
// Driver user name
userdetailsmap.put(IS_USERPASSWORD, user_details.getString(IS_USERPASSWORD, null));
// Driver ID
userdetailsmap.put(IS_SNO, user_details.getString(IS_SNO, null));
//Driver Name
userdetailsmap.put(IS_EMP_ID, user_details.getString(IS_EMP_ID, null));
userdetailsmap.put(IS_FIRST_NAME, user_details.getString(IS_FIRST_NAME, null));
userdetailsmap.put(IS_LAST_NAME, user_details.getString(IS_LAST_NAME, null));
userdetailsmap.put(IS_IMAGE, user_details.getString(IS_IMAGE, null));
return userdetailsmap;
}
public void clearAllvalues() {
user_details_editor = user_details.edit();
user_details_editor.clear();
user_details_editor.apply();
}
}
My splashscreen acticty is :
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (Userloginsession.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
My error is:
Process: com.example.notebook.dptextiles, PID: 214 java.lang.NullPointerException:
Attempt to invoke interface method 'boolean android.content.SharedPreferences.getBoolean(java.lang.String, boolean)' on a null object reference
at com.example.notebook.dptextiles.fragments.Userloginsession.isuserLoggedIn(Userloginsession.java:45
at com.example.notebook.dptextiles.Splashscreen$1.run(Splashscreen at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5441)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
You are using Userloginsession.isuserLoggedIn() directly
use it like this
Userloginsession login=new Userloginsession(getApplicationContext());
if (login.isuserLoggedIn())
The problem is your are not initializing the sharedpreference. Ie. Userloginsession not get initialized. For that you need to give activity context.
the overall class should be
public class Splashscreen extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splashscreen2);
Userloginsession login=new Userloginsession(getApplicationContext());
new Handler().postDelayed(new Runnable() {
/*
* Showing splash screen with a timer. This will be useful when you
* want to show case your app logo / company
*/
#Override
public void run() {
// This method will be executed once the timer is over
// Start your app main activity
if (login.isuserLoggedIn()) {
// startActivity(new Intent(MainActivity.this, RideHistry.class));
startActivity(new Intent(Splashscreen.this, Dashboard.class));
/*overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_right);*/
finish();
} else {
// if driver not login go to DriverLogin Activity
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}
/*} else {
startActivity(new Intent(Splashscreen.this, MainActivity.class));
finish();
}*/
}
}, SPLASH_TIME_OUT);
}
}
Make sure your shared preferences is initialised before query. Put a breakpoint and debug.
you user_details shared preference is null..
in your Splash Activity:
initialize it like:
Userloginsession session = new Userloginsession(Splashscreen.this);
if (session.isuserLoggedIn()) {
First create a seperate Preference class
PrefManager.java
package name;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import java.util.HashMap;
/**
* Created by Ravi on 08/07/15.
*/
public class PrefManager {
// Shared Preferences
SharedPreferences pref;
// Editor for Shared preferences
Editor editor;
// Context
Context _context;
// Shared pref mode
int PRIVATE_MODE = 0;
// Shared preferences file name
private static final String PREF_NAME = "MegaInfomatix";
// All Shared Preferences Keys
private static final String KEY_IS_WAITING_FOR_SMS = "IsWaitingForSms";
private static final String KEY_MOBILE_NUMBER = "mobile_number";
private static final String KEY_IS_LOGGED_IN = "isLoggedIn";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_MOBILE = "mobile";
public PrefManager(Context context) {
this._context = context;
pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
editor = pref.edit();
}
public void setIsWaitingForSms(boolean isWaiting) {
editor.putBoolean(KEY_IS_WAITING_FOR_SMS, isWaiting);
editor.commit();
}
public boolean isWaitingForSms() {
return pref.getBoolean(KEY_IS_WAITING_FOR_SMS, false);
}
public void setMobileNumber(String mobileNumber) {
editor.putString(KEY_MOBILE_NUMBER, mobileNumber);
editor.commit();
}
public String getMobileNumber() {
return pref.getString(KEY_MOBILE_NUMBER, null);
}
public void createLogin(String name, String email, String mobile) {
editor.putString(KEY_NAME, name);
editor.putString(KEY_EMAIL, email);
editor.putString(KEY_MOBILE, mobile);
editor.putBoolean(KEY_IS_LOGGED_IN, true);
editor.commit();
}
public boolean isLoggedIn() {
return pref.getBoolean(KEY_IS_LOGGED_IN, false);
}
public void clearSession() {
editor.clear();
editor.commit();
}
public HashMap<String, String> getUserDetails() {
HashMap<String, String> profile = new HashMap<>();
profile.put("name", pref.getString(KEY_NAME, null));
profile.put("email", pref.getString(KEY_EMAIL, null));
profile.put("mobile", pref.getString(KEY_MOBILE, null));
return profile;
}
}
do this in LoginActivity class and in onCreate method
before onCreate method create preference class object
Preference pref;
pref = new PrefManager(this);
if (pref.isLoggedIn()) {
Intent intent = new Intent(SmsActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
}

convert protobuff class as model and store its value using realm

I am generating protobuf class using Squareup Wire protobuf libary
here is my proto file
syntax = "proto2";
package squareup.dinosaurs;
option java_package = "com.squareup.dinosaurs";
message Dinosaur {
// Common name of this dinosaur, like "Stegosaurus".
optional string name = 1;
// URLs with images of this dinosaur.
repeated string picture_urls = 2;
}
and here is my auto generated code
// Code generated by Wire protocol buffer compiler, do not edit.
// Source file: dinosaur/dinosaur.proto at 8:1
package com.squareup.dinosaurs;
import com.squareup.wire.FieldEncoding;
import com.squareup.wire.Message;
import com.squareup.wire.ProtoAdapter;
import com.squareup.wire.ProtoReader;
import com.squareup.wire.ProtoWriter;
import java.io.IOException;
import java.lang.Object;
import java.lang.Override;
import java.lang.String;
import java.lang.StringBuilder;
import java.util.List;
import okio.ByteString;
public final class Dinosaur extends Message<Dinosaur, Dinosaur.Builder> {
public static final ProtoAdapter<Dinosaur> ADAPTER = new ProtoAdapter<Dinosaur>(FieldEncoding.LENGTH_DELIMITED, Dinosaur.class) {
#Override
public int encodedSize(Dinosaur value) {
return (value.name != null ? ProtoAdapter.STRING.encodedSizeWithTag(1, value.name) : 0)
+ ProtoAdapter.STRING.asRepeated().encodedSizeWithTag(2, value.picture_urls)
+ value.unknownFields().size();
}
#Override
public void encode(ProtoWriter writer, Dinosaur value) throws IOException {
if (value.name != null) ProtoAdapter.STRING.encodeWithTag(writer, 1, value.name);
if (value.picture_urls != null) ProtoAdapter.STRING.asRepeated().encodeWithTag(writer, 2, value.picture_urls);
writer.writeBytes(value.unknownFields());
}
#Override
public Dinosaur decode(ProtoReader reader) throws IOException {
Builder builder = new Builder();
long token = reader.beginMessage();
for (int tag; (tag = reader.nextTag()) != -1;) {
switch (tag) {
case 1: builder.name(ProtoAdapter.STRING.decode(reader)); break;
case 2: builder.picture_urls.add(ProtoAdapter.STRING.decode(reader)); break;
default: {
FieldEncoding fieldEncoding = reader.peekFieldEncoding();
Object value = fieldEncoding.rawProtoAdapter().decode(reader);
builder.addUnknownField(tag, fieldEncoding, value);
}
}
}
reader.endMessage(token);
return builder.build();
}
#Override
public Dinosaur redact(Dinosaur value) {
Builder builder = value.newBuilder();
builder.clearUnknownFields();
return builder.build();
}
};
private static final long serialVersionUID = 0L;
public static final String DEFAULT_NAME = "";
/**
* Common name of this dinosaur, like "Stegosaurus".
*/
public final String name;
/**
* URLs with images of this dinosaur.
*/
public final List<String> picture_urls;
public Dinosaur(String name, List<String> picture_urls) {
this(name, picture_urls, ByteString.EMPTY);
}
public Dinosaur(String name, List<String> picture_urls, ByteString unknownFields) {
super(unknownFields);
this.name = name;
this.picture_urls = immutableCopyOf("picture_urls", picture_urls);
}
#Override
public Builder newBuilder() {
Builder builder = new Builder();
builder.name = name;
builder.picture_urls = copyOf("picture_urls", picture_urls);
builder.addUnknownFields(unknownFields());
return builder;
}
#Override
public boolean equals(Object other) {
if (other == this) return true;
if (!(other instanceof Dinosaur)) return false;
Dinosaur o = (Dinosaur) other;
return equals(unknownFields(), o.unknownFields())
&& equals(name, o.name)
&& equals(picture_urls, o.picture_urls);
}
#Override
public int hashCode() {
int result = super.hashCode;
if (result == 0) {
result = unknownFields().hashCode();
result = result * 37 + (name != null ? name.hashCode() : 0);
result = result * 37 + (picture_urls != null ? picture_urls.hashCode() : 1);
super.hashCode = result;
}
return result;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
if (name != null) builder.append(", name=").append(name);
if (picture_urls != null) builder.append(", picture_urls=").append(picture_urls);
return builder.replace(0, 2, "Dinosaur{").append('}').toString();
}
public static final class Builder extends com.squareup.wire.Message.Builder<Dinosaur, Builder> {
public String name;
public List<String> picture_urls;
public Builder() {
picture_urls = newMutableList();
}
/**
* Common name of this dinosaur, like "Stegosaurus".
*/
public Builder name(String name) {
this.name = name;
return this;
}
/**
* URLs with images of this dinosaur.
*/
public Builder picture_urls(List<String> picture_urls) {
checkElementsNotNull(picture_urls);
this.picture_urls = picture_urls;
return this;
}
#Override
public Dinosaur build() {
return new Dinosaur(name, picture_urls, buildUnknownFields());
}
}
}
now the issue is i want to directly store the value of Dinosaur into the database using Realm in android. i want Dinosaur class to act as a model.
but the problem is Dinosaur class is declared as final so i cant even derive it.
So is there any design pattern or way that exists to reuse or convert Dinosaur class into model?
You cannot use the Wire Dinosaur with Realm as Wire also require you to extend the Message class, while Realm require you to extend RealmObject.
If you want to combine the two you can create a RealmDinosaur class that accept the wire Dinosaur. Something like this:
public class RealmDinosaur extends RealmObject {
private String name;
private RealmList<RealmString> pictureUrls;
public RealmDinosaur(Dinosaur dino) {
// Fill Realm fields. Note that Realm doesn't support Lists
// with primitive strings yet.
// See https://realm.io/docs/java/latest/#primitive-lists
}
// getter and setters
}
realm.beginTransaction();
realm.copyToRealm(new RealmDinosaur(wireDinosaur));
realm.commitTransaction();
Short answer: no.
For me, this is one of several show-stoppers for wide adoption of Realm.
The developers of Realm don't seem to have considered real-world use-cases such as yours, where your data objects already inherit from something.
They also seem don't seem to get Android's threading requirements.
If you really want to use Realm, I think that you'll have to create another set of objects, likely in another package, that you only use with Realm. Then, you'd have to copy your data from your 'real' objects into the Realm objects.
Personally, for anything non-trivial, I'd either use the built-in SQLite, or find another database that better meets your needs.

Store more than one value in Android app preferences using the same key

I'm not so sure on how can I store more than one value in shared preferences on an Android app using the same key.
What the app do is show a list and a button to add that item to favorites I want to store that numeric value to preferences and when the user go to the favorite list send all the stored favorites through http post in an array.
EDIT: I'm doing it this way but when I add a new value it overrides the last one, check implode method, I add the new value to the stored list empty or not it has to add the new value and preserve the last ones.
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;
public class FavoriteActivity {
private static String FAVORITE_LIST = "FAV_LIST";
private static SharedPreferences sharedPreference;
private static Editor sharedPrefEditor;
public static List<NameValuePair> getFavoriteList(Context context) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
String storedList = sharedPreference.getString(FAVORITE_LIST, "");
return explode(storedList);
}
public static void saveFavorite(String fav, Context context) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
sharedPrefEditor = sharedPreference.edit();
implode(getFavoriteList(context), fav, 1);
sharedPrefEditor.putString(FAVORITE_LIST, fav);
sharedPrefEditor.commit();
}
public static List<NameValuePair> explode(String string) {
StringTokenizer st = new StringTokenizer(string, ",");
List<NameValuePair> v = new ArrayList<NameValuePair>();
for (; st.hasMoreTokens();) {
v.add(new BasicNameValuePair("id[]", st.nextToken()));
}
return v;
}
public static String implode(List<NameValuePair> list, String value,
int mode) {
StringBuffer out = new StringBuffer();
switch (mode) {
case 0:
list.remove(new BasicNameValuePair("id[]", value));
break;
case 1:
list.add(new BasicNameValuePair("id[]", value));
break;
}
boolean first = true;
for (NameValuePair v : list) {
if (first)
first = false;
else
out.append(",");
out.append(v.getValue());
}
return out.toString();
}
}
You can't do this. If you use the same key anywhere, it will overwrite the previous value.
Perhaps you could convert your values into an array and store the array, or maybe look into using an SQLite database, in which you can specify the keys in one column, and the corresponding value in another and then run a SELECT statement that selects all rows with the key in it.
Since api 11 you can put StringSet. Another way is not possible.
OK, this is the way I did it and works perfect, also it doesn't add any duplicates.
private static String FAVORITE_LIST = "FAV_LIST";
private static SharedPreferences sharedPreference;
private static Editor sharedPrefEditor;
public static List<NameValuePair> getFavoriteList(Context context) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
String storedList = sharedPreference.getString(FAVORITE_LIST, "");
return explode(storedList);
}
public static void saveFavorite(String fav, Context context) {
modifyFavorite(fav, context, 1);
}
public static void removeFavorite(String fav, Context context) {
modifyFavorite(fav, context, 0);
}
private static void modifyFavorite(String fav, Context context, int mode) {
if (sharedPreference == null) {
sharedPreference = PreferenceManager
.getDefaultSharedPreferences(context);
}
sharedPrefEditor = sharedPreference.edit();
String newList = implode(getFavoriteList(context), fav, mode);
sharedPrefEditor.putString(FAVORITE_LIST, newList);
sharedPrefEditor.commit();
}
private static List<NameValuePair> explode(String string) {
StringTokenizer st = new StringTokenizer(string, ",");
List<NameValuePair> v = new ArrayList<NameValuePair>();
for (; st.hasMoreTokens();) {
v.add(new BasicNameValuePair("id[]", st.nextToken()));
}
return v;
}
private static String implode(List<NameValuePair> list, String value,
int mode) {
StringBuffer out = new StringBuffer();
switch (mode) {
case 0:
list.remove(new BasicNameValuePair("id[]", value));
break;
case 1:
list.add(new BasicNameValuePair("id[]", value));
break;
}
boolean first = true;
for (NameValuePair v : list) {
if (out.lastIndexOf(v.getValue()) == -1) {
if (first) {
first = false;
} else {
out.append(",");
}
out.append(v.getValue());
}
}
return out.toString();
}

Information on setters and getters

I am learning extensively about getters and setters but I seem not to be having my way.
I have a class called Apps_Info which contains my setters and getters and I have my main activity FavouriteApps that has a list which uses the class Apps_Info.
I am trying to get the name of the package from the List in FavouriteApps but I am still getting null.
Please can someone tell what to do? Below is the code in this order: class Apps_Info and FavouriteApps activity
public class Apps_Info {
private Bitmap bIcon;
private String sName;
private String sPacks_Name;
public Apps_Info(Bitmap icon, String name, String Packs_Name) {
bIcon = icon;
sName = name;
sPacks_Name = Packs_Name;
}
public void setIcon(Bitmap icon) {
bIcon=icon;
}
public Bitmap getIcon() {
return bIcon;
}
public void setName(String name) {
sName=name;
}
public String getName() {
return sName;
}
public void setPacks_Name(String Packs_Name) {
this.sPacks_Name=Packs_Name;
}
public String getPacks_Name() {
return sPacks_Name;
}
}
FavouriteApps Activity code (part)
String packname, packsname, apps_names;
Bitmap app_icon;
Resources res = getResources();
List<Apps_Info> ListApps_Info = new ArrayList<Apps_Info>();
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.browser_app), "Browser", "com.browser"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.clock_app), "Alarm Clock", "com.alarm.clock"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.threegplus), "3G Secure Connection", "threeg.secureconnect"));
mGridView.setAdapter(new Apps_Info_Adapter(this, ListApps_Info));
Apps_Info packinfo = new Apps_Info(app_icon, apps_names, packname);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");
You should do like this.
for (int i = 0; i < ListApps_Info.size(); i++) {
Apps_Info packinfo = ListApps_Info.item(i);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");
}
It's because you never initialize the packname variable in your code.
String packname,packsname,apps_names;
When you do this :
Apps_Info packinfo=new Apps_Info(app_icon, apps_names,packname);
packsname=packinfo.getPacks_Name();
your getter is doing well and this is normal if it returns null.

Categories

Resources