我等待从Android Java中的线程返回值。下面的代码总是返回null
try {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(TAG, "Getting userprofile");
DataExchange.setContext(getContext());
DataExchange.getUserProfile();
Log.i(TAG, DataExchange.getResult());
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
//e.printStackTrace();
}
}
}).join();
在DataExchange类中,我有下面的getter和setter:
public static void setResult(String result) {
DataExchange.result = result;
}
public static String getResult() {
return DataExchange.result;
}
getResult的获取器总是返回null
答案 0 :(得分:0)
如果尚未初始化,则将收到null 在DataExchange类中,您都应该有类似的内容
class DataExchange {
String result = "Result";
//getters, setters, other methods...
}
或者您应该先获取它的值
try {
new Thread(new Runnable() {
@Override
public void run() {
try {
Log.i(TAG, "Getting userprofile");
DataExchange.setContext(getContext());
DataExchange.getUserProfile();
DataExchange.setResult("Result");
Log.i(TAG, DataExchange.getResult());
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
//e.printStackTrace();
}
}
}).join();
这个概念是任何对象(可能也是原始数据类型)在访问之前都需要初始化,否则将返回null。