简体   繁体   中英

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?

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

这样的事情应该起作用...

int iMyValue = getX();

创建具有相同数据类型(在这种情况下为整数)的变量,然后使用“ =”赋值运算符为其分配值。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM