'How to set values of global variable inside inner interface and use the values outside of the interface in adnroid
Is there any way to set value of global variable inside an interface and use the value outside of it?
Here is sample of my code:
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);
}
}
Solution 1:[1]
You can't use the list directly after the get()
call, because the get call is async and has not yet finished.
You can create a method outside the interface that takes the list as a parameter:
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
}
Or you can use method-reference:
public static void main(String[] args) {
get(<your class>::doSomethingWithList);
}
private static void doSomethingWithList(List<Sting> list){
//you code here
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |