Arrayadapter添加方法不接受字符串值

时间:2016-09-29 05:12:54

标签: java android

我在Android Studio上运行应用程序,在向arrayadapter对象添加字符串值时,我得到空指针异常。我的确切相关代码是:

    protected void onPostExecute(String[] result) {

                List<String> wordList = new ArrayList<>();
                wordList = Arrays.asList(result);
                if(wordList!= null)
                {
                    for(String forecast: wordList)
                    {
                        Log.v(LOG_TAG,"forecast value: "+forecast);
                        mForecastAdapter.add(forecast);
                    }
                  //  mForecastAdapter.addAll(wordList);

                }
                Log.v(LOG_TAG,"Sorry!! Result is null");

            }

我也尝试使用addAll()方法,但为此我需要升级到API 11.所以这不是一个选项。对于信息:此结果变量不为空,并且在日志中,每次执行此代码集时,我都会获得正确的预测值。 我得到的例外是: java.lang.NullPointerException:尝试在空对象引用上调用虚方法'void android.widget.ArrayAdapter.add(java.lang.Object)'

这是我的代码:

package com.example.khatri.sunshine.app;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.format.Time;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ForecastFragment extends Fragment {
    String[] resultfinal = new String[100];
    public ForecastFragment() {
    }
    ArrayAdapter<String> mForecastAdapter;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
                // Add this line in order for this fragment to handle menu events.
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.forecastfragment, menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.action_refresh) {

            FetchWeatherTask fetchWeatherTask = new FetchWeatherTask();
                    fetchWeatherTask.execute("94043");
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        List<String> weekForecast = new ArrayList<String>();
        weekForecast.add("Today-Sunny-88/63");
        weekForecast.add("Tomorrow FOggy 77/46");
        weekForecast.add("Day after sunny again 45/34");
        weekForecast.add("Thur-foggy again 65/34");
        weekForecast.add("Fri afternoon rainy 76/32");
        weekForecast.add("Sat happy sat 65/12");
        weekForecast.add("Day after sunny again 45/34");
        weekForecast.add("Thur-foggy again 65/34");
        weekForecast.add("Fri afternoon rainy 76/32");
        weekForecast.add("Sat happy sat 65/12");

        ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<String>(
        getContext(),
        R.layout.list_item_forecast,
        R.id.list_item_forecast_textview,
        weekForecast);

        ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
        listView.setAdapter(mForecastAdapter);


        return rootView;

    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

        protected String[] doInBackground(String... params) {

            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

// Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            String format = "json";
            String units = "metric";
            int numDays = 7;
            String appid = "c70ffaa8bf3c10556dc3e82d72d23677";

            try {

                final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
                final String FORMAT_PARAM = "mode";
                final String QUERY_PARAM = "q";
                final String UNITS_PARAM = "units";
                final String DAYS_PARAM = "cnt";
                final String APPID_PARAM = "appid";

                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                        .appendQueryParameter(QUERY_PARAM, params[0])
                        .appendQueryParameter(FORMAT_PARAM, format)
                        .appendQueryParameter(UNITS_PARAM, units)
                        .appendQueryParameter(DAYS_PARAM, Integer.toString(numDays))
                        .appendQueryParameter(APPID_PARAM, appid)
                        .build();

                URL url = new URL(builtUri.toString());

                Log.v(LOG_TAG, "Built URI " + builtUri.toString());

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    forecastJsonStr = null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {

                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    forecastJsonStr = null;
                }
                forecastJsonStr = buffer.toString();

                Log.v(LOG_TAG, "forecast JSON string: " + forecastJsonStr);
            } catch (Exception e) {
                Log.e("PlaceholderFragment", "Error ", e);

                forecastJsonStr = null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        resultfinal = getWeatherDataFromJson(forecastJsonStr, numDays);
                        reader.close();
                    } catch (final IOException e) {
                        Log.e("PlaceholderFragment", "Error closing stream", e);
                    }
                    catch (JSONException jsonexception)
                    {
                        Log.e(LOG_TAG,"JSON Exception",jsonexception);
                    }
                }
            }
            return resultfinal;
        }



        private String getReadableDateString(long time) {
            SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
            return shortenedDateFormat.format(time);
        }

        private String formatHighLows(double high, double low) {
            // For presentation, assume the user doesn't care about tenths of a degree.
            long roundedHigh = Math.round(high);
            long roundedLow = Math.round(low);

            String highLowStr = roundedHigh + "/" + roundedLow;
            return highLowStr;
        }


        private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
                throws JSONException {

            // These are the names of the JSON objects that need to be extracted.
            final String OWM_LIST = "list";
            final String OWM_WEATHER = "weather";
            final String OWM_TEMPERATURE = "temp";
            final String OWM_MAX = "max";
            final String OWM_MIN = "min";
            final String OWM_DESCRIPTION = "main";

            JSONObject forecastJson = new JSONObject(forecastJsonStr);
            JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);


            Time dayTime = new Time();
            dayTime.setToNow();


            int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);


            dayTime = new Time();

            String[] resultStrs = new String[numDays];
            for(int i = 0; i < weatherArray.length(); i++) {
                // For now, using the format "Day, description, hi/low"
                String day;
                String description;
                String highAndLow;

                // Get the JSON object representing the day
                JSONObject dayForecast = weatherArray.getJSONObject(i);

                // The date/time is returned as a long.  We need to convert that
                // into something human-readable, since most people won't read "1400356800" as
                // "this saturday".
                long dateTime;
                // Cheating to convert this to UTC time, which is what we want anyhow
                dateTime = dayTime.setJulianDay(julianStartDay+i);
                day = getReadableDateString(dateTime);

                // description is in a child array called "weather", which is 1 element long.
                JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description = weatherObject.getString(OWM_DESCRIPTION);

                // Temperatures are in a child object called "temp".  Try not to name variables
                // "temp" when working with temperature.  It confuses everybody.
                JSONObject temperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
                double high = temperatureObject.getDouble(OWM_MAX);
                double low = temperatureObject.getDouble(OWM_MIN);

                highAndLow = formatHighLows(high, low);
                resultStrs[i] = day + " - " + description + " - " + highAndLow;

            }

            for (String s : resultStrs) {
                Log.v(LOG_TAG, "Forecast entry: " + s);
            }
            //onPostExecute(resultStrs);

            return resultStrs;



        }

        @Override
        protected void onPostExecute(String[] result) {

            List<String> wordList = new ArrayList<>();
                   wordList = Arrays.asList(result);
            if(wordList!= null)
            {

               // mForecastAdapter.add(result.toString());
                for(String forecast: wordList)
                {
                    Log.v(LOG_TAG,"forecast value: "+forecast);
                    mForecastAdapter.add(forecast);
                }
              //  mForecastAdapter.addAll(wordList);

            }
            Log.v(LOG_TAG,"Sorry!! Reuslt is null");

        }


    }


}

4 个答案:

答案 0 :(得分:0)

当您获取全局变量时,您只需初始化第一次并在全班使用。我希望这对你有所帮助,你得到了解决方案。

public class ForecastFragment extends Fragment {

        ArrayAdapter<String> mForecastAdapter;


        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        ......
        mForecastAdapter = new ArrayAdapter<String>(
                            getContext(),
                            R.layout.list_item_forecast,
                            R.id.list_item_forecast_textview,
                            weekForecast);

        .....       
        }
    }

答案 1 :(得分:0)

您在oncreateView()中初始化了本地mForecastAdapter变量,并将值添加到未初始化的全局mForecastAdapter。这就是为什么它给你空指针。

答案 2 :(得分:0)

点是片段的lifeCycle。 在调用onOptionsItemSelected()方法之前,你能确保调用了onCreteView()方法吗?

我建议您添加一些日志代码或设置一些面包点以查看首先调用的方法。

答案 3 :(得分:0)

我从另一个帖子得到了答案:

清除arrayadapter,mforecastAdapter.clear()然后, 将值添加到此适配器然后, mForecastAdapter.notifyDataSetChanged();

这描绘了我的列表视图中的变化:)