在Android应用上显示小部件的更新值

时间:2014-12-07 00:22:14

标签: android widget

我正在制作移动应用程序的小部件。窗口小部件应该从互联网上的.JSON文件更新数据。我正在使用Android Studio。此时我的小部件从.JSON获取数据,但我无法弄清楚如何在我的小部件上显示这些值。 类FetchWeatherTaskk从Internet获取值,但它在方法onUpdate的末尾执行,因此我想要在小部件中显示的值对我来说始终为空。

FetchWeatherTaskk weatherTask = new FetchWeatherTaskk();
weatherTask.execute("94043");

这些行调用类并从Internet获取数据,但它总是在方法结束时执行。我不明白为什么。

我知道我必须使用远程视图来更改窗口小部件中的文本。但在将它们发送到小部件之前,我不知道如何获取值。

我很抱歉我的英语不好。

我的小部件类:

public class WidgetOru extends AppWidgetProvider {

String v1, v2;

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

    private String[] getWeatherDataFromJson(String forecastJsonStr)
            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_zeno_AT_5s_C = "zeno_AT_5s_C";
        final String OWM_sws200_synop_code = "sws200_synop_code";


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


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

        // description is in a child array called "weather", which is 1 element long.

        JSONObject weatherObject;
        weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        v1 = weatherObject.getString(OWM_zeno_AT_5s_C);
        weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
        v2 = weatherObject.getString(OWM_sws200_synop_code);

        return null;
    }

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

        // If there's no zip code, there's nothing to look up.  Verify size of params.
        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;

        try {
            // Construct the URL for the OpenWeatherMap query
            // Possible parameters are avaiable at OWM's forecast API page, at
            // http://openweathermap.org/API#forecast
            final String FORECAST_BASE_URL =
                    "Link_to_.json_is_here;


            Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                    .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.
                return 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.
                return null;
            }
            forecastJsonStr = buffer.toString();

            Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Error ", e);
            // If the code didn't successfully get the weather data, there's no point in attemping
            // to parse it.
            return null;
        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (final IOException e) {
                    Log.e(LOG_TAG, "Error closing stream", e);
                }
            }
        }

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

        // This will only happen if there was an error getting or parsing the forecast.
        return null;
    }

}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
    // There may be multiple widgets active, so update all of them
    super.onUpdate(context, appWidgetManager, appWidgetIds);
    final int N = appWidgetIds.length;
    CharSequence widgetText = context.getString(R.string.appwidget_text);
    FetchWeatherTaskk weatherTask = new FetchWeatherTaskk();
    weatherTask.execute("94043");

    for (int i = 0; i < N; i++) {
        int widgetID = appWidgetIds[i];
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.widget_oru);
        views.setTextViewText(R.id.appwidget_text, widgetText);     //Paraso teksta is XML
        views.setTextViewText(R.id.appwidget_text, v1);             //Pakeicia teksta i v1 kuris turetu rodyt temperatura bet nerodo
        appWidgetManager.updateAppWidget(widgetID, views);
    }

}}

0 个答案:

没有答案