I am developing a BlackBerry application. I want to store the details of multiple users in my mobile. I have to store data like username, first name, last name ,email id ,phone number for each user. Can any one please provide me a sample code for persistent store using which I can store all this data in a vector and retrieve later.
This link should answer most of what you need to know - http://www.miamicoder.com/post/2010/04/13/How-to-Save-BlackBerry-Application-Settings-in-the-Persistent-Store.aspx.
Below is some code from one of my projects.
public class PreferencesStore
{
// Not a real key, replace it with your own.
private static long m_lTabulaRectaKey = 0l;
public static Vector getTabulaRectas()
{
Vector vecTabulaRectas = new Vector();
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
if(poObject.getContents() != null)
{
vecTabulaRectas = (Vector)poObject.getContents();
}
return vecTabulaRectas;
}
public static void addTabulaRecta(TabulaRecta a_oTabulaRecta)
{
Vector vecTabulaRectas = getTabulaRectas();
vecTabulaRectas.addElement(a_oTabulaRecta);
PersistentObject poObject = PersistentStore.getPersistentObject(m_lTabulaRectaKey);
poObject.setContents(vecTabulaRectas);
poObject.commit();
}
}
Related
I'm writing a bank payment app using Xamarin android that store user card information.
I'm looking for a safe and secure for storing data.
the only thing I found is below link that store account information which is useless for me:
https://developer.xamarin.com/recipes/cross-platform/xamarin-forms/general/store-credentials/
KeyStore is the most secure way to store sensitive data on Android. You can store there anything, if it can be serialized it to string.
For example, you can use free library KeyChain.Net that provides clear API for saving and retreading data from Android and iOS KeyStores.
If you want to save Class with account information and credit card number, you can serealize that class using JSON Newtonsoft.Json
using System;
using Newtonsoft.Json;
public class Account
{
public string user_id;
public string credit_card_number;
public override string ToString () {
return JsonConvert.SerializeObject (this);
}
}
Save Account:
string accountKey ="secure_key";
public static bool SaveAccount (Account account) {
KeyChainHelper keyChainHelper = new KeyChainHelper ();
return keyChainHelper.SetKey (accountKey, account.ToString ());
}
Get Account:
public static Account GetSavedAccount () {
KeyChainHelper keyChainHelper = new KeyChainHelper ();
string jsonAccount = keyChainHelper.GetKey (accountKey);
if (jsonAccount == null || jsonAccount == "") {
return null;
}
Account user = JObject.Parse (jsonAccount).ToObject<Account> ();
return account;
}
I have a BlackBerry Application that sends messages to a server at fixed intervals. The messages are sent via web service using any of the connection methods available; Wifi, BIS, TCP/IP etc.
Since the messages are being sent continuously, I need a mechanism to queue the messages in case internet is not available and send the messages across when internet becomes available. For that reason, I wish to first save any outgoing message in the Persistent Store and then read the Persistent Store and loop through it to send all pending messages. Any new message should be saved at the last spot in the Persistent Store.
I am calling the two methods below when "Send" is clicked:
public static void saveMessage(String msg){
Hashtable hashtable=new Hashtable();
persistentObject = PersistentStore.getPersistentObject(KEY);
hashtable.put("MessageToSend", msg);
persistentObject.commit();
}
public static void sendMessage(String msg){
Hashtable hashtable=new Hashtable();
persistentObject = PersistentStore.getPersistentObject(KEY);
Vector msgVector = (Vector)persistentObject.getContents();
Enumeration eMsgs=msgVector.elements();;
/*synchronized(poObject )*/{
persistentObject.setContents(msgVector);
persistentObject.commit();
}
int i=0;
while(eMsgs.hasMoreElements()){
hashtable=(Hashtable)eMsgs.nextElement();
String encryptedMessage=(String)hashtable.get("MessageToSend");
if(!encryptedMessage.equals("")){
//check internet connection
String C0NNECTION_EXTENSION = checkInternetConnection();
if(C0NNECTION_EXTENSION==null)
{
Dialog.alert("Check internet connection and try again");
return;
}
else
{
MyScreen.PostMsgToServer(encryptedMessage);
hashtable.remove(encryptedMessage);
}
}
i++;
}
}
This is just an attempt from the tutorials/examples that I came across. Kindly help.
The save method you show is not actually putting the hashtable into the PersistentObject. Try something like this instead:
public static void saveMessage(String msg){
Hashtable hashtable = new Hashtable();
persistentObject = PersistentStore.getPersistentObject(KEY);
hashtable.put("MessageToSend", msg);
persistentObject.setContents(hashtable); // <- you were missing this
persistentObject.commit();
}
That's still probably not a great implementation, because I'm assuming that you might want to call saveMessage() multiple times, and add more than one message to the persistent store (?). Is that right, or can you only ever have one message saved? (if that's true, you can ignore this next suggestion for saveMessage())
public static void saveMessage(String msg){
persistentObject = PersistentStore.getPersistentObject(KEY);
Hashtable hashtable = (Hashtable) persistentObject.getContents();
if (hashtable == null) {
// lazily initialize the store contents
hashtable = new Hashtable();
hashtable.put("MessagesToSend", new Vector());
}
Vector queuedMessages = (Vector) hashtable.get("MessagesToSend");
queuedMessages.addElement(msg);
// write the store contents to device storage
persistentObject.setContents(hashtable);
persistentObject.commit();
}
/**
* #param msg TODO: I'm not sure why msg needs to be passed, if
* saveMessage(msg) was called first?
*/
public static void sendMessage(String msg){
// TODO: you could choose to save the message here, so that the caller
// need not remember to call both sendMessage() and saveMessage()
// saveMessage(msg);
persistentObject = PersistentStore.getPersistentObject(KEY);
Hashtable hashtable = (Hashtable) persistentObject.getContents();
if (hashtable != null) {
// check for saved messages first, and send them
Vector msgVector = (Vector) hashtable.get("MessagesToSend");
Enumeration eMsgs = msgVector.elements();
Vector toDelete = new Vector();
while (eMsgs.hasMoreElements()) {
String encryptedMessage = (String)eMsgs.nextElement();
// if the send was successful, you should delete message from the store
toDelete.addElement(encryptedMessage);
}
eMsgs = toDelete.elements();
while (eMsgs.hasMoreElements()) {
// we can delete this sent message now
msgVector.removeElement((String)eMsgs.nextElement());
}
// re-write the persistent store to the device
persistentObject.setContents(hashtable);
persistentObject.commit();
}
}
I'd also generally like to steer you away from making everything static ... that said, that's really a bigger, unrelated issue here, and it does happen that your persistent store object is likely to be a unique, global object in your application (a better implementation, however, would probably avoid all these static declarations).
Update: I'm a little unclear as to how you expect to call these two methods. Based on your description, it seems that you call both saveMessage(msg) and then sendMessage(msg) when Send is clicked by the user. If you save the message first, with my implementation, then there is no need to pass msg in to sendMessage(), since sendMessage() will send out all saved, unsent messages in the queue (vector). So, the API for sendMessage() has an unnecessary parameter. Or, I supposed you could leave sendMessage(String) as the only public method, and have sendMessage(String) first call saveMessage(String).
In any case, that's up to you, and how you want your method calling semantics to work. The basic problem of storing and retrieving persistent objects should be addressed by the code above.
I am using persistent object in blackberry to store config details specific to the app. Here is how I am implementing the class
public class Preferences implements Persistable
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static Hashtable tbl = new Hashtable();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
Hashtable tbl = (Hashtable)persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
But if I uninstall/delete the app these stored values are not getting deleted. When I installs the app for next time the app is fetching the old stored values.
How can i do this properly in blackberry?
Thanks
Create a custom hashtable class like this
package com.myapp.items;
import net.rim.device.api.util.Persistable;
import java.util.*;
public class MyAppHashtable extends Hashtable implements Persistable{
}
And change your code to
public class Preferences
{
private static PersistentObject persistentObject = PersistentStore.getPersistentObject(0x2759d6ff72264bdbL);
private static MyAppHashtable tbl = new MyAppHashtable ();
public static void storeLoginToken(String token)
{
token = removeCharAt(token,0);
token = removeCharAt(token,token.length()-1);
tbl.put("token", token);
persistentObject.setContents(tbl);
persistentObject.commit();
}
public static String getLoginToken()
{
MyAppHashtable tbl = (MyAppHashtable )persistentObject.getContents();
try
{
String token = tbl.get("token").toString();
System.out.println("Token = "+token);
return token;
}
catch(Exception e)
{
return null;
}
}
}
This is so that we adhere to the following info from RIM
The BlackBerry persistence model
When you use the BlackBerry persistence model, data is only deleted if the store contains data that belongs to the removed application.
For example, if an application stores an object with a package called com.mycompany.application.storage and no other application on the BlackBerry smartphone makes reference to the package, the persistent store and the removed application are deleted.
The same is true if the object is wrapped in a container such as a Vector. Even if only one of the elements of the Vector has a package name that is not used by other applications, the entire Vector is removed from the persistent store.
Note: If the application does not store any objects with an identifying package structure, (for example, an application that stores java.util.Vector or javax.microedition.location.AddressInfo objects), the application should create and use a class that extends Vector in order to identify that Vector belongs to the given application. When you store this Vector, which is identified uniquely by its package, you guarantee that the data is removed from the persistent store when the application is removed.
This info is from here
I have developed an application. I want to display a message before the user starts implementing my application. Like when it is used first time i want to show "Count = 1". And when app is visited second time, "Count = 2".
How can i achieve it? I had done such thing in android using sharedperferences. But how can i do it in blackberry. I had tried something with PersistentStore. But cant achieve that, for i dont know anything about the Persistance in BB.
Also i would wish to restrict the use for 100. Is it possible?
sample codes for this will be appreciable, since i am new to this environment..
You can achieve it with Persistent Storage.
Check this nice tutorial about storing persistent data.
Also you can use SQLite. Link to a development guide which describes how to use SQLite databases in Java® applications: Storing data in SQLite databases.
You can restrict user for trying your application at most 100 times using your own logic with the help of persistent data. But I think there may be some convention, so try Google for that.
got it...
I created a new class which implements Persistable. In that class i had created an integer variable and set an getter and setter function for that integer...
import net.rim.device.api.util.Persistable;
public class Persist implements Persistable
{
private int first;
public int getCount()
{
return first;
}
public void setCount()
{
this.first += 1;
}
}
Then in the class which initializes my screen, i had declared persistence variables and 3 functions to use my Persist.java, initStore(), savePersist(), and getPersist()
public final class MyScreen extends MainScreen implements FieldChangeListener
{
/*
* Declaring my variables...
*/
private static PersistentObject store;
public Persist p;
public MyScreen()
{
//my application codes
//here uses persistence
initStore();
p = getPersist();
if(p.getCount()<100)
{
savePersist();
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
Dialog.alert(p.getCount.toString());
}
});
}
else
{
close();
System.exit(0);
}
}
//three function....
public static void initStore()
{
store = PersistentStore.getPersistentObject(0x4612d496ef1ecce8L);
}
public void savePersist()
{
synchronized (store)
{
p.setCount();
store.setContents(p);
store.commit();
}
}
public Persist getPersist()
{
Persist p = new Persist();
synchronized(store)
{
p = (Persist)store.getContents();
if(p==null)
{
p = new Persist();
}
}
return p;
}
}
I hope u all will get it right now....
If there are another simple way, plz let me know...
Thanks
I need to create an application,that should contain two storage,one is persistent storage and another one is cache storage.After loading, the application should check the username and password with the cache storage data if it is empty then it should check with the persistent storage.How to accomplish this task?Is there any separate concept of cache or we have create the persistent as cache.please help me.
You can use RecordStore which is also persistent, or RuntimeStore which is shared between all apps but is non persistent.
Alternatively you can use some custom storage class to implement cache functionality,
storing, updating values in that class, sharing it as a field of Application class:
class Cache {
String mName = null;
String mPhone = null;
}
public class CacheApp extends UiApplication {
Cache mCache = null;
public static void main(String[] args) {
CacheApp app = new CacheApp();
app.enterEventDispatcher();
}
public CacheApp() {
initCache();
CacheScr scr = new CacheScr();
pushScreen(scr);
}
private void initCache() {
mCache = new Cache();
mCache.mName = "Name";
mCache.mPhone = "Phone";
}
}
class CacheScr extends MainScreen {
public CacheScr() {
CacheApp app = (CacheApp) UiApplication.getUiApplication();
String name = app.mCache.mName;
String phone = app.mCache.mPhone;
}
}
Coldice is correct, however I fail to see why one would use a store separate from PersistentStore (or RecordStore) for data that must endure and may be shared, and RuntimeStore for data which is shared but not durable. This just seems to be adding complexity to normal application transient storage.