即使在onCreate中声明后,ListAdapter值在Async类中也为null

时间:2015-06-26 12:46:13

标签: android

我调试了整个程序,mForecastAdapter中的错误onPostExecution为空,因此任何使用mForecastAdapter.clear()的尝试都会导致错误,我甚至无法理解mForecastAdapter是全局变量它在onCreate()函数中初始化,请帮助

代码

public class ForecastFragment extends Fragment {

    private ArrayAdapter<String> mForecastAdapter=null;
    private List<String> weekForecast=null;
    private Context con;
    public ForecastFragment(){

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView= inflater.inflate(R.layout.fragment_main, container, false);

        //con=getActivity().getApplicationContext();
        String[] forecastArray={
                "Mon 6/23 - Sunny -31/17",
                "Tue 6/24 - Foggy -21/8",
                "Wed 6/25 - Cloudy -22/17",
                "Thurs 6/26 - Rainy -18/11",
                "Fri 6/27 - Foggy -21/10",
                "Sat 6/28 - TRAPPED IN WEATHERSTATION -23/18",
                "Sun 6/29 - Sunny -31/17"};

        weekForecast=new ArrayList<String>(Arrays.asList(forecastArray));
        mForecastAdapter=new ArrayAdapter<String>(getActivity(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,forecastArray );
        ListView listview=(ListView)rootView.findViewById(R.id.listview_forecast);
        listview.setAdapter(mForecastAdapter);

        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String forecast=mForecastAdapter.getItem(position);
                callActivity(forecast);

            }
        });


        return rootView;
    }

    private void callActivity(String forecast) {
        Intent myIntent=new Intent(getActivity(), DetailedForecast.class).putExtra("INFORMATION",forecast);
        startActivity(myIntent);
    }

    public class FetchWeatherTask extends AsyncTask<String,Void,String[]>{

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

            if(params.length==0){
                return null;
            }

            HttpURLConnection urlConnection=null;
            BufferedReader reader=null;

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

            try {

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

                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))
                        .build();

                Log.i("ALEX",builtUri.toString());


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

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

                Log.v("ALEX","JSON"+forecastJsonStr);

            } catch (MalformedURLException ee) {
                ee.printStackTrace();
            }catch (IOException ee){
                Log.e("PlaceholderFragment", "Error ", ee);
            }finally {
                if(urlConnection!=null){
                    urlConnection.disconnect();
                }

                if(reader!=null){
                    try{
                        reader.close();
                    } catch (IOException ee) {
                        Log.e("PlaceholderFragment", "Error closing stream", ee);
                    }
                }
            }

            try{
                return getWeatherDataFromJson(forecastJsonStr,numDays);
            }catch (JSONException e){
                Log.e("ALEX",e.getMessage(),e);
                e.printStackTrace();
            }

            return null;
        }

         //CODE FROM UDACITY STARTS
         private String getReadableDateString(long time){

             SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
             return shortenedDateFormat.format(time);
         }
         //CODE FROM UDACITY ENDS

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

             final String OWM_LIST="list";
             final String OWM_WEATHER="weather";
             final String OWM_TEMP="temp";
             final String OWM_MAX="max";
             final String OWM_MIN="min";
             final String OWM_DESCRIPTION="main";

             JSONObject weather=new JSONObject(forecastJsonStr);
             JSONArray days=weather.getJSONArray(OWM_LIST);

             //CODE FROM UDACITY STARTS
             Time dayTime = new Time();
             dayTime.setToNow();
             int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
             //CODE FROM UDACITY ENDS

             String[] resultStrs=new String[numDays];
             for(int i=0;i<days.length();i++){

                 String day="";
                 String description;
                 String highAndLow;

                 JSONObject dayForecast=days.getJSONObject(i);


                 //CODE FROM UDACITY STARTS
                 long dateTime;
                 dateTime = dayTime.setJulianDay(julianStartDay+i);
                 day = getReadableDateString(dateTime);
                 //CODE FROM UDACITY ENDS


                 JSONObject weatherObject=dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                 description=weatherObject.getString(OWM_DESCRIPTION);


                 JSONObject temp=dayForecast.getJSONObject(OWM_TEMP);
                 double high=temp.getDouble(OWM_MAX);
                 double low=temp.getDouble(OWM_MIN);
                 //highAndLow=formatHighLows(high, low);

                 highAndLow=Double.toString(Math.round(high))+"/"+Double.toString(Math.round(low));


                 resultStrs[i]=day+" - "+description+" - "+highAndLow;

             }

             for (String s : resultStrs) {
                 Log.v("ALEX", "Forecast entry: " + s);
             }
             return resultStrs;


         }


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

            mForecastAdapter.clear();
            mForecastAdapter.addAll(strings);

         }
     }
}

这是错误,请看第一行

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ArrayAdapter.clear()' on a null object reference
        at com.betatech.alex.sunshine.ForecastFragment$FetchWeatherTask.onPostExecute(ForecastFragment.java:269)
        at com.betatech.alex.sunshine.ForecastFragment$FetchWeatherTask.onPostExecute(ForecastFragment.java:89)
        at android.os.AsyncTask.finish(AsyncTask.java:632)
        at android.os.AsyncTask.access$600(AsyncTask.java:177)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:645)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:135)
        at android.app.ActivityThread.main(ActivityThread.java:5312)
        at java.lang.reflect.Method.invoke(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:372)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)

