-1

appwidget を作成し、appwidget(stackview ウィジェット) に json のアイテム (画像とテキスト) を表示しようとしましたが、アプリ ウィジェットを正常に作成し、ウィジェットに json を表示することもできますが、ウィジェットをクリックする必要がある場合、エラー NullPointerException が発生します

これは私のコードです:

public class BriGeRemoteViewsService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {

    return new BriGeRemoteViewsFactory(this.getApplicationContext(), intent);
}

static class BriGeRemoteViewsFactory implements RemoteViewsFactory {

    public static ArrayList<ItemI> itemList;
    private static Context context;
    private int appWidgetId;

    public BriGeRemoteViewsFactory(Context context, Intent intent) {
        this.context = context;
                    itemList = new ArrayList<ItemI>();
        this.appWidgetId = intent.getIntExtra(
                AppWidgetManager.EXTRA_APPWIDGET_ID,
                AppWidgetManager.INVALID_APPWIDGET_ID);
    }

    @Override
    public void onCreate() {
        itemList = getData();
    }

    @Override
    public void onDataSetChanged() {
        itemList = getData();
    }

    @Override
    public void onDestroy() {
        itemList.clear();
    }

    @Override
    public int getCount() {
        if (itemList != null)
            return itemList.size();
        else
            return 0;
    }

    @Override
    public RemoteViews getViewAt(int position) {
        ItemI item = itemList.get(position);

        RemoteViews rv = new RemoteViews(context.getPackageName(),
                R.layout.item_view);

        rv.setTextViewText(R.id.widgettitle, item.getTitle());

        rv.setImageViewBitmap(R.id.img, getImageBitmap(item.getImage()));

        Bundle extras = new Bundle();
        extras.putInt(BriGeWidgetProvider.EXTRA_ITEM, position);
        Intent fillIntent = new Intent();
        fillIntent.putExtras(extras);

        rv.setOnClickFillInIntent(R.id.item_root, fillIntent);

        return rv;
    }

    private Bitmap getImageBitmap(String url) {
        Bitmap bm = null;
        try {
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
        } catch (IOException e) {
        }
        return bm;
    }

    @Override
    public RemoteViews getLoadingView() {
        return null;
    }

    @Override
    public int getViewTypeCount() {
        return 1;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    private static ArrayList<ItemI> getData() {
        JsonParser jp = new JsonParser(context);
        return jp.getDataAsList();
    }
}

}

public class BriGeWidgetProvider extends AppWidgetProvider {
public static final String TOAST_ACTION = "com.example.android.stackwidget.TOAST_ACTION";
public static final String EXTRA_ITEM = "com.example.android.stackwidget.EXTRA_ITEM";
private RemoteViews views;
private Intent intent;


@Override
public void onDeleted(Context context, int[] appWidgetIds) {
    super.onDeleted(context, appWidgetIds);
}
@Override
public void onDisabled(Context context) {
    super.onDisabled(context);
}

@Override
public void onEnabled(Context context) {
    super.onEnabled(context);
}

@Override
public void onReceive(Context context, Intent intent) {

    if (intent.getAction().equals(TOAST_ACTION)) {

        int viewIndex = intent.getIntExtra(EXTRA_ITEM, 0);

        ItemI item = BriGeRemoteViewsFactory.itemList.get(viewIndex);

        context.startActivity(new Intent(context, WidgetResult.class)
                .putExtra("KEY_title", item.getTitle())
                .putExtra("KEY_desc", item.getDescription())

                .putExtra("KEY_tabula", item.getJournal())
                .putExtra("KEY_datetime", item.getPubDate())
                .putExtra("KEY_image", item.getImage())
                .putExtra("KEY_startID", item.getStatID())

                .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));

    }
    super.onReceive(context, intent);
}

