如何在内部接口内设置全局变量的值并在 adnroid 中使用接口外的值
How to set values of global variable inside inner interface and use the values outside of the interface in adnroid
有没有办法在接口内部设置全局变量的值并在接口外部使用该值?
这是我的代码示例:
class A{
static ArrayList<String> myList = new ArrayList<>();
public static void main(String[] args) {
get(new Inter() {
@Override
public void callBack(ArrayList<String> list) {
myList = list; // here list is the textual data from firebase and I want to use it outside
// this get function call
}
});
myList.toString(); // I want to use it here. But its value out of the function call was null
// but it has the same value with list inside the function call
}
static void get(Inter inter){
// here I want to get some textual data from firebase into ArrayList of String
list = array of String from firebase
inter.callBack(list);
}
interface Inter{
void callBack(ArrayList<String> list);
}
}
不能在get()
调用后直接使用列表,因为get调用是异步的,还没有完成。
可以在接口外创建一个方法,将列表作为参数:
public static void main(String[] args) {
get(new Inter() {
@Override
public void callBack(ArrayList<String> list) {
doSomethingWithList(list);
}
});
}
private static void doSomethingWithList(List<Sting> list){
//you code here
}
或者您可以使用 method-reference:
public static void main(String[] args) {
get(<your class>::doSomethingWithList);
}
private static void doSomethingWithList(List<Sting> list){
//you code here
}
有没有办法在接口内部设置全局变量的值并在接口外部使用该值?
这是我的代码示例:
class A{
static ArrayList<String> myList = new ArrayList<>();
public static void main(String[] args) {
get(new Inter() {
@Override
public void callBack(ArrayList<String> list) {
myList = list; // here list is the textual data from firebase and I want to use it outside
// this get function call
}
});
myList.toString(); // I want to use it here. But its value out of the function call was null
// but it has the same value with list inside the function call
}
static void get(Inter inter){
// here I want to get some textual data from firebase into ArrayList of String
list = array of String from firebase
inter.callBack(list);
}
interface Inter{
void callBack(ArrayList<String> list);
}
}
不能在get()
调用后直接使用列表,因为get调用是异步的,还没有完成。
可以在接口外创建一个方法,将列表作为参数:
public static void main(String[] args) {
get(new Inter() {
@Override
public void callBack(ArrayList<String> list) {
doSomethingWithList(list);
}
});
}
private static void doSomethingWithList(List<Sting> list){
//you code here
}
或者您可以使用 method-reference:
public static void main(String[] args) {
get(<your class>::doSomethingWithList);
}
private static void doSomethingWithList(List<Sting> list){
//you code here
}