我目前有一個活動,我需要從Parse數據庫中獲取數據。僅當本地數據存儲區爲空時才應該執行提取。我試圖創建一個asynctask以及使用if-else塊,但是,在獲取數據之前,控件跳轉到下一行代碼,導致應用程序崩潰。我該如何做到這一點? 下面的代碼:如何在跳轉到下一行代碼之前完全執行一個方法?
public class Splash extends AppCompatActivity {
ArrayList<String> Titles = new ArrayList<>();
ArrayList<String> Descriptions = new ArrayList<>();
ArrayList<String> VideoIDs = new ArrayList<>();
ArrayList<String> FullUrls = new ArrayList<>();
ArrayList<String> IDsForYTsdk = new ArrayList<>();
String lang, objCode;// englishObject, hindiObject ;
Intent intent;
Firebase myFirebaseRef;
ParseQuery<ParseObject> query = ParseQuery.getQuery("class");
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
Window window = getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.setStatusBarColor(Color.parseColor("#512DA8"));
}
checkFirstRun() /if first run, fetch from database
try {
FileInputStream fis = openFileInput(getResources().getString(R.string.FILENAME));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String c;
lang = "";
while ((c = br.readLine()) != null) {
lang = lang + c;
}
br.close();
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
intent = new Intent(Splash.this, MainActivity.class);
Thread timer = new Thread() {
@Override
public void run() {
super.run();
//final ParseQuery<ParseObject> query = ParseQuery.getQuery("class"); //GET PARSEOBJECTS LIST FROM SERVER
try {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
//query.fromLocalDatastore(); //so user doesnt have to wait
query.whereExists("youtube_id");
query.setLimit(30);
query.orderByDescending("updatedAt");
if (lang.equals("en"))
query.whereEqualTo("language", "en");
else if (lang.equals("hi"))
query.whereEqualTo("language", "hi");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> idList, ParseException e) {
if (e == null) {
for (int i = 0; i < idList.size(); i++) {
Titles.add(i, idList.get(i).get("video_title").toString());
Descriptions.add(i, idList.get(i).get("video_script").toString());
VideoIDs.add(i, "https://www.youtube.com/embed/" + idList.get(i).get("youtube_id").toString() + "?rel=0&controls=0&showinfo=0&autoplay=1&modestbranding=1");
IDsForYTsdk.add(i, YouTubeUrlParser.getVideoId(VideoIDs.get(i)));
FullUrls.add(i, "https://youtu.be/" + IDsForYTsdk.get(i));
}
//Toast.makeText(getApplicationContext(), "IDs weren't same", Toast.LENGTH_SHORT).show();
intent.putStringArrayListExtra("titles", Titles);
intent.putStringArrayListExtra("descs", Descriptions);
intent.putStringArrayListExtra("videoIds", VideoIDs);
intent.putStringArrayListExtra("idsForSDK", IDsForYTsdk);
intent.putStringArrayListExtra("links", FullUrls);
ParseObject.unpinAllInBackground("objectsID", idList, new DeleteCallback() {
public void done(ParseException e) {
if (e != null) {
return;
}
ParseObject.pinAllInBackground(idList);
}
});
startActivity(intent);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Couldn't fetch data", Toast.LENGTH_SHORT).show();
}
}
});
} else {
query.fromLocalDatastore();
query.orderByDescending("updatedAt");
if (lang.equals("en"))
query.whereEqualTo("language", "en");
else if (lang.equals("hi"))
query.whereEqualTo("language", "hi");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> idList, ParseException e) {
if (e == null) {
for (int i = 0; i < idList.size(); i++) {
Titles.add(i, idList.get(i).get("video_title").toString());
Descriptions.add(i, idList.get(i).get("video_script").toString());
VideoIDs.add(i, "https://www.youtube.com/embed/" + idList.get(i).get("youtube_id").toString() + "?rel=0&controls=0&showinfo=0&autoplay=1");
IDsForYTsdk.add(i, YouTubeUrlParser.getVideoId(VideoIDs.get(i)));
FullUrls.add(i, "https://youtu.be/" + IDsForYTsdk.get(i));
}
intent.putStringArrayListExtra("titles", Titles);
intent.putStringArrayListExtra("descs", Descriptions);
intent.putStringArrayListExtra("videoIds", VideoIDs);
intent.putStringArrayListExtra("links", FullUrls);
intent.putStringArrayListExtra("idsForSDK", IDsForYTsdk);
//intent.putStringArrayListExtra("language", Language);
Toast.makeText(getApplicationContext(), "Fetched saved data", Toast.LENGTH_SHORT).show();
startActivity(intent);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Couldn't fetch saved data", Toast.LENGTH_SHORT).show();
}
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
timer.start();
}
public void checkFirstRun() {
boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE).getBoolean("isFirstRun", true);
if (isFirstRun) {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
try {
FileOutputStream fos = openFileOutput(getResources().getString(R.string.FILENAME), Context.MODE_PRIVATE);
fos.write(getResources().getString(R.string.ENGLISH).getBytes());
fos = openFileOutput(getResources().getString(R.string.storeEnObjFile), Context.MODE_PRIVATE);
fos.write(getResources().getString(R.string.objEN).getBytes());
fos = openFileOutput(getResources().getString(R.string.storeHiObjFile), Context.MODE_PRIVATE);
fos.write(getResources().getString(R.string.objHI).getBytes());
fos.close();
//Toast.makeText(this, "File created", Toast.LENGTH_SHORT).show();
setUpAppOnFirstLaunch();
FirebaseCode();
} catch (Exception fne) {
fne.printStackTrace();
}
getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.edit()
.putBoolean("isFirstRun", false)
.apply();
} else {
Toast.makeText(this, "Please connect to a network and try again.", Toast.LENGTH_LONG).show();
finish();
}
}
}
private void setUpAppOnFirstLaunch() {
query.whereExists("youtube_id");
query.setLimit(30);
query.orderByDescending("updatedAt");
if (lang.equals("en"))
query.whereEqualTo("language", "en");
else if (lang.equals("hi"))
query.whereEqualTo("language", "hi");
query.findInBackground(new FindCallback<ParseObject>() {
public void done(final List<ParseObject> idList, ParseException e) {
if (e == null) {
for (int i = 0; i < idList.size(); i++) {
Titles.add(i, idList.get(i).get("video_title").toString());
Descriptions.add(i, idList.get(i).get("video_script").toString());
VideoIDs.add(i, "https://www.youtube.com/embed/" + idList.get(i).get("youtube_id").toString() + "?rel=0&controls=0&showinfo=0&autoplay=1");
IDsForYTsdk.add(i, YouTubeUrlParser.getVideoId(VideoIDs.get(i)));
FullUrls.add(i, "https://youtu.be/" + IDsForYTsdk.get(i));
}
//Toast.makeText(getApplicationContext(), "IDs weren't same", Toast.LENGTH_SHORT).show();
intent.putStringArrayListExtra("titles", Titles);
intent.putStringArrayListExtra("descs", Descriptions);
intent.putStringArrayListExtra("videoIds", VideoIDs);
intent.putStringArrayListExtra("links", FullUrls);
intent.putStringArrayListExtra("idsForSDK", IDsForYTsdk);
ParseObject.unpinAllInBackground("objectsID", idList, new DeleteCallback() {
public void done(ParseException e) {
if (e != null) {
return;
}
ParseObject.pinAllInBackground(idList);
}
});
startActivity(intent);
} else {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "Couldn't fetch data", Toast.LENGTH_SHORT).show();
}
}
});
}
如果應用程序崩潰,則包含錯誤日誌。另外,這不是[mcve]。如果你的代碼不同步,或者你沒有正確處理回調,那麼耶代碼將被「跳過」 –