Eric Kong
Eric Kong

Reputation: 31

How to have persistent variable in android module?

I'm planning to create a module whereby information was stored in a variable in my java codes. I've made a simple test app whereby a variable in my java code was incremented by 1 every time a button was pressed. When I tested it out, no matter how many times I press, it returns 1, no increment at all. My java code:

private static int counter = 0;

@Kroll.method
public int increment() {
    setIncrementProp(1);
    return counter;
}

@Kroll.setProperty
public void setIncrementProp(int value) {
    counter = counter + value;
}

My Javascript code:

var module = require("com.modulewhatever");

var testToast = Titanium.UI.createNotification({ message :module.increment().toString() });

var button = Titanium.UI.createButton({ title : "Test" });

button.addEventListener("click", function(e) { testToast.show(); });

Upvotes: 0

Views: 948

Answers (1)

Lucifer
Lucifer

Reputation: 29642

You can use one of a feature called SharedPreference in Android.

SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(context);

p.edit().putString("username", username).commit();
p.edit().putString("password", password).commit(); //SECURITY HAZARD: read below...

for retrieving values,

String username = p.getString("username", "");
String password = p.getString("password", "");

Upvotes: 2

Related Questions