在跳转到下一行代码之前,如何完全执行方法?

时间:2016-04-03 05:40:43

标签: android parse-platform

我目前有一项活动需要从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&amp;controls=0&amp;showinfo=0&amp;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&amp;controls=0&amp;showinfo=0&amp;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();
                }

            }
        });
}

2 个答案:

答案 0 :(得分:1)

如果您使用的是 AsyncTask ,请覆盖其onPostExecute方法,并在调用完成后放置您想要执行的任何方法。

如果您使用解析后台任务,则覆盖done()方法并放置您想要执行的任何方法。

很难给你一个特定的代码,你的代码......非常混乱,难以阅读。所以请记住以上提示并尝试一下。

答案 1 :(得分:1)

我不知道如果这是正确的方法,但它对我有用。

如果在从AsyncTask完成检​​查后必须执行某些操作

  1. 执行onPostExecute

  2. async Task.()的下一行
  3. 如果您没有访问任何GUI组件,您可以在doOnBackground的末尾写下您必须执行的下一行(即使在您的情况下不会被调用) asyncTask