javaandroidnetwork-programmingandroid-appwidgetappwidgetprovider

updating app widget showing different layouts


In my app users can login using different accounts and I want to show different data based on that but there is also a state that user hasn't logged in to any account. so I want to show two different layouts. first one containing the account data and the second showing a button to my login activity. I tried toggling the visibility of my button but when the user logs in the widget doesn't update.

xml of my widget:

<?xml version="1.0" encoding="utf-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
    android:initialKeyguardLayout="@layout/updating_chart_widget_iot"
    android:initialLayout="@layout/updating_chart_widget_iot"
    android:minHeight="250dp"
    android:minWidth="250dp"
    android:previewImage="@drawable/chart_widget_preview"
    android:resizeMode="vertical"
    android:updatePeriodMillis="60000"
    android:widgetCategory="home_screen">
</appwidget-provider>

here is the code of my widget provider: please tell me which part am I doing worng...

public class IoTUpdatingChartWidget extends AppWidgetProvider {
//    private PendingIntent serviceIntent;

    SharedPrefManager sharedPrefManager;
    ApiInterface apiService;

    ArrayList<String> hoursArrayList;
    ArrayList<Double> usagesArrayList;

    BarChart hourlyUsageChart;

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

        sharedPrefManager = SharedPrefManager.getInstance();
        apiService = ApiClient.getClient().create(ApiInterface.class);

        if (sharedPrefManager.isLoggedIn(context)) {

            Call<WidgetInfo> getWidgetInfoCall = apiService.getWidgetInfo(sharedPrefManager.getApiToken(context.getApplicationContext()));
            getWidgetInfoCall.enqueue(new Callback<WidgetInfo>() {
                @Override
                public void onResponse(Call<WidgetInfo> call, Response<WidgetInfo> response) {
                    Log.e("response code service", response.code() + "");
                    if (response.code() == 200) {

                        WidgetInfo widgetInfo = response.body();

                        RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.updating_chart_widget_iot);
//                        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
                        Log.e("chart arraysize service", widgetInfo.getHourlyUsageArray().size() + "");

                        ArrayList<HourlyUsage> hourlyUsageArrayList = widgetInfo.getHourlyUsageArray();

                        hoursArrayList = null;
                        usagesArrayList = null;
                        usagesArrayList = new ArrayList<>();
                        hoursArrayList = new ArrayList<>();

                        for (int i = 0; i < hourlyUsageArrayList.size(); i++) {
                            hoursArrayList.add(Utils.convertEng2FaNumbers(hourlyUsageArrayList.get(i).getHour()));
                            usagesArrayList.add(hourlyUsageArrayList.get(i).getEnergy());
                        }

                        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                        hourlyUsageChart = (BarChart) inflater.inflate(R.layout.bar_chart, null, false).findViewById(R.id.hourly_usage_chart);

                        initializeHourlyUsageChart(context);

                        Bitmap bitmap = Utils.takeScreenShotOfView(hourlyUsageChart, 350, 300);

                        view.setImageViewBitmap(R.id.image_view_chart, bitmap);

                        Drawable statusDrawable;
                        switch (Utils.getUsageTime()) {
                            case "پر باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_red_36);
                                break;
                            case "میان باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_yellow_36);
                                break;
                            case "کم باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_green_36);
                                break;
                            default:
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_white_36);
                        }

                        view.setImageViewBitmap(R.id.image_view_network_status, Utils.drawableToBitmap(statusDrawable));
                        view.setTextViewText(R.id.text_view_usage_time, Utils.getUsageTime());
                        view.setTextViewText(R.id.text_view_cost, Utils.convertEng2FaNumbers(((int) widgetInfo.getCost() / 10) + " تومان"));
                        view.setTextViewText(R.id.text_view_user_score, Utils.convertEng2FaNumbers((int) widgetInfo.getRankInUsage() + " از " + (int) widgetInfo.getTotalUsers()));
                        view.setTextViewText(R.id.text_view_monthly_usage, Utils.convertEng2FaNumbers(((double)((int)(widgetInfo.getMonthlyUsage() *10 ))) / 10+ " kwh"));
                        view.setTextViewText(R.id.text_view_daily_usage, Utils.convertEng2FaNumbers(((double)((int)(widgetInfo.getDailyUsage() * 10))) / 10  + " kwh"));
                        view.setViewVisibility(R.id.progress_bar, View.GONE);
                        view.setViewVisibility(R.id.text_view_error, View.GONE);
                        view.setViewVisibility(R.id.button_enter, View.GONE);

                        ComponentName theWidget = new ComponentName(context, IoTUpdatingChartWidget.class);

                        AppWidgetManager manager = AppWidgetManager.getInstance(context);
                        manager.updateAppWidget(theWidget, view);

                    } else

                    {

                        //server error
                        RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.updating_chart_widget_iot);

                        Drawable statusDrawable;
                        switch (Utils.getUsageTime()) {
                            case "پر باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_red_36);
                                break;
                            case "میان باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_yellow_36);
                                break;
                            case "کم باری":
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_green_36);
                                break;
                            default:
                                statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_white_36);
                        }

