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

Java

build a weather app - NetworkInfo returning null regardless of permission settings

So I have narrowed it down to the portion of the code where I am attempting to check network connection of the phone. NetworkInfo call is returning null no matter what the permission settings are. here is the code:

MainActivity.java
package smoke.com.durumnedir;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.Tag;
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 com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    public static final String TAG = MainActivity.class.getSimpleName();
    private CurrentWeather mCurrentWeather;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_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 {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            mCurrentWeather = getCurrentDetails(jsonData);
                        } else {
                            alertUserAboutError();
                        }
                    } catch (IOException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                    catch (JSONException e) {
                        Log.e(TAG, "Exception caught: ", e);
                    }
                }
            });
        } else {
            Toast.makeText(this, R.string.network_on_available, Toast.LENGTH_LONG).show();
        }
        Log.d(TAG, "Main UI code is running!");
    }

    private CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
        JSONObject forecast = new JSONObject(jsonData);
        String timezone = forecast.getString("timezone");
        Log.i(TAG,"From JSON" + timezone);
        return new CurrentWeather();
    }

    private boolean isNetWorkAvailable() {

        ConnectivityManager manager = (ConnectivityManager)
                getSystemService(Context.CONNECTIVITY_SERVICE);

        //  now we need to substantiate a NetworkInfo object. Lets call it 'networkInfo'
        NetworkInfo networkInfo = manager.getActiveNetworkInfo(); //now we can analyze the network info to see if it is both present and active
        // ^ to use .getActiveNetworkInfo method, we need to add another permission to manifest*

        boolean isAvailable = false;
        if (networkInfo != null && networkInfo.isConnected()){
            isAvailable = true;
        }
        return isAvailable;
    }

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

AndroidManifest.xml:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

I feel like im missing one little piece of the puzzle. Any tips would be appreciated it. thanks.

[MOD: edited code block and hidden API key]

2 Answers

I put a break point and followed the code till a value had something strange/unexpected. I noticed the code kept going down the sad path and not setting the value for mCurrentWeather as you mentioned (i have not completed that code, I was following the videos as I wrote the code)

It was never going the happy path because of the method as a pointed out, and like you said too, not sure why it is returning null. Since it returns null it goes the sad path....

WOW just as I typing the response it dawns in my mind - I left it in airplane mode!!!!!!!!! All set now. thanks for the help :)

Haha! I would love to say I'd never done that; but I can't. :wink: :+1:

Hi Ersan,

I can't see anything wrong with your permissions or the code within isNetworkAvailable - that all seems fine. Have you tested the variable to be null?

What are the symtpoms that you are trying to fix? Is your CurrentWeather empty?

I'm not sure that your getCurrentDetails() method is correct. You are calling it and passing it the jsonData, which is fine. But you are then just returning a blank CurrentWeather object. Are you sure that the code wants to return that as soon as it is created without extracting any information from the JSON?

I'll have a look through the video to see if I can spot where this is.

Steve.