StackView Widget не отображается - PullRequest
0 голосов
/ 08 октября 2018

Я смотрел и читал много уроков, но ни в одном из них нет StackView с изображением.В данный момент мой виджет получает цвет фона, но ничего не отображается!

Это когда я запускаю эмулятор!

Вот действия с кодом:

Как видите, я передаю объект класса Automoviles, который я использую для заполнения RecyclerView.

    public class AdapterViewCars extends RecyclerView.Adapter<AdapterViewCars.RecyclerViewHolder>{
    private List<Automoviles> automovilesList;
    private Context context;

    public AdapterViewCars(Context context, List<Automoviles> itemList){
        this.automovilesList=itemList;
        this.context=context;
    }
    @NonNull
    @Override
    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_carros,null);
        RecyclerViewHolder rcv=new RecyclerViewHolder(view);
        return rcv;
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, final int position) {
        Automoviles automoviles=automovilesList.get(position);
        holder.txtTitulo.setText(automoviles.getMarca());
        Glide.with(context)
                .load(automoviles.getImagen())
                .into(holder.imgCarro);

        Intent imageIntent=new Intent(context, CarWidget.class);
        imageIntent.putExtra("widget_image",automoviles);
        holder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Automoviles model = automovilesList.get(position);
                Intent intent  =new Intent(context, CarDetailView.class);

                intent.putExtra("ListaVehiculos",model);
                context.startActivity(intent);
            }
        });
    }


    @Override
    public int getItemCount() {
        return this.automovilesList.size();
    }

    public class RecyclerViewHolder extends RecyclerView.ViewHolder  {

        @BindView(R.id.imgCarro)
        ImageView imgCarro;
        @BindView(R.id.txttitulo)
        TextView txtTitulo;

        public RecyclerViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this,itemView);

        }

    }

}

Теперь в этом сервисе я пытаюсь получить намерение получить изображение

public class WidgetService extends RemoteViewsService {
    SvAutomoviles svAutomoviles;
    List<Automoviles> mArraylistAutomoviles;
    FirebaseDatabase mFirebaseDatabase;
    DatabaseReference mDatabaseReference;



    @Override
    public RemoteViewsFactory onGetViewFactory(Intent intent) {
        return new WidgetItemFactory(getApplicationContext(),intent);
    }

    class WidgetItemFactory implements RemoteViewsFactory{
        private Context context;
        private int appWidgetId;
        String marca;
        String imagen;
        List<Automoviles> mAutos;
        Automoviles automoviles;

        WidgetItemFactory(Context context,Intent intent){
            this.context=context;
            this.appWidgetId=intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,
                    AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        @Override
        public void onCreate() {

            mFirebaseDatabase=FirebaseDatabase.getInstance();

            mDatabaseReference=FirebaseDatabase.getInstance().getReference();

            mArraylistAutomoviles=new ArrayList<>();


            Query query = mDatabaseReference.child(AppModel.Automoviles);
            query.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                    Automoviles automoviles = new Automoviles();

                    SvAutomoviles svAutomoviles=new SvAutomoviles();

                    /**
                     * Here you Create another Automoviles object to setLista_de_automoviles
                     *
                     */


                    automoviles.setLista_de_automoviles(svAutomoviles.GetAutomoviles(dataSnapshot));


                    mArraylistAutomoviles=automoviles.getLista_de_automoviles();
                    marca=automoviles.getMarca();
                    imagen=automoviles.getImagen();

                    /**
                     * Then you get the arraylist in the adapters constructor which receives as parameters
                     * AdapterViewCars(context,List<Automoviles)
                     */
                    AdapterViewCars adapterViewCars=new AdapterViewCars(getApplicationContext(), automoviles.getLista_de_automoviles());


                }
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });


            }

        @Override
        public void onDataSetChanged() {

        }

        @Override
        public void onDestroy() {

        }

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

        @Override
        public RemoteViews getViewAt(int position) {

            RemoteViews views=new RemoteViews(context.getPackageName(), R.layout.widget_item);
            views.setTextViewText(R.id.textView, (CharSequence) mArraylistAutomoviles.get(position));

            mAutos=new ArrayList<>();

           Automoviles autos= mArraylistAutomoviles.get(position);

           Intent intent=new Intent();
           automoviles=intent.getExtras().getParcelable("widget_image");
           String autoImagen=automoviles.getImagen();


           String image=autos.getImagen();

           Intent imageIntent=new Intent();
           imageIntent.putExtra("widget_image",image);


           return views;
        }

        @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;
        }
    }
}

Это действие по настройке моего виджета:

public class CarWidgetConfigureActivity extends Activity {

    private static final String PREFS_NAME = "com.example.mac.udacitycapstonefinalproject.Widget.CarWidget";
    private static final String PREF_PREFIX_KEY = "appwidget_";


    int mAppWidgetId = AppWidgetManager.INVALID_APPWIDGET_ID;
    EditText mAppWidgetText;