                        view.setImageViewBitmap(R.id.image_view_network_status, Utils.drawableToBitmap(statusDrawable));
                        view.setTextViewText(R.id.text_view_usage_time, Utils.getUsageTime());

                        view.setTextViewText(R.id.text_view_cost, context.getString(R.string.short_no_data));
                        view.setTextViewText(R.id.text_view_user_score, context.getString(R.string.short_no_data));
                        view.setTextViewText(R.id.text_view_monthly_usage, context.getString(R.string.short_no_data));
                        view.setViewVisibility(R.id.progress_bar, View.VISIBLE);
                        view.setViewVisibility(R.id.text_view_error, View.VISIBLE);
                        view.setViewVisibility(R.id.image_view_chart, View.GONE);
                        view.setViewVisibility(R.id.button_enter, View.GONE);

                        view.setTextViewText(R.id.text_view_error, context.getString(R.string.server_err));
                        ComponentName theWidget = new ComponentName(context, IoTUpdatingChartWidget.class);

                        AppWidgetManager manager = AppWidgetManager.getInstance(context);
                        manager.updateAppWidget(theWidget, view);
                    }

                }

                @Override
                public void onFailure(Call<WidgetInfo> call, Throwable t) {
                    // internet error
                    if (hoursArrayList == null) {
                        RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.updating_list_widget_iot);

                        view.setViewVisibility(R.id.progress_bar, View.VISIBLE);
                        view.setViewVisibility(R.id.text_view_error, View.VISIBLE);
                        view.setViewVisibility(R.id.button_enter, View.GONE);
                        view.setViewVisibility(R.id.list_view, View.GONE);

                        view.setTextViewText(R.id.text_view_error, context.getString(R.string.internet_err));
                        ComponentName theWidget = new ComponentName(context, IoTUpdatingChartWidget.class);

                        AppWidgetManager manager = AppWidgetManager.getInstance(context);
                        manager.updateAppWidget(theWidget, view);
                    }
                    Log.e("chart responsecode serv", t.getMessage());
                }
            });

        } else if (!sharedPrefManager.isLoggedIn(context)) {

            // not logged in state
            RemoteViews view = new RemoteViews(context.getPackageName(), R.layout.updating_list_widget_iot);

            view.setViewVisibility(R.id.progress_bar, View.VISIBLE);
            view.setViewVisibility(R.id.text_view_error, View.VISIBLE);
            view.setTextViewText(R.id.text_view_error, context.getString(R.string.login_to_your_account));
            view.setViewVisibility(R.id.button_enter, View.VISIBLE);
            view.setViewVisibility(R.id.progress_bar, View.GONE);

            view.setViewVisibility(R.id.list_view, View.GONE);

            Intent intent = new Intent(context, SplashScreenActivity.class);
            PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);

            view.setOnClickPendingIntent(R.id.button_enter, pendingIntent);

            Drawable statusDrawable;
            switch (Utils.getUsageTime()) {
                case "پر باری":
                    statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_red_36);
                    break;
                case "میان باری":
                    statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_yellow_36);
                    break;
                case "کم باری":
                    statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_green_36);
                    break;
                default:
                    statusDrawable = context.getResources().getDrawable(R.drawable.circle_filled_white_36);
            }

            view.setImageViewBitmap(R.id.image_view_network_status, Utils.drawableToBitmap(statusDrawable));
            view.setTextViewText(R.id.text_view_usage_time, Utils.getUsageTime());

            ComponentName theWidget = new ComponentName(context, IoTUpdatingChartWidget.class);
            AppWidgetManager manager = AppWidgetManager.getInstance(context);
            manager.updateAppWidget(theWidget, view);
        }
    }
}

Solution

  • You can force all the instances of your home screen widgets to refresh like this:

    private void udpateWidgets() {
        Intent intent = new Intent(this, IoTUpdatingChartWidget.class);
        intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
         int[] ids = AppWidgetManager.getInstance(getApplication())
            .getAppWidgetI‌​ds(new ComponentName(getApplication(), IoTUpdatingChartWidget.class));
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids);
        sendBroadcast(intent);
    }
    

    I cannot see the login and logout code, but it may just be a case of calling updateWidgets() when the session state changes.