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

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

Hi My Question is that i am getting a java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 error in the code below at the line "getForecast(latitude,longtitude);" and in the class mRefreshImageView The code is JAVA `` package app.aryan.intelligentweatherapp.UI;

import android.content.Context; import android.content.Intent; import android.graphics.drawable.Drawable; import android.location.Address; import android.location.Geocoder; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; 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.google.android.gms.location.LocationRequest; 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.JSONArray; import org.json.JSONException; import org.json.JSONObject;

import java.io.IOException; import java.util.List; import java.util.Locale;

import app.aryan.intelligentweatherapp.R; import app.aryan.intelligentweatherapp.Weather.Current; import app.aryan.intelligentweatherapp.Weather.Day; import app.aryan.intelligentweatherapp.Weather.Forecast; import app.aryan.intelligentweatherapp.Weather.Hour; import app.aryan.intelligentweatherapp.location.GPSTracker; import butterknife.ButterKnife; import butterknife.InjectView; import butterknife.OnClick;

public class MainActivity extends ActionBarActivity {

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



// boolean flag to toggle periodic location updates
private boolean mRequestingLocationUpdates = false;

private LocationRequest mLocationRequest;
private String currentCityName;


private Forecast mForecast;

@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;
@InjectView(R.id.locationLabel)
TextView mLocationLabel;

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


    mProgressBar.setVisibility(View.INVISIBLE);

    GPSTracker GTracker = new GPSTracker(MainActivity.this);

    if (GTracker != null) {
        System.out.print("location is NOT null.... ");

        latitude = GTracker.getLatitude();
        longitude = GTracker.getLongitude();


        Geocoder geocoder = new Geocoder(this, Locale.getDefault());
        List<Address> addresses = null;
        try {
            addresses = geocoder.getFromLocation(latitude, longitude, 1);
            currentCityName = addresses.get(0).getAddressLine(2);
            //String stateName = addresses.get(0).getAddressLine(2);
            //String countryName = addresses.get(0).getAddressLine(3);
        } catch (IOException e) {
            e.printStackTrace();
        }
  } else {
        Toast.makeText(this, getString(R.string.network_unavailable_message),
               Toast.LENGTH_LONG).show();
        latitude = Double.parseDouble(null);
        longitude = Double.parseDouble(null);

}

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

  }


private void getForecast(double latitude, double longitude) {
    String apiKey = "9128496ffcbe8e4df9709ba56e90dfd4";
    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();
    }
}

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() {
    Current current = mForecast.getCurrent();

    mTemperatureLabel.setText(current.getTemperature() + "");
    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);
    //mLocationLabel.setText(currentCityName);
}

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.setIcon(jsonHour.getString("icon"));
        hour.setTemperature(jsonHour.getDouble("temperature"));
        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() {
    alertDialogFragement dialog = new alertDialogFragement();
    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());
    startActivity(intent);

}

`` The Logs Say

java.lang.RuntimeException: Unable to start activity ComponentInfo{app.aryan.IntelligentWeatherApp/app.aryan.intelligentweatherapp.UI.MainActivity}: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198) at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257) at android.app.ActivityThread.access$800(ActivityThread.java:139) at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210) at android.os.Handler.dispatchMessage(Handler.java:102) at android.os.Looper.loop(Looper.java:136) at android.app.ActivityThread.main(ActivityThread.java:5086) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) at dalvik.system.NativeStart.main(Native Method) Caused by: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0 at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255) at java.util.ArrayList.get(ArrayList.java:308) at app.aryan.intelligentweatherapp.UI.MainActivity.onCreate(MainActivity.java:124) at android.app.Activity.performCreate(Activity.java:5248) at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110) at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162) ... 11 more Thanks Aryan Please Help

2 Answers

Kris B
Kris B
11,107 Points

I can't offer a solution, but I can tell you what the exception means and perhaps steer you in the right direction.

IndexOutOfBound exception means you've got a problem because you're trying to access an index which doesn't exist or is empty (not null). For example if you've got an array with only two elements, so it only has index 0 and 1, and you try to access index 2 you'll get an IndexOutOfBoundException because index 2 doesn't exist. If you make an array of 10 elements and only fill 5, indexes 4-9 will be empty, accessing those might cause an IndexOutOfBoundException. If you create an array you know will have empty elements, set them as null. I'm not 100% that would cause an IndexOutOfBoundsException, but it is good practise to set them as null as it can cause problems when accessing empty indexes.

If you're using an IDE it might help you to debug the problem by removing the throws statements. Throws statements "pass the buck" when it comes to exceptions, you're not actually handling exceptions by using throws. Try-catch statements handle exceptions much better because they narrow down the area where the problem is (because they 'test' the code within the try brackets.

Throws have their place, but for debugging try-catch can be much more helpful.

Hopefully some of that helps. Good luck. :)

Hi I Just Checked You Were Right It was The Problem As in some case The 2nd Index doesnt exist any tips how come i check the Length Thanks Aryan