简体   繁体   English

如何等待直到异步任务中另一个类的方法在Android中完成

[英]How to wait until method from another class in asynctask finishes in android

I am newbie in AsyncTask, and I got problem. 我是AsyncTask的新手,但遇到了问题。 I have AsyncTask, which saves info in DB by calling function from another class. 我有AsyncTask,它通过从另一个类调用函数将信息保存在DB中。 The problem is that onPostExecute method is calling before my function finishes; 问题在于onPostExecute方法在我的函数完成之前正在调用; Here is my code: 这是我的代码:

class checkNewReviews2 extends AsyncTask<List<ReviewList.ReviewItem>, Void, Void>{


    @Override
    protected Void doInBackground(List<ReviewList.ReviewItem>... reviewList) {

        int size = reviewList[0].size();
        if(size>0) {

            for (int i = 0; i < size; i++) {
                ReviewList.ReviewItem r = reviewList[0].get(i);
                ContentValues c = new ContentValues();
                c.put(LentaClass.LentaListEntry.FILM_ID, r.getFilm_id());
                c.put(LentaClass.LentaListEntry.USER_ID, r.getUser_id());
                c.put(LentaClass.LentaListEntry.REVIEW_TEXT, r.getReview_text());
                c.put(LentaClass.LentaListEntry.CREATED_AT, r.getCreated_at());
                c.put(LentaClass.LentaListEntry.REVIEW_TYPE, r.getReview_type());
                c.put(LentaClass.LentaListEntry.VIEWS, r.getViews());
                sqLiteDatabase.insert(LentaClass.LentaListEntry.TABLE_NAME, null, c);

                c.clear();
            }
            FilmHandler filmHandler = new FilmHandler(getContext());
            filmHandler.HandleFilms(reviewList[0]);
            UserHandler userHandler = new UserHandler(getContext());
            userHandler.HandleUsers(reviewList[0]);


        }
        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);

        initiateRecyclerView();
    }
}

I already tried to put all calls into onPreExecute, but the result is still the same. 我已经尝试将所有调用放入onPreExecute,但是结果仍然相同。 Also as a notice, the first block of sql code (cycle) is succesfully handled, not as Film and User handlers. 还要注意,成功处理了第一段sql代码(循环),而不是将其作为Film和User处理程序。 How should I call initiateRecyclerView after AsyncTask completely executed? 在AsyncTask完全执行后,我该如何调用initiateRecyclerView?

Your doInBackgound() method needs to "wait" for your FilmHandler , UserHandler classes to finish. 您的doInBackgound()方法需要“等待”您的FilmHandlerUserHandler类完成。

My guess is that your classes are working on a background thread so when you use them your code immediately continues to the return null statement - and finishing the background work, causing onPostExecute() to be called. 我的猜测是您的类在后台线程上工作,因此当您使用它们时,代码将立即继续执行return null语句-并完成后台工作,从而导致onPostExecute()

Change your classes implementation to work on the calling thread and not create their own. 更改您的类实现以在调用线程上工作而不创建自己的类。

您是否也可以在doinbackground参数中添加上下文。可能是getcontext返回null / Application Context

onPostExecute will execute only after completion of doInBackground. onPostExecute将仅在doInBackground完成后执行。 If the FilmHandler and Userhandler are implemented on separate thread , it can cause the issue. 如果FilmHandler和Userhandler是在单独的线程上实现的,则可能导致此问题。 So to avoid this,do not use another thread to save data in DB (or) Performing some other sort of operatio instead complete the entire saving data in the doInBackground itself. 因此,为避免这种情况,请勿使用其他线程在DB中保存数据(或)执行其他某种操作,而应在doInBackground本身中完成整个保存数据。

Else there is an another way which also you can archive the functionality. 另外,还有另一种方法可以存档功能。 You need to add a call back for the filmHandler or userHandler functions and check for the update in doinBackground and based on it you can pass the result to PostExcecute() 您需要为filmHandler或userHandler函数添加回调,并在doinBackground中检查更新,然后可以基于该更新将结果传递给PostExcecute()

class checkNewReviews2 extends AsyncTask<List<ReviewList.ReviewItem>, Void, Boolean>{


@Override
protected Void doInBackground(List<ReviewList.ReviewItem>... reviewList) {

    int size = reviewList[0].size();
    if(size>0) {

        for (int i = 0; i < size; i++) {
            ReviewList.ReviewItem r = reviewList[0].get(i);
            ContentValues c = new ContentValues();
            c.put(LentaClass.LentaListEntry.FILM_ID, r.getFilm_id());
            c.put(LentaClass.LentaListEntry.USER_ID, r.getUser_id());
            c.put(LentaClass.LentaListEntry.REVIEW_TEXT, r.getReview_text());
            c.put(LentaClass.LentaListEntry.CREATED_AT, r.getCreated_at());
            c.put(LentaClass.LentaListEntry.REVIEW_TYPE, r.getReview_type());
            c.put(LentaClass.LentaListEntry.VIEWS, r.getViews());
            sqLiteDatabase.insert(LentaClass.LentaListEntry.TABLE_NAME, null, c);

            c.clear();
        }


        FilmHandler filmHandler = new FilmHandler(YourActivity.this);
       boolean filmHandlerState =   filmHandler.HandleFilms(reviewList[0]);
        UserHandler userHandler = new UserHandler(YourActivity.this);
      boolean userHandlerState =   userHandler.HandleUsers(reviewList[0]);



        if(filmHandlerState && userHandlerState )
        {
        return true;
        } 
       else
       {
       return false;
       }
    }
}

@Override
protected void onPostExecute(Void result) {
    super.onPostExecute(result);

      if(result)
     {
       initiateRecyclerView();
     }
     else
     {
      // any one of the filmHandler or userHandler function has failed. so do your handling here 

}

} }

In another point as stated by @user3413619 might be getContext() is returning null so, try to make it YourActivity.this @ user3413619指出的另一点可能是getContext()返回null,因此,请尝试将其设置为YourActivity.this

make doInBackground method return type boolean and pass result to postExecute boolean then check if result true do what method you want to call. 使doInBackground方法返回boolean类型,并将结果传递给postExecute boolean,然后检查result是否为true即可执行您要调用的方法。

Thanks 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何等到四个不同的方法完成,然后在 Android/Java 中执行另一个不同的方法 - How to wait until four different methods finishes and then execute another different method in Android/Java Android AsyncTask等到完成 - Android AsyncTask wait until finished 如何延迟进程直到AsyncTask完成? - How to delay processes until and AsyncTask finishes? Java - 在 for 循环中等待直到方法完成,然后继续 - Java - wait in for loop until method finishes, then continue 从另一个方法中的AsyncTask访问变量返回null。 如何在加载完成后才获取变量? - Accessing variable from AsyncTask in another method returns null. How do I grab the variable only after it finishes loading? 如何从android上的另一个类获取异步任务结果值? - How to get asynctask result value from another class on android ? 一个线程如何等待,直到另一个线程完成触发某些操作 - How one thread can wait until another one finishes to fire some actions 运行 function 直到另一个完成 Android - Run function until another finishes Android 如何使Android类等到另一个类完成其任务? - How to make an Android class wait until another class completes its task? 如何在Android中完成AsyncTask后更新片段? - How to update a Fragment after an AsyncTask finishes in Android?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM