Why am I getting : Can't create handler inside thread that has not called Looper.prepare()
error here ?
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() ;
As other answers for similar questions have suggessted , I am not doing any UI updates inside the background method . But still am getting the error.
I'm new to android and java . How do I fix this ?
Call looper.prepare()
in the run()
method of your new thread.
A Handler
can't dispatch Messages
or Runnables
to the Looper
of a thread if it does not exist. Refer to this in the official documentation.
new Handler(Looper.getMainLooper())
文档中有更多详细信息。
onPostExecute() is invoked on the main UI thread. Try removing the runOnUiThread() call. For more details on AsyncTask see https://developer.android.com/reference/android/os/AsyncTask
The culprit may be one of the method calls in your doInBackground
method. try running those on 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;
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.