我有一个显示瓷砖网格视图的 Android 应用小部件。每个磁贴都包含股票报价信息。我从网络服务器查询股票报价信息并将其存储在 ArrayList (stock_info_list) 中——RemoteViewsFactory 的成员变量。
问题是在一段时间不活动之后,当我尝试滚动 gridview 时,它变空 - 出现空视图 - 意味着 ArrayList 被清除。为什么 RemoteViewFactory 中的 ArrayList 会自动清除?如果我按下刷新按钮,这会导致 onDataChanged() 被调用,以重新填充 ArrayList,小部件将再次填充股票报价。
我怎样才能使数据保持持久性,以便在滚动小部件时数据不会消失?
package com.screenulator.stocktile;
import java.text.DecimalFormat;
import android.annotation.SuppressLint;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.GradientDrawable;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import android.widget.TextView;
@SuppressLint("NewApi")
public class MyWidgetService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent arg0)
{
return new MyRemoteViewsFactory(this.getApplicationContext(), arg0);
}
}
class MyRemoteViewsFactory implements RemoteViewsService.RemoteViewsFactory
{
final public DecimalFormat DF2 = new DecimalFormat("#.##");
public ArrayList<StockInfo> stock_info_list = new ArrayList<StockInfo>();
private Context mContext;
private int mAppWidgetId;
public MyRemoteViewsFactory(Context context, Intent intent)
{
mContext = context;
mAppWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
}
public void onCreate()
{
}
@Override
public int getCount()
{
return stock_info_list.size();
}
@Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
@Override
public RemoteViews getLoadingView() {
// TODO Auto-generated method stub
return null;
}
@Override
public RemoteViews getViewAt(int position)
{
Singleton s = Singleton.getInstance();
RemoteViews rv = new RemoteViews(mContext.getPackageName(),
R.layout.my_grid_layout);
// rv.setTextViewText(R.id.symbol, "Hello");
StockInfo symbol_info = stock_info_list.get(position);
if (symbol_info != null)
{
// details of initialize each grid omitted
}
return rv;
}
@Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 1;
}
@Override
public boolean hasStableIds() {
return true;
}
@Override
public void onDataSetChanged() {
// TODO Auto-generated method stub
Log.i("remoteviews_factory", "onDataSetChanged");
DataServerInstance d = DataServerInstance.getInstance();
if (d.stock_info_list.size() > 0)
{
stock_info_list.clear();
stock_info_list = d.duplicate_stock_info_list();
}
}
@Override
public void onDestroy() {
// TODO Auto-generated method stub
}
}