Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android Build a Weather App (2015) Hooking Up the Model to the View Adding a Refresh Button

Ganta Hemanth
Ganta Hemanth
6,460 Points

progress bar not disappearing

The functionality of the refresh buttion is good . But when i press the refresh button the progress bar is appearing but is not disappearing.

The java code is

package com.example.hemanth.stromy;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
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 org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;


public class MainActivity extends ActionBarActivity {

   private CurrentWeather mcurrentweather;
   public static final String TAG = MainActivity.class.getSimpleName();
    @InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
    @InjectView(R.id.humidityValue) TextView mHumiditylable;
    @InjectView(R.id.precipValue) TextView mPreciplable;
    @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
    @InjectView(R.id.timelabel)TextView mTimeLabel;
    @InjectView(R.id.iconImageView) ImageView miconview;
    @InjectView(R.id.refresh) ImageView mrefresh;
    @InjectView(R.id.progress)
    ProgressBar mProgressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        mrefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getforecast();
            }
        });
        getforecast();
    }

    private void getforecast() {
        String apiKey = "2b345aa7cb761cc607bce49e23e4cb72";
        double latitude = 37.8267;
        double longitude = -122.423;
        String apiUrl = "https://api.forecast.io/forecast/"+apiKey+"/"+latitude+","+longitude;
        if(isNetworkAvailable()) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    togglerefresh();
                }
            });

            OkHttpClient Client = new OkHttpClient();
            Request request = new Request.Builder().url(apiUrl).build();
            Call call = Client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Toast.makeText(MainActivity.this, "There are network problems", Toast.LENGTH_LONG);
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            togglerefresh();
                        }
                    });
                    alertUser();
                }

                @Override
                public void onResponse(Response response) {

                    try {

                        String jasonData = response.body().string();
                        if (response.isSuccessful()) {
                            Log.v(TAG, jasonData);
                            mcurrentweather = getCurrentDetails(jasonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });


                        } else {
                            alertUser();
                        }
                    }
                    catch (IOException e) {
                        Log.e(TAG, "expection is ", e);
                    }
                    catch (JSONException e){
                        Log.e(TAG, "expection is ", e);
                    }
                }
            });
        }
        else{
            Toast.makeText(this,"The network is unavailable",Toast.LENGTH_LONG).show();
        }
    }

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

    private void updateDisplay() {

        mTemperatureLabel.setText(mcurrentweather.getmTemeperature()+"");
        mTimeLabel.setText("At "+mcurrentweather.getFormattedString()+" it will be ");
        mHumiditylable.setText(mcurrentweather.getmHumidity()+"");
        mPreciplable.setText(mcurrentweather.getmPrecipChance() + "");
        mSummaryLabel.setText(mcurrentweather.getmSummary());
        Drawable drawable = getResources().getDrawable(mcurrentweather.getIconId());
        miconview.setImageDrawable(drawable);

    }

    private CurrentWeather getCurrentDetails(String jasonData) throws JSONException{
        JSONObject forecast = new JSONObject(jasonData);
        String timezone = forecast.getString("timezone");
        JSONObject current = forecast.getJSONObject("currently");
        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setmHumidity(current.getDouble("humidity"));
        currentWeather.setmTemeperature(current.getDouble("temperature"));
        currentWeather.setmTimeZone(timezone);
        currentWeather.setmIcon(current.getString("icon"));
        currentWeather.setMtime(current.getInt("time"));
        Log.i(TAG,"From Json : "+timezone);

        return 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 alertUser() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(),"Error_dialog");

    }


}

The xml code is

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#ffffc32f"
    android:id="@+id/MainActivity"
    android:focusableInTouchMode="false">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="100"
        android:id="@+id/temperatureLabel"
        android:textSize="130sp"
        android:textIsSelectable="true"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/degree"
        android:layout_alignTop="@+id/temperatureLabel"
        android:layout_toRightOf="@+id/temperatureLabel"
        android:layout_toEndOf="@+id/temperatureLabel"
        android:src="@drawable/degree" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temperature at 5 pm"
        android:id="@+id/timelabel"
        android:textColor="#80ffffff"
        android:textSize="20sp"
        android:layout_above="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="42dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Durgapur West Bengal"
        android:id="@+id/tagline"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/timelabel"
        android:layout_alignStart="@+id/timelabel"
        android:layout_marginTop="58dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iconImageView"
        android:src="@drawable/cloudy"
        android:cropToPadding="false"
        android:layout_alignBottom="@+id/tagline"
        android:layout_toLeftOf="@+id/temperatureLabel"
        android:layout_toStartOf="@+id/temperatureLabel" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temperatureLabel"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:weightSum="100"
        android:id="@+id/linearLayout">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="HUMIDITY"
                android:id="@+id/humidity"
                android:textColor="#80ffffff"
                android:textSize="20sp"
                android:gravity="center_horizontal" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="0.98"
                android:id="@+id/humidityValue"
                android:textSize="32sp"
                android:gravity="center_horizontal" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Precepitation"
                android:id="@+id/precipitaion"
                android:textSize="20sp"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="100%"
                android:id="@+id/precipValue"
                android:textSize="30sp"
                android:gravity="center_horizontal" />
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="the day is stromy"
        android:id="@+id/summaryLabel"
        android:textColor="#80ffffff"
        android:textSize="25sp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignLeft="@+id/timelabel"
        android:layout_alignStart="@+id/timelabel"
        android:layout_marginTop="44dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/refresh"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:src="@drawable/refresh" />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/progress"
        android:layout_below="@+id/refresh"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

I could

Ganta Hemanth
Ganta Hemanth
6,460 Points

Thanks for the reply..

THat didn't help. Now the refresh button is not being displayed at all.. Any other suggestions??

3 Answers

Found my code from when I did the project. This has been run so it should work. Here is the getForecast method where your problem is. The first issue in your code is that the first call to "toggleRefresh()" does not need to be on the "runOnUiThread" block. The second is the one I pointed out earlier where you need to make sure it gets called both in "onFailure" and in "onResponse".

private void getForecast(double latitude, double longitude) {
        String apiKey = "246ae2b2893518a118adc024a050b70a";

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

        if(isNetworkAvailable()) {
            toggleRefresh();

            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) {
                    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_message), Toast.LENGTH_LONG).show();
        }
    }
Ganta Hemanth
Ganta Hemanth
6,460 Points

It is showing compilation errors..

See my modified answer.

Ganta Hemanth
Ganta Hemanth
6,460 Points

Thank You for the reply..

There is no need of the refreshtoggle() outside the onresponse and on failure block. If you remove that method from your code it is working fine. I will rate your answer as best answer so please make the above said changes..

Josh Gold
Josh Gold
12,206 Points

Hello Ganta, You have JasonData instead of JSONData.

'''java @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.inject(this); mrefresh.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getforecast(); } }); getforecast(); } ''' You need to give getforcast() long and lat values

'''java mRefreshImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getForcast(latitude,longitude); } });

    getForcast(latitude,longitude);

'''

for visibility you need
'''java mProgressBar.setVisibility(View.INVISIBLE); '''

under your ButterKnife.inject(this); clause