skip to Main Content

I use OkHttp in a separate service to fetch data from the twitter API.
I have been trying to Alert the user that tweets cannot be loaded without an internet connection. But when i try this, the application crashes.The error is
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare().
Here’s my code

 private void getTweets(final String topic) {
    final TwitterService twitterService = new TwitterService();
    twitterService.findTweets(topic, new Callback() {
        @Override
        public void onFailure(Request request, IOException e) {
            e.printStackTrace();
            Log.e("Traffic Activity", "Failed to make API call");
            Toast.makeText(getApplicationContext(), "Bigger fail", Toast.LENGTH_LONG).show();

        }

2

Answers


  1. Probably you are calling Toast.makeText from the wrong thread. It needs to be called from the UI thread. Try this instead

    activity.runOnUiThread(new Runnable() {
        public void run() {
            Toast.makeText(activity, msg, Toast.LENGTH_SHORT).show();
        }
    });
    

    More informations here Can't create handler inside thread that has not called Looper.prepare()

    Login or Signup to reply.
  2. You’re calling it from a worker thread. You need to call Toast.makeText() (and most other functions dealing with the UI) from within the main thread. You could use a handler, for example

    //set this up in UI thread

    mHandler = new Handler(Looper.getMainLooper()) {
    @Override
    public void handleMessage(Message message) {
        // This is where you do your work in the UI thread.
        // Your worker tells you in the message what to do.
    }
    

    };

    void workerThread() {
    // And this is how you call it from the worker thread:
    Message message = mHandler.obtainMessage(command, parameter);
    message.sendToTarget();
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search