gpt4 book ai didi

java - 变量作用域[JAVA]

转载 作者:行者123 更新时间:2023-12-01 07:54:16 24 4
gpt4 key购买 nike

在 if 语句中记录时,我可以成功获取“startTime”变量的值。当我尝试从 if 语句外部访问此变量时,我的问题就出现了。

public class MainActivity extends AppCompatActivity {
String startTime = "";
String endTime = "";
....
....
....
public void dailyHours(){
//Retrieve clockInId (ObjectID for clockInTime)
ParseQuery<ParseObject> startQuery = ParseQuery.getQuery("clockIn");
startQuery.getInBackground(clockInId, new GetCallback<ParseObject>() {
public void done(ParseObject clockIn, ParseException e) {
if (e == null) {
startTime = clockIn.getString("Time");
Log.d(TAG, "StartTime: " + startTime);
} else {
// something went wrong
}
}
});

//Retrieve clockOutId (ObjectID for clockOutTime)
ParseQuery<ParseObject> endQuery = ParseQuery.getQuery("clockOut");
endQuery.getInBackground(clockOutId, new GetCallback<ParseObject>() {
public void done(ParseObject clockOut, ParseException e) {
if (e == null) {
endTime = clockOut.getString("Time");
Log.d(TAG, "EndTime: " + endTime);
} else {
// something went wrong
}
}
});

}

例如,当 Log.d() 移至 ParseQuery 外部时,startTime 返回空。

public void dailyHours(){
//Retrieve clockInId (ObjectID for clockInTime)
ParseQuery<ParseObject> startQuery = ParseQuery.getQuery("clockIn");
startQuery.getInBackground(clockInId, new GetCallback<ParseObject>() {
public void done(ParseObject clockIn, ParseException e) {
if (e == null) {
startTime = clockIn.getString("Time");
} else {
// something went wrong
}
}
});
Log.d(TAG, "StartTime: " + startTime); //startTime returns an empty string when moved here.

最佳答案

GetCallback<ParseObject>()方法是异步调用的(在另一个线程中),所以实际上赋值 startTime = clockIn.getString("Time")可以在Log.d(TAG, "StartTime: " + startTime)之后执行.

这里有“竞争条件”。

关于java - 变量作用域[JAVA],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32260981/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com