我是android开发的新手,我不太清楚如何为解析JSON数据并显示在列表中的应用程序创建一个appwidget。

最佳答案

我使用此链接(https://laaptu.wordpress.com/2013/07/19/android-app-widget-with-listview/)解决了我的问题。

它有一系列的教程
(1.app带有ListView的小部件
2.使用来自网络的数据填充应用程序小部件列表视图
3.下载图像并使用listview在appwidget的imageview上显示
4.使用ListView在appwidget上设置更新间隔
5,如何在手机重启后使Appwidget更新生效)

为了使用简单的JSON URL来获取图像和文本,我在第三篇教程的RemoteFetchService.java中进行了以下更改,

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.IBinder;
import android.util.Log;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.example.mk.widgets.data.DatabaseManager;
import com.example.mk.widgets.data.FileManager;

public class RemoteFetchService extends Service {

private int appWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;

JSONObject jsonobject;
JSONArray jsonarray;
AQuery aquery;
private String remoteJsonUrl =   "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors";

public static ArrayList<ListItem> listItemList;
private int count = 0;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

/*
 * Retrieve appwidget id from intent it is needed to update widget later
 * initialize our AQuery class
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent.hasExtra(AppWidgetManager.EXTRA_APPWIDGET_ID))
        appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    aquery = new AQuery(getBaseContext());
    new DownloadJSON().execute();
    return super.onStartCommand(intent, flags, startId);
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        listItemList = new ArrayList<ListItem>();
        // Retrieve JSON Objects from the given URL address
        jsonobject = JSONfunctions.getJSONfromURL(remoteJsonUrl);
        try {
            // Locate the array name in JSON
            jsonarray = jsonobject.getJSONArray("actors");

            for (int i = 0; i < jsonarray.length(); i++) {
                jsonobject = jsonarray.getJSONObject(i);
                // Retrive JSON Objects
                ListItem listItem = new ListItem();
                listItem.heading = jsonobject.getString("name");
                listItem.content = jsonobject.getString("country");
                listItem.imageUrl = jsonobject.getString("image");
                listItemList.add(listItem);
            }
            storeListItem();
        } catch (JSONException e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }
}
/**
 * Instead of using static ArrayList as we have used before,no we rely upon
 * data stored on database so saving the fetched json file content into
 * database and at same time downloading the image from web as well
 */
private void storeListItem() {
    DatabaseManager dbManager = DatabaseManager.INSTANCE;
    dbManager.init(getBaseContext());
    dbManager.storeListItems(appWidgetId, listItemList);

    int length = listItemList.size();
    for (int i = 0; i < length; i++) {
        ListItem listItem = listItemList.get(i);
        final int index = i;
        aquery.ajax(listItem.imageUrl, Bitmap.class,new AjaxCallback<Bitmap>() {
                    @Override
                    public void callback(String url, Bitmap bitmap, AjaxStatus status) {
                        super.callback(url, bitmap, status);
                        storeBitmap(index, bitmap);
                    };
                });
    }
}
/**
 * Saving the downloaded images into file and after all the download of
 * images be complete begin to populate widget as done previously
 */
private void storeBitmap(int index, Bitmap bitmap) {
    FileManager.INSTANCE.storeBitmap(appWidgetId, bitmap,
            listItemList.get(index).heading, getBaseContext());
    count++;
    Log.i("count",String.valueOf(count) + "::"+ Integer.toString(listItemList.size()));
    if (count == listItemList.size()) {
        count = 0;
        populateWidget();
    }

}

/**
 * Method which sends broadcast to WidgetProvider so that widget is notified
 * to do necessary action and here action == WidgetProvider.DATA_FETCHED
 */
private void populateWidget() {

    Intent widgetUpdateIntent = new Intent();
    widgetUpdateIntent.setAction(WidgetProvider.DATA_FETCHED);
    widgetUpdateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
            appWidgetId);
    sendBroadcast(widgetUpdateIntent);

    this.stopSelf();
}
}


JSONfunctions.java

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONfunctions {

public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
}
}


希望这对某人有帮助,并非常感谢(https://stackoverflow.com/users/739306/laaptu)提供的教程。

关于android - 如何创建AppWidget以显示JSON解析图像和文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33140384/

10-11 04:25