Search in sources :

Example 1 with BaseActivitySummary

use of nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary in project Gadgetbridge by Freeyourgadget.

the class ActivitySummariesAdapter method fill_dashboard.

@Override
protected View fill_dashboard(BaseActivitySummary item, int position, View view, ViewGroup parent, Context context) {
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.activity_summary_dashboard_item, parent, false);
    double durationSum = 0;
    double caloriesBurntSum = 0;
    double distanceSum = 0;
    double activeSecondsSum = 0;
    double firstItemDate = 0;
    double lastItemDate = 0;
    int activitiesCount = getCount() - 1;
    int activityIcon = 0;
    boolean activitySame = true;
    TextView durationSumView = view.findViewById(R.id.summary_dashboard_layout_duration_label);
    TextView caloriesBurntSumView = view.findViewById(R.id.summary_dashboard_layout_calories_label);
    TextView distanceSumView = view.findViewById(R.id.summary_dashboard_layout_distance_label);
    TextView activeSecondsSumView = view.findViewById(R.id.summary_dashboard_layout_active_duration_label);
    TextView timeStartView = view.findViewById(R.id.summary_dashboard_layout_from_label);
    TextView timeEndView = view.findViewById(R.id.summary_dashboard_layout_to_label);
    TextView activitiesCountView = view.findViewById(R.id.summary_dashboard_layout_count_label);
    TextView activityKindView = view.findViewById(R.id.summary_dashboard_layout_activity_label);
    ImageView activityIconView = view.findViewById(R.id.summary_dashboard_layout_activity_icon);
    ImageView activityIconBigView = view.findViewById(R.id.summary_dashboard_layout_big_activity_icon);
    for (BaseActivitySummary sportitem : getItems()) {
        // first item is empty, for dashboard
        if (sportitem.getStartTime() == null)
            continue;
        if (firstItemDate == 0)
            firstItemDate = sportitem.getStartTime().getTime();
        lastItemDate = sportitem.getEndTime().getTime();
        durationSum += sportitem.getEndTime().getTime() - sportitem.getStartTime().getTime();
        if (activityIcon == 0) {
            activityIcon = sportitem.getActivityKind();
        } else {
            if (activityIcon != sportitem.getActivityKind()) {
                activitySame = false;
            }
        }
        ActivitySummaryJsonSummary activitySummaryJsonSummary = new ActivitySummaryJsonSummary(sportitem);
        JSONObject summarySubdata = activitySummaryJsonSummary.getSummaryData();
        if (summarySubdata != null) {
            try {
                if (summarySubdata.has("caloriesBurnt")) {
                    caloriesBurntSum += summarySubdata.getJSONObject("caloriesBurnt").getDouble("value");
                }
                if (summarySubdata.has("distanceMeters")) {
                    distanceSum += summarySubdata.getJSONObject("distanceMeters").getDouble("value");
                }
                if (summarySubdata.has("activeSeconds")) {
                    activeSecondsSum += summarySubdata.getJSONObject("activeSeconds").getDouble("value");
                }
            } catch (JSONException e) {
                LOG.error("SportsActivity", e);
            }
        }
    }
    DecimalFormat df = new DecimalFormat("#.##");
    durationSumView.setText(String.format("%s", DateTimeUtils.formatDurationHoursMinutes((long) durationSum, TimeUnit.MILLISECONDS)));
    caloriesBurntSumView.setText(String.format("%s %s", (long) caloriesBurntSum, context.getString(R.string.calories_unit)));
    distanceSumView.setText(String.format("%s %s", df.format(distanceSum / 1000), context.getString(R.string.km)));
    distanceSumView.setText(FormatUtils.getFormattedDistanceLabel(distanceSum));
    activeSecondsSumView.setText(String.format("%s", DateTimeUtils.formatDurationHoursMinutes((long) activeSecondsSum, TimeUnit.SECONDS)));
    activitiesCountView.setText(String.valueOf(activitiesCount));
    String activityName = context.getString(R.string.activity_summaries_all_activities);
    if (gettActivityKindFilter() != 0) {
        activityName = ActivityKind.asString(gettActivityKindFilter(), context);
        activityIconView.setImageResource(ActivityKind.getIconId(gettActivityKindFilter()));
        activityIconBigView.setImageResource(ActivityKind.getIconId(gettActivityKindFilter()));
    } else {
        if (activitySame) {
            activityIconView.setImageResource(ActivityKind.getIconId(activityIcon));
            activityIconBigView.setImageResource(ActivityKind.getIconId(activityIcon));
        }
    }
    activityKindView.setText(activityName);
    // start and end are inverted when filer not applied, because items are sorted the other way
    timeStartView.setText((dateFromFilter != 0) ? DateTimeUtils.formatDate(new Date(dateFromFilter)) : DateTimeUtils.formatDate(new Date((long) lastItemDate)));
    timeEndView.setText((dateToFilter != 0) ? DateTimeUtils.formatDate(new Date(dateToFilter)) : DateTimeUtils.formatDate(new Date((long) firstItemDate)));
    return view;
}
Also used : DecimalFormat(java.text.DecimalFormat) JSONException(org.json.JSONException) Date(java.util.Date) JSONObject(org.json.JSONObject) LayoutInflater(android.view.LayoutInflater) BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) TextView(android.widget.TextView) ImageView(android.widget.ImageView) ActivitySummaryJsonSummary(nodomain.freeyourgadget.gadgetbridge.model.ActivitySummaryJsonSummary)