    View.OnClickListener mOnClickListener = new View.OnClickListener() {
        public void onClick(View v) {
            final Context context = CarWidgetConfigureActivity.this;

            // When the button is clicked, store the string locally
            String widgetText = mAppWidgetText.getText().toString();
            saveTitlePref(context, mAppWidgetId, widgetText);

            // It is the responsibility of the configuration activity to update the app widget
            AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
            CarWidget.updateAppWidget(context, appWidgetManager, mAppWidgetId);

            // Make sure we pass back the original appWidgetId
            Intent resultValue = new Intent();
            resultValue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, mAppWidgetId);
            setResult(RESULT_OK, resultValue);
            finish();
        }
    };

    public CarWidgetConfigureActivity() {
        super();
    }

    // Write the prefix to the SharedPreferences object for this widget
    static void saveTitlePref(Context context, int appWidgetId, String text) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.putString(PREF_PREFIX_KEY + appWidgetId, text);
        prefs.apply();
    }

    // Read the prefix from the SharedPreferences object for this widget.
    // If there is no preference saved, get the default from a resource
    static String loadTitlePref(Context context, int appWidgetId) {
        SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, 0);
        String titleValue = prefs.getString(PREF_PREFIX_KEY + appWidgetId, null);
        if (titleValue != null) {
            return titleValue;
        } else {
            return context.getString(R.string.appwidget_text);
        }
    }

    static void deleteTitlePref(Context context, int appWidgetId) {
        SharedPreferences.Editor prefs = context.getSharedPreferences(PREFS_NAME, 0).edit();
        prefs.remove(PREF_PREFIX_KEY + appWidgetId);
        prefs.apply();
    }

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);

        // Set the result to CANCELED.  This will cause the widget host to cancel
        // out of the widget placement if the user presses the back button.
        setResult(RESULT_CANCELED);

        setContentView(R.layout.car_widget_configure);
        mAppWidgetText = (EditText) findViewById(R.id.appwidget_text);
        findViewById(R.id.add_button).setOnClickListener(mOnClickListener);

        // Find the widget id from the intent.
        Intent intent = getIntent();
        Bundle extras = intent.getExtras();
        if (extras != null) {
            mAppWidgetId = extras.getInt(
                    AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID);
        }

        // If this activity was started with an intent without an app widget ID, finish with an error.
        if (mAppWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID) {
            finish();
            return;
        }

        mAppWidgetText.setText(loadTitlePref(CarWidgetConfigureActivity.this, mAppWidgetId));
    }
}

И это мой поставщик виджетов:

public class CarWidget extends AppWidgetProvider {

    String image="";



    static void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                                int appWidgetId) {

        CharSequence widgetText = CarWidgetConfigureActivity.loadTitlePref(context, appWidgetId);
        // Construct the RemoteViews object
        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.car_widget);
        views.setTextViewText(R.id.appwidget_text, widgetText);

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

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


        image = intent.getStringExtra("widget_image");

    }

    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        for (int i = 0; i < appWidgetIds.length; ++i) {
            RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.car_widget);

            // set intent for widget service that will create the views
            Intent serviceIntent = new Intent(context, WidgetService.class);
            serviceIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            serviceIntent.setData(Uri.parse(serviceIntent.toUri(Intent.URI_INTENT_SCHEME))); // embed extras so they don't get ignored
            remoteViews.setRemoteAdapter(appWidgetIds[i], R.id.widget_stack_view, serviceIntent);

            // set intent for item click (opens main activity)
            Intent viewIntent = new Intent(context, MainActivity.class);
            viewIntent.setAction(MainActivity.ACTIVITY_SERVICE);
            viewIntent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[i]);
            viewIntent.setData(Uri.parse(viewIntent.toUri(Intent.URI_INTENT_SCHEME)));

            PendingIntent viewPendingIntent = PendingIntent.getActivity(context, 0, viewIntent, 0);
            remoteViews.setPendingIntentTemplate(R.id.widget_stack_view
                    , viewPendingIntent);

            // update widget
            appWidgetManager.updateAppWidget(appWidgetIds[i], remoteViews);

            AppWidgetTarget awt = new AppWidgetTarget(context, R.id.widget_image_item, remoteViews, appWidgetIds) {
                @Override
                public void onResourceReady(Bitmap resource, Transition<? super Bitmap> transition) {
                    super.onResourceReady(resource, transition);
                }
            };

            RequestOptions options = new RequestOptions().
                    override(300, 300).placeholder(R.drawable.carapp_logo).error(R.drawable.carapp_logo);

            Glide.with(context.getApplicationContext())
                    .asBitmap()
                    .load(image)
                    .apply(options)
                    .into(awt);

        }
        super.onUpdate(context, appWidgetManager, appWidgetIds);
    }


    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        // When the user deletes the widget, delete the preference associated with it.
//        for (int appWidgetId : appWidgetIds) {
//            CarWidgetConfigureActivity.deleteTitlePref(context, appWidgetId);
//        }
        super.onDeleted(context,appWidgetIds);
    }

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

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

Я пытался получить его в намерениях двумя способамииз адаптера в класс CarWidget оба возвращают null.Я очень запутался с этими виджетами. Возможно, я думаю, что что-то не так с другими представленными классами виджетов.

...