2 个答案:

答案 0 :(得分:0)

要进行ListView更新,您应该更新提供给适配器的阵列并致电adapter.notifyDataSetCHanged()。适配器将为您处理其余部分。

即。您应该forecastArray全局(在课程顶部声明),然后在onPostExecute()中,您可以执行以下操作:

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

               forecastArray = strings;
               mForecastAdapter.notifyDataSetChanged();

             }

如果这有帮助,或者您需要更多信息,请告诉我。

编辑:这是我在评论中试图向您解释的代码。

public class ForecastFragment extends Fragment {

    private ArrayAdapter<String> mForecastAdapter;
    private List<String> weekForecast=null;
    private Context con;
    ListView listview;
    public ForecastFragment(){

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView= inflater.inflate(R.layout.fragment_main, container, false);

        //con=getActivity().getApplicationContext();

        listview=(ListView)rootView.findViewById(R.id.listview_forecast);


        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String forecast=mForecastAdapter.getItem(position);
                callActivity(forecast);

            }
        });


        return rootView;
    }

    private void callActivity(String forecast) {
        Intent myIntent=new Intent(getActivity(), DetailedForecast.class).putExtra("INFORMATION",forecast);
        startActivity(myIntent);
    }

    public class FetchWeatherTask extends AsyncTask<String,Void,String[]> {

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

            if(params.length==0){
                return null;
            }

            HttpURLConnection urlConnection=null;
            BufferedReader reader=null;

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

            try {

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

                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))
                        .build();

                Log.i("SANJEEV", builtUri.toString());


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

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

                Log.v("SANJEEV_TAG","JSON"+forecastJsonStr);

            } catch (MalformedURLException ee) {
                ee.printStackTrace();
            }catch (IOException ee){
                Log.e("PlaceholderFragment", "Error ", ee);
            }finally {
                if(urlConnection!=null){
                    urlConnection.disconnect();
                }

                if(reader!=null){
                    try{
                        reader.close();
                    } catch (IOException ee) {
                        Log.e("PlaceholderFragment", "Error closing stream", ee);
                    }
                }
            }

            try{
                return getWeatherDataFromJson(forecastJsonStr,numDays);
            }catch (JSONException e){
                Log.e("SANJEEV",e.getMessage(),e);
                e.printStackTrace();
            }

            return null;
        }

        //CODE FROM UDACITY STARTS
        private String getReadableDateString(long time){

            SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
            return shortenedDateFormat.format(time);
        }
        //CODE FROM UDACITY ENDS

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

            final String OWM_LIST="list";
            final String OWM_WEATHER="weather";
            final String OWM_TEMP="temp";
            final String OWM_MAX="max";
            final String OWM_MIN="min";
            final String OWM_DESCRIPTION="main";

            JSONObject weather=new JSONObject(forecastJsonStr);
            JSONArray days=weather.getJSONArray(OWM_LIST);

            //CODE FROM UDACITY STARTS
            Time dayTime = new Time();
            dayTime.setToNow();
            int julianStartDay = Time.getJulianDay(System.currentTimeMillis(), dayTime.gmtoff);
            //CODE FROM UDACITY ENDS

            String[] resultStrs=new String[numDays];
            for(int i=0;i<days.length();i++){

                String day="";
                String description;
                String highAndLow;

                JSONObject dayForecast=days.getJSONObject(i);


                //CODE FROM UDACITY STARTS
                long dateTime;
                dateTime = dayTime.setJulianDay(julianStartDay+i);
                day = getReadableDateString(dateTime);
                //CODE FROM UDACITY ENDS


                JSONObject weatherObject=dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                description=weatherObject.getString(OWM_DESCRIPTION);


                JSONObject temp=dayForecast.getJSONObject(OWM_TEMP);
                double high=temp.getDouble(OWM_MAX);
                double low=temp.getDouble(OWM_MIN);
                //highAndLow=formatHighLows(high, low);

                highAndLow=Double.toString(Math.round(high))+"/"+Double.toString(Math.round(low));


                resultStrs[i]=day+" - "+description+" - "+highAndLow;

            }

            for (String s : resultStrs) {
                Log.v("SANJEEV", "Forecast entry: " + s);
            }
            return resultStrs;


        }


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


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

            listview.setAdapter(mForecastAdapter);


        }
    }
}

我尽可能快地把它扔在一起,所以如果有错误我很抱歉。但是,要关注的部分是类顶部的声明,我在onCreateView()onPostExecute()中所做的一些更改。

另外,我敦促你要求一点点要求,并且对你获得的免费帮助有点感激。如果我心情不好,我可能会(理所当然地)在你最后几次评论后告诉你在其他地方找到帮助。

答案 1 :(得分:0)

**只是把条件放在** **

if(!mForecastAdapter.isempty()){

mForecastAdapter.clear()

}