Example 2 with BaseActivitySummary

use of nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary in project Gadgetbridge by Freeyourgadget.

the class ActivitySummariesAdapter method loadItems.

@Override
public void loadItems() {
    try (DBHandler handler = GBApplication.acquireDB()) {
        BaseActivitySummaryDao summaryDao = handler.getDaoSession().getBaseActivitySummaryDao();
        Device dbDevice = DBHelper.findDevice(device, handler.getDaoSession());
        QueryBuilder<BaseActivitySummary> qb = summaryDao.queryBuilder();
        if (deviceFilter == ALL_DEVICES) {
            qb.orderDesc(BaseActivitySummaryDao.Properties.StartTime);
        } else if (deviceFilter != 0) {
            qb.where(BaseActivitySummaryDao.Properties.DeviceId.eq(deviceFilter)).orderDesc(BaseActivitySummaryDao.Properties.StartTime);
        } else {
            qb.where(BaseActivitySummaryDao.Properties.DeviceId.eq(dbDevice.getId())).orderDesc(BaseActivitySummaryDao.Properties.StartTime);
        }
        if (activityKindFilter != 0) {
            qb.where(BaseActivitySummaryDao.Properties.ActivityKind.eq(activityKindFilter));
        }
        if (dateFromFilter != 0) {
            qb.where(BaseActivitySummaryDao.Properties.StartTime.gt(new Date(dateFromFilter)));
        }
        if (dateToFilter != 0) {
            qb.where(BaseActivitySummaryDao.Properties.EndTime.lt(new Date(dateToFilter)));
        }
        if (nameContainsFilter != null && nameContainsFilter.length() > 0) {
            qb.where(BaseActivitySummaryDao.Properties.Name.like("%" + nameContainsFilter + "%"));
        }
        if (itemsFilter != null) {
            qb.where(BaseActivitySummaryDao.Properties.Id.in(itemsFilter));
        }
        List<BaseActivitySummary> allSummaries = new ArrayList<>();
        allSummaries.add(new BaseActivitySummary());
        allSummaries.addAll(qb.build().list());
        setItems(allSummaries, true);
    } catch (Exception e) {
        GB.toast("Error loading activity summaries.", Toast.LENGTH_SHORT, GB.ERROR, e);
    }
}
Also used : DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) BaseActivitySummaryDao(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummaryDao) Device(nodomain.freeyourgadget.gadgetbridge.entities.Device) GBDevice(nodomain.freeyourgadget.gadgetbridge.impl.GBDevice) ArrayList(java.util.ArrayList) BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) Date(java.util.Date) JSONException(org.json.JSONException)

Example 3 with BaseActivitySummary

use of nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary in project Gadgetbridge by Freeyourgadget.

the class FetchSportsSummaryOperation method handleActivityFetchFinish.