@SuppressWarnings("deprecation")
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {

    final int N = appWidgetIds.length;
    for (int i = 0; i < N; i++) {
        int appWidgetId = appWidgetIds[i];

        intent = new Intent(context, BriGeRemoteViewsService.class);

        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);

        views = new RemoteViews(context.getPackageName(),
                R.layout.widget_layout);
        views.setRemoteAdapter(appWidgetId, R.id.stackWidgetView, intent);

        views.setEmptyView(R.id.stackWidgetView, R.id.stackWidgetEmptyView);

        Intent templateIntent = new Intent(context,
                BriGeWidgetProvider.class);
        templateIntent.setAction(BriGeWidgetProvider.TOAST_ACTION);
        templateIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                appWidgetId);
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
        PendingIntent templatePendingIntent = PendingIntent.getBroadcast(
                context, 0, templateIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        views.setPendingIntentTemplate(R.id.stackWidgetView,
                templatePendingIntent);

        appWidgetManager.updateAppWidget(appWidgetId, views);
    }
    super.onUpdate(context, appWidgetManager, appWidgetIds);
}

}

例外はこの行です

ItemI item = BriGeRemoteViewsFactory.itemList.get(viewIndex);

これは WidgetResult クラスです

public class WidgetResult extends Activity {
public TextView widgetTitle, widgetDescription, widgetTabula, widgetDate;
public String resulttitle, resutlTabul, resultdesc, resultimage,
        resultPutdate, resutlStartID;
public ImageView img;

private ConnectionDetector cd;
AlertDialogManager alert = new AlertDialogManager();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.widget_result);

    cd = new ConnectionDetector(getApplicationContext());

    widgetTitle = (TextView) findViewById(R.id.widgettitleDetails);
    widgetDescription = (TextView) findViewById(R.id.widgetdescriptionDetails);
    img = (ImageView) findViewById(R.id.widgetimageDetails);
    widgetTabula = (TextView) findViewById(R.id.widgetDateTimeDetails);
    widgetDate = (TextView) findViewById(R.id.widgetTabula);

    Intent intent = getIntent();

    resulttitle = intent.getStringExtra("KEY_title");
    resultdesc = intent.getStringExtra("KEY_desc");

    resutlTabul = intent.getStringExtra("KEY_tabula");
    resultimage = intent.getStringExtra("KEY_image");
    resultPutdate = intent.getStringExtra("KEY_datetime");
    resutlStartID = intent.getStringExtra("KEY_startID");

    widgetTabula.setText(resutlTabul);
    widgetTabula.setTypeface(MainActivity.tf2);
    String ab = resultimage.replaceAll("-c.jpg", ".jpg");

    Log.e("imageeeeeeeeeeeeeeeeeeeeeeeeeeeee", ab);
    if (!cd.isConnectingToInternet()) {

    } else {
        new DownloadTask().execute(ab);
    }

    widgetTitle.setText(resulttitle);
    widgetTitle.setTypeface(MainActivity.tf2);

    resultdesc = resultdesc.trim();

    widgetDescription.setText(resultdesc);

}

private Bitmap downloadUrl(String strUrl) throws IOException {
    Bitmap bitmap = null;
    InputStream iStream = null;
    try {
        URL url = new URL(strUrl);

        HttpURLConnection urlConnection = (HttpURLConnection) url
                .openConnection();

        urlConnection.connect();

        iStream = urlConnection.getInputStream();

        bitmap = BitmapFactory.decodeStream(iStream);

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        iStream.close();
    }

    return bitmap;
}

private class DownloadTask extends AsyncTask<String, Integer, Bitmap> {
    Bitmap bitmap = null;

    @Override
    protected Bitmap doInBackground(String... url) {
        try {
            bitmap = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return bitmap;
    }

    @Override
    protected void onPostExecute(Bitmap result) {

        img.setImageBitmap(result);
        Log.e("Bitmapppppppppppppppp", result.toString());

        // Toast.makeText(getBaseContext(),
        // "Image downloaded successfully",Toast.LENGTH_SHORT).show();
    }

}

}

初めてアプリが完璧に動作しますウィジェットに触れることができ、問題はありませんが、アプリを閉じてからクリックする必要があります-例外があります

誰かが解決策を知っているなら、私を助けてくださいありがとう

私の丸太猫エラー

4

1 に答える 1

0

itemListinBriGeRemoteViewsFactoryはインスタンス化されないため、インスタンス化するBriGeRemoteViewsFactory.itemListとnullになります。修正は、以下の行をコンストラクターに追加してインスタンス化することですBriGeRemoteViewsFactory

itemList = new ArrayList<ItemI>();
于 2014-02-24T19:47:09.843 に答える