Как отправить данные из фрагмента поставщику виджетов? - PullRequest
0 голосов
/ 23 декабря 2018

Я нашел здесь несколько тем, но ни один из них не посвящен этому конкретному вопросу.Я храню список массивов в Shared Preferences и Gson во фрагменте (первый пример кода ниже) RemoteViewsFactory также будет реализован (2-й код).Этот список будет отображаться в виджете.Получу ли я список непосредственно в 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
        }
    }
...