在if語句內登錄時,我可以成功獲取「startTime」變量的值。當我嘗試從if語句之外訪問此變量時,就會出現我的問題。變量作用域[JAVA]
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以外,開始時間返回空。
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.
本質上,我試圖做的是從解析中檢索兩個對象,然後取兩者的差異。你能指導我正確的方向,以解決我的問題?我怎樣才能確保'startTime'和'endTime'首先被啓動?這樣我就可以回去並改變它。 – jchav
可能的修正之一是添加:'Object timeLock = new Object();'到MainActivity,然後檢查'synchronized(timeLock){if(startTime.length()> 0 && endTime.length()> 0)//計算差異}'每個內部'if(e == null)'block –