无法在AsycTask中返回字符串数组

时间:2016-09-26 10:36:46

标签: java android android-asynctask

如果我更改为字符串,则返回字符串值。但我无法弄清楚为什么它没有返回字符串值。我检查所有仍然无法得到它。

我的错误在哪里?提前谢谢。

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

 private String[] getWeatherDataFromJson(String forecastJsonStr)
            throws JSONException {

        // These are the names of the JSON objects that need to beextracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "temp_max";
final String OWM_MIN = "temp_min";
final String OWM_DESCRIPTION = "main";

JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
JSONObject city=forecastJson.getJSONObject("city");
String name=city.getString("name");

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

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_DESCRIPTION);
            double high = temperatureObject.getDouble(OWM_MAX);
            double low = temperatureObject.getDouble(OWM_MIN);

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

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


    }

doinbackground也在string []

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


        //if there is no zip code nothing to look it
        if (params.length == 0) {

            return null;

        }

        // These two need to be declared outside the try/catch
       // so that they can be closed in the finally block.
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;

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


        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are available at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
            final String QUERY_PARAM = "id";
            final String APPID = "APPID";


            Uri builturi = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .appendQueryParameter(QUERY_PARAM, params[0])
                    .appendQueryParameter(APPID, appid)
                    .build();
            URL URl;
            URl = new URL(builturi.toString());
            Log.v(LOG_TAG, "BUILT URI" + builturi.toString());


            //  URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/city?id=524901&APPID=bc16214cbb434f8386d9b0c3d7eebc17");

            // 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) {
                // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                // But it does make debugging a *lot* easier if you print out the completed
                // buffer for debugging.
                buffer.append(line + "\n");
            }

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

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            Log.e("PlaceholderFragment", "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attempting
            // to parse it.
            //forecastJsonStr = null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e("PlaceholderFragment", "Error closing stream", e);
                }
            }

        }
        try {
            return getWeatherDataFromJson(forecastJsonStr);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //this will happen if there was an error getting  or parsing the document
        return null;
    }

    @Override
    protected void onPostExecute(String[] result) {
        if (result!=null){
            Toast.makeText(getActivity(),"working", Toast.LENGTH_LONG).show();
            arrayAdapter.clear();
           for (String dayforcast:result){
                arrayAdapter.add(dayforcast);
            }
        }
    //i used to figure out it is working or not
    // not much significance
if (result==null){
Toast.makeText(getActivity(),"not working", Toast.LENGTH_LONG).show();
        }
    }
}
    //Onpost in string[],asyctask also string[],dolnbackground also string[]

1 个答案:

答案 0 :(得分:0)

在添加了所有dayforcast元素后,尝试在onPostExecute上调用arrayadapter上的notifyDataSetChanged; - )