如何修复无法在尚未调用Looper.prepare()

时间:2018-07-03 16:56:06

标签: java android

为什么我得到:Can't create handler inside thread that has not called Looper.prepare()错误?

public class MovieInterface extends AsyncTask<String, Void, MovieResultsPage> {
    public Activity activity;

    MovieInterface(Activity context) {
        this.activity = context;
    }

    public void handleUpcomingMovies() {

    }

    @Override
    protected MovieResultsPage doInBackground(String... strings) {
        TmdbMovies movies = new TmdbApi("d2e5d02fe295efc00bad8da4dc384edf").getMovies();
        MovieResultsPage upcomingMovies = movies.getUpcoming(null, 1, "IN");
        int totalpages = upcomingMovies.getTotalPages();
        return upcomingMovies;
    }


    @Override
    protected void onPostExecute(final MovieResultsPage movieDbs) {
        super.onPostExecute(movieDbs);

                ArrayList<MovieClass> mymovielist = new ArrayList<>();
                for (MovieDb movieResult : movieDbs.getResults()) {
                    mymovielist.add(new MovieClass(movieResult.getTitle(), movieResult.getOverview()));
                }

                MovieAdapter movieClassArrayAdapter = new MovieAdapter(activity, R.layout.movie_list_item, mymovielist);

                ((ListView) activity.findViewById(R.id.upcomingMoviesList)).setAdapter(movieClassArrayAdapter);

    }

方法调用:

MovieInterface movieInterface = new MovieInterface(this) ;
movieInterface.execute() ;

由于提出了类似问题的其他答案,因此我没有在background方法内进行任何UI更新。但是仍然出现错误。

我是android和java的新手。我该如何解决 ?

4 个答案:

答案 0 :(得分:1)

在新线程的looper.prepare()方法中调用run()

Handler不能将MessagesRunnables调度到线程的Looper(如果不存在)。请参阅官方文档中的this

答案 1 :(得分:0)

new Handler(Looper.getMainLooper())

documentation中的更多详细信息。

答案 2 :(得分:0)

onPostExecute()在主UI线程上调用。尝试删除runOnUiThread()调用。有关AsyncTask的更多详细信息,请参见https://developer.android.com/reference/android/os/AsyncTask

答案 3 :(得分:0)

罪魁祸首可能是您的doInBackground方法中的方法调用之一。 尝试在UIThread上运行它们:

runOnUiThread(new Runnable() {
            @Override
            public void run() {
                TmdbMovies movies = new TmdbApi("d2e5d02fe295efc00bad8da4dc384edf").getMovies();
                MovieResultsPage upcomingMovies = movies.getUpcoming(null, 1, "IN");
                int totalpages = upcomingMovies.getTotalPages();
                return upcomingMovies;
            }
        });