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 Android Lists and Adapters (2015) Lists with RecyclerViews Using a Layout Manager

Jordan Ernst
Jordan Ernst
5,121 Points

MainActivity.java uses or overrides a depricated api. recompile with Xlint

stormy is crashing each time i hit the button. the above question is the only error i am finding through everything. the error started a few lessons ago. please help with this or the other question i posted a few hours ago; either would probably fix the problem

Timothy Boland
Timothy Boland
18,237 Points

Can you post your MainActivity.java and build.gradle code so we can take a look?

Also, Wrap your code with 3 backticks (```) on the line before and after. If you specify the language after the first set of backticks, that'll help us with syntax highlighting.

      ```html
      <p>This is code!</p>
      ```
Jordan Ernst
Jordan Ernst
5,121 Points

i updated all of my software completely now i get a fatal exception error. and stormy crashes immediately when i run it.

here is my MainActivity.Java:

package com.teamtreehouse.stormy.ui;

import android.annotation.TargetApi; import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Build; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; 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 com.teamtreehouse.stormy.R; import com.teamtreehouse.stormy.Weather.Current; import com.teamtreehouse.stormy.Weather.Day; import com.teamtreehouse.stormy.Weather.Forecast; import com.teamtreehouse.stormy.Weather.Hour;

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

import java.io.IOException;

import butterknife.Bind; import butterknife.ButterKnife; import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

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

    private Forecast mForecast;

    @Bind(R.id.timeLabel)TextView mTimeLabel;
    @Bind(R.id.temperatureLabel) TextView mTemperatureLabel;
    @Bind(R.id.humidityValue) TextView mHumidityValue;
    @Bind(R.id.precipValue) TextView mPrecipValue;
    @Bind(R.id.summaryLabel) TextView mSummaryLabel;
    @Bind(R.id.iconImageView)ImageView mIconImageView;
    @Bind(R.id.refreshImageView)ImageView mRefreshImageView;
    @Bind(R.id.progressBar)ProgressBar mProgressBar;

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

        mProgressBar.setVisibility(View.INVISIBLE);

        final double latitude= 37.8267;
        final double longitude= -122.423;

        mRefreshImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getForecast(latitude, longitude);
            }
        });

        getForecast(latitude, longitude);
        Log.d(TAG,"main Ui code is running");
    }

    private void getForecast(double latitude, double longitude) {
        String apiKey="985474687ba757c24da7fb0e0c94cece";
        String forecastUrl= "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;

        if(isNetworkAvailable()) {
            toggleRefresh();

            OkHttpClient client = new OkHttpClient();// default constructor
            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) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            toggleRefresh();
                        }
                    });
                    alertUserAboutError();
                }

                @Override
                public void onResponse(Response response) throws IOException {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                toggleRefresh();
                            }
                        });
                    try {
                        String jsonData = response.body().string();
                        Log.v(TAG, jsonData);
                        if (response.isSuccessful()) {
                            mForecast= parseForecastDetails(jsonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });
                        } 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),
                    Toast.LENGTH_LONG).show();// instead of a toast attempt to create a dialog displaying the network is unavailable
        }
    }

    private void toggleRefresh() {
        if(mProgressBar.getVisibility() == View.INVISIBLE){
            mProgressBar.setVisibility(View.VISIBLE);
            mRefreshImageView.setVisibility(View.INVISIBLE);
        }
        else{
            mProgressBar.setVisibility(View.INVISIBLE);
            mRefreshImageView.setVisibility(View.VISIBLE);
        }
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    private void updateDisplay() {
        Current current= mForecast.getCurrent();

        mTemperatureLabel.setText(String.format("%d", current.getTemperature()));// converts the double value to a string
        mTimeLabel.setText("At " + current.getFormattedTime() + " it will be");
        mHumidityValue.setText(current.getHumidity()+ "");
        mPrecipValue.setText(current.getPrecipChance()+ "%");
        mSummaryLabel.setText(current.getSummary());
        Drawable drawable= getResources().getDrawable(current.getIconId());
        mIconImageView.setImageDrawable(drawable);
    }

    private Forecast parseForecastDetails (String jsonData) throws JSONException{
        Forecast forecast= new Forecast();

        forecast.setCurrent(getCurrentDetails(jsonData));
        forecast.setHourlyForecast(getHourlyForecast(jsonData));
        forecast.setDailyForecast(getDailyForecast(jsonData));

        return forecast;
    }

    private Day[] getDailyForecast(String jsonData) throws JSONException {
        JSONObject forecast= new JSONObject(jsonData);
        String timezone= forecast.getString("timezone");
        JSONObject daily= forecast.getJSONObject("daily");
        JSONArray data= daily.getJSONArray("data");

        Day[] days= new Day[data.length()];

        for (int i= 0; i< data.length(); i++){
            JSONObject jsonDay= data.getJSONObject(i);
            Day day= new Day();

            day.setSummary(jsonDay.getString("summary"));
            day.setIcon(jsonDay.getString("icon"));
            day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
            day.setTime(jsonDay.getLong("time"));
            day.setTimezone(timezone);

            days[i]= day;
        }

        return days;
    }

    private Hour[] getHourlyForecast(String jsonData) throws JSONException{
        JSONObject forecast= new JSONObject(jsonData);
        String timezone= forecast.getString("timezone");
        JSONObject hourly= forecast.getJSONObject("hourly");
        JSONArray data= hourly.getJSONArray("data");

        Hour[] hours= new Hour[data.length()];

        for (int i= 0; i < data.length(); i++){
            JSONObject jsonHour= data.getJSONObject(i);
            Hour hour= new Hour();

            hour.setSummary(jsonHour.getString("summary"));
            hour.setTemperature(jsonHour.getDouble("temperature"));
            hour.setIcon(jsonHour.getString("icon"));
            hour.setTime(jsonHour.getLong("time"));
            hour.setTimezone(timezone);

            hours[i]= hour;
        }

        return hours;
    }

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

        JSONObject currently= forecast.getJSONObject("currently");
        Current current = new Current();
        current.setHumidity(currently.getDouble("humidity"));
        current.setTime(currently.getLong("time"));
        current.setIcon(currently.getString("icon"));
        current.setPrecipChance(currently.getDouble("precipProbability"));
        current.setSummary(currently.getString("summary"));
        current.setTemperature(currently.getDouble("temperature"));
        current.setTimeZone(timezone);

        Log.d(TAG, current.getFormattedTime());

        return current;
    }

    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");
    }

    @OnClick  (R.id.dailyButton)
    public void startDailyActivity (View view){
        Intent intent= new Intent(this, DailyForecastActivity.class);
        intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
        startActivity(intent);
    }
    @OnClick (R.id.hourlyButton)
    public void startHourlyActivity (View view){
        Intent intent= new Intent(this, HourlyForecastActivity.class);
        intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast()); // bug may be in here
        startActivity(intent);

    }


}

here is the errors:

11-22 06:00:23.114 20220-20220/com.teamtreehouse.stormy E/AndroidRuntime: FATAL EXCEPTION: main Process: com.teamtreehouse.stormy, PID: 20220 java.lang.RuntimeException: Unable to start activity ComponentInfo{com.teamtreehouse.stormy/com.teamtreehouse.stormy.ui.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2661) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726) at android.app.ActivityThread.access$900(ActivityThread.java:172) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:145) at android.app.ActivityThread.main(ActivityThread.java:5835) at java.lang.reflect.Method.invoke(Native Method) at java.lang.reflect.Method.invoke(Method.java:372) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194) Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity. at android.support.v7.app.AppCompatDelegateImplV7.createSubDecor(AppCompatDelegateImplV7.java:310) at android.support.v7.app.AppCompatDelegateImplV7.ensureSubDecor(AppCompatDelegateImplV7.java:279) at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:253) at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109) at com.teamtreehouse.stormy.ui.MainActivity.onCreate(MainActivity.java:61) at android.app.Activity.performCreate(Activity.java:6221) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2614) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2726)  at android.app.ActivityThread.access$900(ActivityThread.java:172)  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1421)  at android.os.Handler.dispatchMessage(Handler.java:102)  at android.os.Looper.loop(Looper.java:145)  at android.app.ActivityThread.main(ActivityThread.java:5835)  at java.lang.reflect.Method.invoke(Native Method)  at java.lang.reflect.Method.invoke(Method.java:372)  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Build.gradle:

apply plugin: 'com.android.application'

android { compileSdkVersion 23 buildToolsVersion "23.0.1"

defaultConfig {
    applicationId "com.teamtreehouse.stormy"
    minSdkVersion 14
    targetSdkVersion 23
    versionCode 1
    versionName "1.0"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}

}

dependencies { compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:23.1.1' compile 'com.android.support:recyclerview-v7:23.1.1' compile 'com.squareup.okhttp:okhttp:2.5.0' compile 'com.jakewharton:butterknife:7.0.1' }

1 Answer

Daniel Hartin
Daniel Hartin
18,106 Points

Hi Jordan

Are you struggling with this still?

I have had this problem a few times with apps of mine, it was usually becuase I was trying to be clever with themes in the android manifest (I hate themes , I can never get them to work :))

I would check you android manifest for a line like the following:

android:theme="@android:style/Theme.Translucent.NoTitleBar.Fullscreen"

This could be either in the MainActivity section or the application section. The error is saying it should use an appCompat theme a useful stack overflow I found for my problem is here http://stackoverflow.com/questions/21814825/you-need-to-use-a-theme-appcompat-theme-or-descendant-with-this-activity (not sure if you are having the same problem or not)

Hopefully this can get you on the right track if nothing else

Daniel