即使将字符串数组作为参数获取,ArrayAdapter也为null

时间:2016-01-21 10:03:36

标签: android listview nullpointerexception android-arrayadapter

我正在Udacity开发Android应用程序课程中的Sunshine应用程序。目前停留在第2课中。我已经列出了MainActivity.java,其中包含一个listview,该视图由AsyncTask中的网络调用填充为MainActivity.java中的内部类。但是由于空指针异常,应用程序崩溃,因为数组适配器为空。我已经尝试过调试,而weekForecast(即存储解析数据的ArrayList,并且是创建ArrayAdapter的参数)确实具有有效的解析数据。感谢您的帮助。

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

1 个答案:

答案 0 :(得分:1)

尝试删除该行

listView.setAdapter(arrayAdapter);
在初始化arrayAdapter之后,从onCreate方法

并将其添加到AsyncTask的onPostExecute()方法中。

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