Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

David H
David H
4,504 Points

I have a question.

I'm getting 4 errors currently:

Error:(49, 41) error: <anonymous davidhipwell.tempestas.TempestasMainActivity$1> is not abstract and does not override abstract method onResponse(Call,Response) in Callback

Error:(50, 17) error: method does not override or implement a method from a supertype

Error:(55, 17) error: method does not override or implement a method from a supertype

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.

I’ve tried using my google-fu to figure out the problem. I've compared my code to the source code and looked up many websites with similar issues to my own.

Android studio wants me to change my Callback to this

            Call call = client.newCall(request);
call.enqueue(new Callback() {
   @Override
   public void onFailure(Call call, IOException e) {

   }

   @Override
   public void onResponse(Call call, Response response) throws IOException {

   }

instead of what I currently have.

Call call = client.newCall(request);
call.enqueue(new Callback() {
   @Override
   public void onFailure(Request request, IOException e) {

   }

   @Override

   public void onResponse(Response response) throws IOException {
       try {
           Log.v(TAG, response.body().string());
           if (response.isSuccessful()) {

           } else {
               alertUserAboutError();
           }
       } catch (IOException e) {
           Log.e(TAG, "Exception caught: ", e);
       }
   }
});

I’m not knowledgeable enough yet to know whether I should do.

My MainActivity code is below. I hope someone can help.

package davidhipwell.tempestas;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;


import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class TempestasMainActivity extends AppCompatActivity {

    public static final String TAG = TempestasMainActivity.class.getSimpleName();

    private CurrentWeather mCurrentWeather;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tempestas_main);
        String apiKey = "HIDDEN";
        double latitude = 37.8267;
        double longitude = 122.423;

        String  forecastUrl = "https://api.forecast.io/forecast/"+ apiKey+ "/"+latitude+","+longitude;

        if(isNetworkAvailable()) {
            OkHttpClient client = new OkHttpClient();
            Request request = new Request.Builder()
                    .url(forecastUrl)
                    .build();

            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override

                public void onResponse(Response response) throws IOException {
                    try {
                        Log.v(TAG, response.body().string());
                        if (response.isSuccessful()) {

                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        }
        else {
            Toast.makeText(this, getString(R.string.network_unavilable_message),
                    Toast.LENGTH_LONG).show();
        }
        Log.d(TAG, "Main UI code is running");


    }

    private boolean isNetworkAvailable() {
        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = manager.getActiveNetworkInfo();
        boolean isAvailable = false;
        if(networkInfo != null && networkInfo.isConnected()){
            isAvailable = true;
        }
        return  isAvailable;
    }

    private void alertUserAboutError() {
        AlertDialogueFragment dialog = new AlertDialogueFragment();
        dialog.show(getFragmentManager(), "error_dialog");
    }
}

Hi David,

I edited your code blocks and hid your API key ... I'm just loading AS now to see fi I can help you.

What prompted you to change the call? You say AS wanted you to? What was the message?

I have a working version of this app in a Github repo if you want to compare your code with mine; here

And which line is 49 - I can work the rest out from there.

Steve.

I just replicated the Callback code completion and got the same as in the project:

   call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {

                }
            })

I just replicated the Callback code completion and got the same as in the project:

   call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {

                }

                @Override
                public void onResponse(Response response) throws IOException {

                }
            })
David H
David H
4,504 Points

Thanks for your speedy reply Steve Hunter.

When I hover over Callback i get the following message

Callback class anonymous must either be declared abstract or implemented abstract method onFailure(Call, IOException) in 'Callback.'

When I go into the package info it says the following.

package okhttp3;

import java.io.IOException;

public interface Callback { /**

  • Called when the request could not be executed due to cancellation, a connectivity problem or
  • timeout. Because networks can fail during an exchange, it is possible that the remote server
  • accepted the request before the failure. */ void onFailure(Call call, IOException e);

/**

  • Called when the HTTP response was successfully returned by the remote server. The callback may
  • proceed to read the response body with {@link Response#body}. The response is still live until
  • its response body is closed with {@code response.body().close()}. The recipient of the callback
  • may even consume the response body on another thread. *
  • <p>Note that transport-layer success (receiving a HTTP response code, headers and body) does
  • not necessarily indicate application-layer success: {@code response} may still indicate an
  • unhappy HTTP response code like 404 or 500. */ void onResponse(Call call, Response response) throws IOException; }

This is what I meant by the message that android studio giving.

I'm going to retrace my steps and try and figure this out. If you get any insights I'd love to know. Time to play the detective game with my code.

David H
David H
4,504 Points

I've figured out where my code diverges but I'm still unsure why its occurring. On the "Making our code Asynchronous" at around 44 seconds in. What I get in android studio and what happens on the video is different as highlighted above.

I've started from scratch again and I've gotten the same results. Not sure where I am going wrong.

Hi David,

Apologies for the delay; I had to get a shift out of the way.

What error are you seeing; why are you hovering over Callback?

I'll see if I can locate the video and see what you are expecting to see. One thing; what does the class extend in the video? ActionBarActivity? And what Android SDK version are you using; 23?

Steve.

David H
David H
4,504 Points

Hi Steve,

I believe the answer is that the Callback was changed in version 3.0.0 in the okhttp so that was causing the changes I was seeing. Is this correct?

Version 3.0.0 + +2016-01-13 + +This release commits to a stable 3.0 API. Read the 3.0.0-RC1 changes for advice +on upgrading from 2.x to 3.x. + + The Callback interface now takes a Call. This makes it easier to + check if the call was canceled from within the callback. When migrating + async calls to this new API,Call is now the first parameter for both + onResponse() and onFailure(). + * Fix: handle multiple cookies in JavaNetCookieJar on Android. + * Fix: improve the default HTTP message in MockWebServer responses. + * Fix: don't leak file handles when a conditional GET throws. + * Fix: Use charset specified by the request body content type in OkHttp's + logging interceptor. + * Fix: Don't eagerly release pools on cache hits. + * New: Make OkHttp OSGi ready. + * New: Add already-implemented interfaces Closeable and Flushable to the cache. +

1 Answer

Ah, yes. That's certainly the difference that your code illustrates. Can you use the older version by setting the version number in Gradle?

compile 'com.squareup.okhttp:okhttp:2.3.0'

If not, then we'll have to figure out a workaround - that should be OK to do; we "just" need to figure out the Call requirement.

Steve.

David H
David H
4,504 Points

Thanks for all your help Steve, much appreciated. I've changed the version number and its working correctly. I was tempted to stick with the newer version but decided against it.

Thanks again.

I think that's a sensible way forward. Maybe, once you've completed the app, you can go back and try to make it work with the newer version. Personally, I got mine to work with the GPS for a non hard-coded location. I'm fine with using the old version of okhttp!

Good luck.

Steve.