开发者

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

开发者 https://www.devze.com 2023-02-28 09:01 出处:网络
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.

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 met开发者_如何转开发hod:

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?


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()


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


int var=getX();

Something like that should work...


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号