@Override
protected void handleActivityFetchFinish(boolean success) {
    LOG.info(getName() + " has finished round " + fetchCount);
    // GregorianCalendar lastSyncTimestamp = saveSamples();
    // if (lastSyncTimestamp != null && needsAnotherFetch(lastSyncTimestamp)) {
    // try {
    // startFetching();
    // return;
    // } catch (IOException ex) {
    // LOG.error("Error starting another round of fetching activity data", ex);
    // }
    // }
    BaseActivitySummary summary = null;
    if (success) {
        summary = new BaseActivitySummary();
        // due to a bug this has to be set
        summary.setStartTime(getLastStartTimestamp().getTime());
        summary.setRawSummaryData(buffer.toByteArray());
        HuamiActivitySummaryParser parser = new HuamiActivitySummaryParser();
        summary = parser.parseBinaryData(summary);
        if (summary != null) {
            // remove json before saving to database,
            summary.setSummaryData(null);
            try (DBHandler dbHandler = GBApplication.acquireDB()) {
                DaoSession session = dbHandler.getDaoSession();
                Device device = DBHelper.getDevice(getDevice(), session);
                User user = DBHelper.getUser(session);
                summary.setDevice(device);
                summary.setUser(user);
                summary.setRawSummaryData(buffer.toByteArray());
                session.getBaseActivitySummaryDao().insertOrReplace(summary);
            } catch (Exception ex) {
                GB.toast(getContext(), "Error saving activity summary", Toast.LENGTH_LONG, GB.ERROR, ex);
            }
        }
    }
    super.handleActivityFetchFinish(success);
    if (summary != null) {
        FetchSportsDetailsOperation nextOperation = new FetchSportsDetailsOperation(summary, getSupport(), getLastSyncTimeKey());
        try {
            nextOperation.perform();
        } catch (IOException ex) {
            GB.toast(getContext(), "Unable to fetch activity details: " + ex.getMessage(), Toast.LENGTH_LONG, GB.ERROR, ex);
        }
    }
}
Also used : DBHandler(nodomain.freeyourgadget.gadgetbridge.database.DBHandler) User(nodomain.freeyourgadget.gadgetbridge.entities.User) Device(nodomain.freeyourgadget.gadgetbridge.entities.Device) BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) HuamiActivitySummaryParser(nodomain.freeyourgadget.gadgetbridge.devices.huami.HuamiActivitySummaryParser) IOException(java.io.IOException) IOException(java.io.IOException) DaoSession(nodomain.freeyourgadget.gadgetbridge.entities.DaoSession)

Example 4 with BaseActivitySummary

use of nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary in project Gadgetbridge by Freeyourgadget.

the class ActivitySummariesActivity method fillKindMap.

private LinkedHashMap fillKindMap() {
    // reset
    LinkedHashMap<String, Integer> newMap = new LinkedHashMap<>(0);
    newMap.put(getString(R.string.activity_summaries_all_activities), 0);
    for (BaseActivitySummary item : getItemAdapter().getItems()) {
        String activityName = ActivityKind.asString(item.getActivityKind(), this);
        if (!newMap.containsKey(activityName) && item.getActivityKind() != 0) {
            newMap.put(activityName, item.getActivityKind());
        }
    }
    return newMap;
}
Also used : BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) LinkedHashMap(java.util.LinkedHashMap)

Example 5 with BaseActivitySummary

use of nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary in project Gadgetbridge by Freeyourgadget.

