![](/img/trans.png)
[英]Android thread error - Can't create handler inside thread that has not called Looper.prepare()
[英]how to fix Can't create handler inside thread that has not called Looper.prepare()
我為什么得到: Can't create handler inside thread that has not called Looper.prepare()
錯誤的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的新手。 我該如何解決 ?
在新線程的run()
方法中調用looper.prepare()
。
一個Handler
無法調度Messages
或Runnables
的Looper
線程,如果它不存在。 請參閱本官方文檔。
new Handler(Looper.getMainLooper())
文檔中有更多詳細信息。
onPostExecute()在主UI線程上調用。 嘗試刪除runOnUiThread()調用。 有關AsyncTask的更多詳細信息,請參見https://developer.android.com/reference/android/os/AsyncTask
罪魁禍首可能是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;
}
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.