Arjun Issar
Arjun Issar

Reputation: 654

ArrayAdapter is null even after getting a string array as a parameter

I'm working on the Sunshine app in the Developing Android App course by Udacity. Currently stuck in lesson 2. I've listed down the MainActivity.java that contains a listview that is populated by a network call in the AsyncTask as an inner class in the MainActivity.java. But the application crashes, due to a null pointer exception, as the array adapter is null. I've tried debugging, and the weekForecast (i.e., the ArrayList that stores the parsed data, and is a parameter to the creation of the ArrayAdapter) does have valid parsed data. Thanks for the help in advance.

public class MainActivity extends AppCompatActivity {

ListView listView;
ArrayAdapter<String> arrayAdapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listView=(ListView)findViewById(R.id.listview_forecast);
    GettingWeatherFromNetwork gettingWeatherFromNetwork = new GettingWeatherFromNetwork();
    gettingWeatherFromNetwork.execute("94043");
    listView.setAdapter(arrayAdapter);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.main,menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    switch(id) {
        case R.id.action_settings : return true;
        case R.id.action_refresh : GettingWeatherFromNetwork gettingWeatherFromNetwork = new GettingWeatherFromNetwork();
            gettingWeatherFromNetwork.execute("94043");
            return true;
    }
    return super.onOptionsItemSelected(item);
}

public class GettingWeatherFromNetwork extends AsyncTask<String, Void, String[]> {
    private final String LOG_TAG = GettingWeatherFromNetwork.class.getSimpleName();
    //Removed API KEY. But it is a part of the main code I'm running.
    private final String API_KEY = "  ";

    @Override
    protected String[] doInBackground(String... params) {
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

        String forecastJsonStr = null;
        String format = "json";
        String units = "metric";
        int noOfDays = 7;

        try {

            final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
            final String QUERY_PARAM = "q";
            final String MODE_PARAM = "mode";
            final String UNITS_PARAM = "units";
            final String COUNT_PARAM = "cnt";
            final String KEY_PARAM = "appid";

            Uri builtURI = Uri.parse(BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM,params[0])
                    .appendQueryParameter(MODE_PARAM,format)
                    .appendQueryParameter(UNITS_PARAM,units)
                    .appendQueryParameter(COUNT_PARAM, String.valueOf(noOfDays))
                    .appendQueryParameter(KEY_PARAM,API_KEY)
                    .build();

            String Url = builtURI.toString();
            URL url = new URL(Url);

            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            StringBuffer buffer = new StringBuffer();
            if (inputStream == null) {
                return null;
            }
            reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                buffer.append(line + "\n");
            }

            if (buffer.length() == 0) {
                return null;
            }
            forecastJsonStr = buffer.toString();
        } catch (IOException e) {
            Log.e(LOG_TAG, String.valueOf(e));
            return null;
        } finally{
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, String.valueOf(e));
                }
            }
        }

        String [] weatherForecast = new String[0];
        WeatherParser weatherParser = new WeatherParser();
        try {
            weatherForecast = weatherParser.getWeatherDataFromJson(forecastJsonStr,7);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return weatherForecast;
    }

    @Override
    protected void onPostExecute(String[] s) {
        List<String> weekForecast = new ArrayList<String>(Arrays.asList(s));
        arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);
    }
}
}

Upvotes: 0

Views: 1296

Answers (1)

Hari Krishnan
Hari Krishnan

Reputation: 6302

Try removing the line

listView.setAdapter(arrayAdapter);

from onCreate method and add it in onPostExecute() method of AsyncTask, after initialising the arrayAdapter.

@Override
protected void onPostExecute(String[] s) {
    List<String> weekForecast = new ArrayList<String>(Arrays.asList(s));
    arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);

    //set adapter set to listview after initialzing it.

    listView.setAdapter(arrayAdapter);
}

Upvotes: 1

Related Questions