如何将数据从片段发送到窗口小部件提供程序?

时间:2018-12-23 08:01:42

标签: android widget broadcastreceiver gson sharedpreferences

我在这里找到了几个线程,但是没有一个线程可以解决这个特定问题。我在共享首选项和Gson的Fragment中存储一个数组列表(下面的第一个代码示例),RemoteViewsFactory也将被实现(第二个代码)。此列表将显示在窗口小部件中。我是否可以直接在WidgetProvider(第4个代码)中检索列表?还是将其从Fragment类发送到Provider类?这是我第一次在小部件中检索SharedPreferences。预先感谢您。

public class IngredientsFragment extends Fragment
{

    private static final String TAG = IngredientsFragment.class.getSimpleName();

    @BindView(R.id.recyclerview_ingredients)
    RecyclerView mIngredientRecyclerView;

    ArrayList<Ingredients> ingredientsArrayList;
    Recipes recipes;

    // Final Strings to store state information about the list of ingredients and list index
    private static final String KEY_INGREDIENTS_LIST = "ingredients_list";

    /**
     * Mandatory empty constructor for the fragment manager to instantiate the fragment
     */
    public IngredientsFragment()
    {
    }

    /**
     * Inflates the fragment layout file and sets the correct resource for the image to display
     */
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        //Inflate the Ingredients fragment layout
        View rootView = inflater.inflate(R.layout.fragment_ingredient, container, false);

        // Bind the views
        ButterKnife.bind(this, rootView);

        Bundle bundle = this.getArguments();
        if (bundle != null)
        {
            recipes = getArguments().getParcelable("Recipes");

            ingredientsArrayList = new ArrayList<>();
            ingredientsArrayList = recipes.getRecipeIngredients();

            if (savedInstanceState != null)
            {
                //Restore the fragment's state here
                ingredientsArrayList = savedInstanceState.getParcelableArrayList(KEY_INGREDIENTS_LIST);
            }

            RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getContext());
            mIngredientRecyclerView.setLayoutManager(mLayoutManager);
            Log.i("listIngredients", ingredientsArrayList.size() + "");

            IngredientsAdapter ingredientsAdapter = new IngredientsAdapter(ingredientsArrayList, getContext());
            mIngredientRecyclerView.setAdapter(ingredientsAdapter);

            mIngredientRecyclerView.addItemDecoration(new VerticalSpacingDecoration(25));

            //Store Ingredients in SharedPreferences
            SharedPreferences appSharedPrefs = PreferenceManager.getDefaultSharedPreferences((getActivity()).getApplicationContext());
            SharedPreferences.Editor prefsEditor = appSharedPrefs.edit();

            Gson gson = new Gson();
            String json = gson.toJson(ingredientsArrayList);
            prefsEditor.putString("IngredientsList_Widget", json);
            prefsEditor.apply();


        }
        return rootView;
    }

    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);

        //Save the fragment's state here
        outState.putParcelableArrayList(KEY_INGREDIENTS_LIST, ingredientsArrayList);
        super.onSaveInstanceState(outState);
    }
}

RemoteViewFactory类:

public class RecipeWidgetViewFactory implements RemoteViewsService.RemoteViewsFactory
{
    private ArrayList<Ingredients> mIngredientsList;
    private Context mContext;

    public RecipeWidgetViewFactory(Context context)
    {
        mContext = context;
    }

    @Override
    public void onCreate() {
    }

    @Override
    public int getCount()
    {
        return mIngredientsList.size();
    }

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

    @Override
    public RemoteViews getViewAt(int position) {

        Ingredients ingredient = mIngredientsList.get(position);

        RemoteViews itemView = new RemoteViews(mContext.getPackageName(), R.layout.ingredient_list_item);

        itemView.setTextViewText(R.id.ingredient_quantity, ingredient.getIngredientQuantity());
        itemView.setTextViewText(R.id.ingredient_measure, ingredient.getIngredientMeasure());
        itemView.setTextViewText(R.id.ingredient_name, ingredient.getIngredientName());

        Intent intent = new Intent();
        intent.putExtra(RecipeWidgetProvider.EXTRA_ITEM, ingredient);

        return itemView;

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

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

    @Override
    public void onDataSetChanged() {

        //code structure based on this link:
        //https://stackoverflow.com/questions/37927113/how-to-store-and-retrieve-an-object-from-gson-in-android
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext);

        Gson gson = new Gson();
        Type type = new TypeToken<List<Ingredients>>() {}.getType();
        String gsonString = sharedPreferences.getString("userImages", "");
        mIngredientsList = gson.fromJson(gsonString, type);

    }

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

    @Override
    public void onDestroy() {

    }
}

RemoteViewService类。

public class RecipeWidgetService extends RemoteViewsService
{
    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent)
    {
        return new RecipeWidgetViewFactory(getApplicationContext());
   }
}

WidgetProvider类。

/**
 * Implementation of App Widget functionality.
 */
public class RecipeWidgetProvider extends AppWidgetProvider {
    //The following code is based on the code in these links:
    //https://joshuadonlan.gitbooks.io/onramp-android/content/widgets/collection_widgets.html
    //http://www.vogella.com/tutorials/AndroidWidgets/article.html

    public static final String EXTRA_ITEM =
            "annin.my.android.RecipeWidgetProvider.EXTRA_ITEM";

    /*
    This method is called once a new widget is created as well as every update interval.
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager,
                         int[] appWidgetIds) {
        for (int i = 0; i < appWidgetIds.length; i++) {
            // Construct the RemoteViews object
            RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.recipe_widget_provider);

            // Register an onClickListener
            Intent intent = new Intent(context, RecipeWidgetProvider.class);

            intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
            intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

            // Instruct the widget manager to update the widget
           // appWidgetManager.updateAppWidget(appWidgetId, views);
        }

     //    Build the intent to call the service
        Intent intent = new Intent(context.getApplicationContext(),
              RecipeWidgetService.class);
           intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);

       //  Update the widgets via the service
          context.startService(intent);
}

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

        super.onReceive(context, intent);
    }


        @Override
        public void onEnabled (Context context){
        // Enter relevant functionality for when the first widget is created
        }


        @Override
        public void onDisabled (Context context){
        // Enter relevant functionality for when the last widget is disabled
        }
    }

0 个答案:

没有答案