Frank
Frank

Reputation: 13

Super Noob Question: Getting a returned integer value from a Method

This is a super noob question... I created a method that gets a sharedpreference and returns it. However, I don't know how to get and use the integer that is returned by the method.

here is the method:

public int getX() {
     return mPrefs.getInt("x", 1);
}

How do I call this method in a way that allows me to get and use that integer value?

Upvotes: 1

Views: 218

Answers (4)

Tobber
Tobber

Reputation: 7531

I expect you're very new to java, so you here comes some basic stuff:


The call depends on where you make the call.

In the same class/object you just write (as Olly and Dalex points out)

int var = getX()

or of course

int var
//...
var = getX()

Outside the object (or in any static method) you need to initialize the object first (as duffymo says)

Preferences prefs = new Preferences(); // Or whatever you class is
int value = prefs.getX();

BUT: are you sure you want the shared preferences to be an Object. It might be easier to keep it static. (If you don't know the difference, static is the way =) ). If it's static, you don't have to initialize the object.

To make the method static simply add static after the public keyword as:

public static int getX() {
    return mPrefs.getInt("x", 1);
}

The calls will then be:

Locally (same class)

int var = getX()

Globally (other classes)

int var = Preferences.getX()

Upvotes: 4

Olly
Olly

Reputation: 21

int iMyValue = getX();

Create a variable with the same data type (integer in this case), then assign a value to it using the '=' assignment operator.

Upvotes: 0

duffymo
duffymo

Reputation: 308848

Instanstiate an instance of the class that owns that method and call it:

Preferences prefs = new Preferences(); // Or whatever you class is
int value = prefs.getX();  // get the value here

Upvotes: 2

Freesnöw
Freesnöw

Reputation: 32143

int var=getX();

Something like that should work...

Upvotes: 0

Related Questions