the class ActivitySummariesActivity method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    Bundle extras = getIntent().getExtras();
    if (extras != null) {
        mGBDevice = extras.getParcelable(GBDevice.EXTRA_DEVICE);
    } else {
        throw new IllegalArgumentException("Must provide a device when invoking this activity");
    }
    deviceFilter = getDeviceId(mGBDevice);
    IntentFilter filterLocal = new IntentFilter();
    filterLocal.addAction(GBDevice.ACTION_DEVICE_CHANGED);
    LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver, filterLocal);
    super.onCreate(savedInstanceState);
    ActivitySummariesAdapter activitySummariesAdapter = new ActivitySummariesAdapter(this, mGBDevice, activityFilter, dateFromFilter, dateToFilter, nameContainsFilter, deviceFilter, itemsFilter);
    int backgroundColor = getBackgroundColor(ActivitySummariesActivity.this);
    activitySummariesAdapter.setBackgroundColor(backgroundColor);
    activitySummariesAdapter.setShowTime(false);
    setItemAdapter(activitySummariesAdapter);
    getItemListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            // item 0 is empty for dashboard
            if (position == 0)
                return;
            Object item = parent.getItemAtPosition(position);
            if (item != null) {
                ActivitySummary summary = (ActivitySummary) item;
                try {
                    showActivityDetail(position);
                } catch (Exception e) {
                    GB.toast(getApplicationContext(), "Unable to display Activity Detail, maybe the activity is not available yet: " + e.getMessage(), Toast.LENGTH_LONG, GB.ERROR, e);
                }
            }
        }
    });
    getItemListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
    getItemListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {

        @Override
        public void onItemCheckedStateChanged(ActionMode actionMode, int position, long id, boolean checked) {
            if (position == 0 && checked)
                subtrackDashboard = 1;
            if (position == 0 && !checked)
                subtrackDashboard = 0;
            final int selectedItems = getItemListView().getCheckedItemCount() - subtrackDashboard;
            actionMode.setTitle(selectedItems + " selected");
        }

        @Override
        public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
            getMenuInflater().inflate(R.menu.activity_list_context_menu, menu);
            findViewById(R.id.fab).setVisibility(View.INVISIBLE);
            return true;
        }

        @Override
        public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
            return false;
        }

        @Override
        public boolean onActionItemClicked(ActionMode actionMode, MenuItem menuItem) {
            boolean processed = false;
            SparseBooleanArray checked = getItemListView().getCheckedItemPositions();
            switch(menuItem.getItemId()) {
                case R.id.activity_action_delete:
                    List<BaseActivitySummary> toDelete = new ArrayList<>();
                    for (int i = 0; i < checked.size(); i++) {
                        if (checked.valueAt(i)) {
                            toDelete.add(getItemAdapter().getItem(checked.keyAt(i)));
                        }
                    }
                    deleteItems(toDelete);
                    processed = true;
                    break;
                case R.id.activity_action_export:
                    List<String> paths = new ArrayList<>();
                    for (int i = 0; i < checked.size(); i++) {
                        if (checked.valueAt(i)) {
                            BaseActivitySummary item = getItemAdapter().getItem(checked.keyAt(i));
                            if (item != null) {
                                ActivitySummary summary = item;
                                String gpxTrack = summary.getGpxTrack();
                                if (gpxTrack != null) {
                                    paths.add(gpxTrack);
                                }
                            }
                        }
                    }
                    shareMultiple(paths);
                    processed = true;
                    break;
                case R.id.activity_action_select_all:
                    for (int i = 0; i < getItemListView().getCount(); i++) {
                        getItemListView().setItemChecked(i, true);
                    }
                    // don't finish actionmode in this case!
                    return true;
                case R.id.activity_action_addto_filter:
                    List<Long> toFilter = new ArrayList<>();
                    for (int i = 0; i < checked.size(); i++) {
                        if (checked.valueAt(i)) {
                            BaseActivitySummary item = getItemAdapter().getItem(checked.keyAt(i));
                            if (item != null && item.getId() != null) {
                                ActivitySummary summary = item;
                                Long id = summary.getId();
                                toFilter.add(id);
                            }
                        }
                    }
                    itemsFilter = toFilter;
                    setItemsFilter(itemsFilter);
                    refresh();
                    processed = true;
                    break;
                default:
                    break;
            }
            actionMode.finish();
            return processed;
        }

        @Override
        public void onDestroyActionMode(ActionMode actionMode) {
            findViewById(R.id.fab).setVisibility(View.VISIBLE);
        }
    });
    swipeLayout = findViewById(R.id.list_activity_swipe_layout);
    swipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {

        @Override
        public void onRefresh() {
            fetchTrackData();
        }
    });
    FloatingActionButton fab = findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            fetchTrackData();
        }
    });
    activityKindMap = fillKindMap();
}
Also used : BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) ActivitySummary(nodomain.freeyourgadget.gadgetbridge.model.ActivitySummary) SwipeRefreshLayout(androidx.swiperefreshlayout.widget.SwipeRefreshLayout) SparseBooleanArray(android.util.SparseBooleanArray) BaseActivitySummary(nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary) FloatingActionButton(com.google.android.material.floatingactionbutton.FloatingActionButton) ArrayList(java.util.ArrayList) List(java.util.List) Menu(android.view.Menu) ActivitySummariesAdapter(nodomain.freeyourgadget.gadgetbridge.adapter.ActivitySummariesAdapter) IntentFilter(android.content.IntentFilter) Bundle(android.os.Bundle) AbsListView(android.widget.AbsListView) MenuItem(android.view.MenuItem) View(android.view.View) AdapterView(android.widget.AdapterView) AbsListView(android.widget.AbsListView) ListView(android.widget.ListView) ActionMode(android.view.ActionMode) AdapterView(android.widget.AdapterView)

Aggregations

BaseActivitySummary (nodomain.freeyourgadget.gadgetbridge.entities.BaseActivitySummary)7 ArrayList (java.util.ArrayList)3 Bundle (android.os.Bundle)2 View (android.view.View)2 ImageView (android.widget.ImageView)2 TextView (android.widget.TextView)2 Date (java.util.Date)2 List (java.util.List)2 DBHandler (nodomain.freeyourgadget.gadgetbridge.database.DBHandler)2 Device (nodomain.freeyourgadget.gadgetbridge.entities.Device)2 JSONException (org.json.JSONException)2 SuppressLint (android.annotation.SuppressLint)1 AlertDialog (android.app.AlertDialog)1 Context (android.content.Context)1 DialogInterface (android.content.DialogInterface)1 Intent (android.content.Intent)1 IntentFilter (android.content.IntentFilter)1 SparseBooleanArray (android.util.SparseBooleanArray)1 ActionMode (android.view.ActionMode)1 LayoutInflater (android.view.LayoutInflater)1