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 Build a Weather App (2015) Working with JSON Introducing JSONObject

doesn't find the JSON String in Log

I have been written the same code and once also trying by copy paste the code from treehouse downloads , But in both cases i just find the " Main UI code is running! " in log but does'nt find the JSON String in log? What's may be wrong help me! plz!

Alejandro Crespo
Alejandro Crespo
6,628 Points

Do you have your logcat set to verbose? Are you sure you're logging it correctly? Can you show me your code?

yah! i have been set the logcat to verbose.

Code is: MainActivity.java :

(```)

(```)package com.example.abdulrehman.idea;

import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.widget.Toast;

import com.example.abdulrehman.idea.AlertDialogFragment; import com.example.abdulrehman.idea.CurrentWeather; import com.example.abdulrehman.idea.R; 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 ActionBarActivity {

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

private CurrentWeather mCurrentWeather;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String apiKey = "7721c98a5e54fd53839ee2f0cd52b97e";
    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, getString(R.string.network_unavailable_message),
                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);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if (networkInfo != null && networkInfo.isConnected()) {
        isAvailable = true;
    }

    return isAvailable;
}

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

}

(```)

//////// CurrentWeather.java

package com.example.abdulrehman.idea;

/**

  • Created by AbdulRehman on 4/29/2015. */ public class CurrentWeather { private String mIcon; private long mTime; private double mTemperature; private double mHumidity; private double mPrecipChance; private String mSummary;

    public String getIcon() { return mIcon; }

    public void setIcon(String icon) { mIcon = icon; }

    public long getTime() { return mTime; }

    public void setTime(long time) { mTime = time; }

    public double getTemperature() { return mTemperature; }

    public void setTemperature(double temperature) { mTemperature = temperature; }

    public double getHumidity() { return mHumidity; }

    public void setHumidity(double humidity) { mHumidity = humidity; }

    public double getPrecipChance() { return mPrecipChance; }

    public void setPrecipChance(double precipChance) { mPrecipChance = precipChance; }

    public String getSummary() { return mSummary; }

    public void setSummary(String summary) { mSummary = summary; } }

(```)

Mohammed Amin
Mohammed Amin
5,445 Points

Are you testing the code on a physical device or an emulator? Try running it on an emulator as a physical device often has other things its logging and it may clutter your output.

Also when trying to run it on both the physical device and emulator, try to filter out the results by typing MainActivity in the search bar next to Log Level where your output is.

I've tested your api key and it does result in feedback from the api. Possible issues can include connectivity to the api. If you've got it up and running, you should consider reseting your api key from your developer account at https://developer.forecast.io/

1 Answer

Charles Herrera
Charles Herrera
3,292 Points

This might sound silly but make sure you aren't still in airplane mode from the previous exercise. That's what happened to me :S