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

Jose Alejandro Fibla
Jose Alejandro Fibla
3,526 Points

Need help with a custom code i made for Stormy (Forecast Android App), an spinner arraylist objects of locations.

I don't know how to take the latitude and longitude variables to change the location and the refresh to work.

Here's the code...

public class MainActivity extends AppCompatActivity {

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

private CurrentWeather mCurrentWeather;
private Spinner sp;

ArrayList <Cities> myCities;
String[] nombres= new String[]{"BARCELONA","MADRID","ROMA","BERLIN","PARIS"};

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


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

    mProgressBar.setVisibility(View.INVISIBLE);

    //SPINNER
    sp = (Spinner)findViewById(R.id.spinnerLocation);
    //METODO
    myCities = new ArrayList <Cities>();
    populateList();
    //ADAPTADOR
    ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_spinner_item,nombres);
    sp.setAdapter(adapter);
    //ITEM SELECCIONADO
    sp.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            final double lat=myCities.get(position).getLatitude();
            final double lon=myCities.get(position).getLongitude();
            Toast.makeText(getApplicationContext(),"("+lat+","+lon+")",Toast.LENGTH_SHORT).show();

        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

    final double latitude = 41.3818;
    final double longitude = 2.1685;

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

    getForecast(latitude, longitude);

    Log.d(TAG, "Main UI code is running!");
}

protected void getForecast(double lat, double lon) {
    String apiKey = "efa22893b0b416eaa0443a956d8d76ea";
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
            "/" + lat + "," + lon;

    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()) {
                        mCurrentWeather = getCurrentDetails(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();
    }
}

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

private void updateDisplay() {
    mTemperatureLabel.setText(mCurrentWeather.getTemperature() + "");
    mTimeLabel.setText("At " + mCurrentWeather.getFormattedTime() + " it will be");
    mHumidityValue.setText(mCurrentWeather.getHumidity() + "");
    mPrecipValue.setText(mCurrentWeather.getPrecipChance() + "%");
    mSummaryLabel.setText(mCurrentWeather.getSummary());

    Drawable drawable = getResources().getDrawable(mCurrentWeather.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

private CurrentWeather 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");

    CurrentWeather currentWeather = new CurrentWeather();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setSummary(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));
    currentWeather.setTimeZone(timezone);

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

    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 alertUserAboutError() {
    AlertDialogFragment dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(), "error_dialog");
}

public void populateList(){
    myCities.add(new Cities("Barcelona", 41.3818, 2.1685));
    myCities.add(new Cities("Madrid", 40.4165000, -3.7025600));
    myCities.add(new Cities("Roma", 41.8919300, 12.5113300));
    myCities.add(new Cities("Berlin", 52.5243700, 13.4105300));
    myCities.add(new Cities("Paris", 48.8534100, 2.3488000));

}

}

4 Answers

Seth Kroger
Seth Kroger
56,413 Points

I would consider making latitude and longitude member variables instead of final. Or storing the current city in a member variable and pulling the latitude and longitude from that when you call getForecast().

Jose Alejandro Fibla
Jose Alejandro Fibla
3,526 Points

You mean...

double lat,lon;

public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { lat=myCities.get(position).getLatitude(); lon=myCities.get(position).getLongitude(); Toast.makeText(getApplicationContext(),"("+lat+","+lon+")",Toast.LENGTH_SHORT).show();

Seth Kroger
Seth Kroger
56,413 Points

You still need to use those in the getForecast() calls for it to work. I'd also suggest initializing them with the default location and making them either private or public.

Jose Alejandro Fibla
Jose Alejandro Fibla
3,526 Points

it works, thanks for your help Seth Kroger,