2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of Mobile-Ledger.
4 * Mobile-Ledger is free software: you can distribute it and/or modify it
5 * under the term of the GNU General Public License as published by
6 * the Free Software Foundation, either version 3 of the License, or
7 * (at your opinion), any later version.
9 * Mobile-Ledger is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License terms for details.
14 * You should have received a copy of the GNU General Public License
15 * along with Mobile-Ledger. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.content.Intent;
21 import android.content.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.support.annotation.ColorInt;
26 import android.support.v4.app.Fragment;
27 import android.support.v4.app.FragmentManager;
28 import android.support.v4.app.FragmentPagerAdapter;
29 import android.support.v4.view.GravityCompat;
30 import android.support.v4.view.ViewPager;
31 import android.support.v4.widget.DrawerLayout;
32 import android.support.v7.app.ActionBarDrawerToggle;
33 import android.support.v7.app.AppCompatActivity;
34 import android.support.v7.widget.Toolbar;
35 import android.util.Log;
36 import android.view.ContextMenu;
37 import android.view.MenuItem;
38 import android.view.View;
39 import android.widget.LinearLayout;
40 import android.widget.ProgressBar;
41 import android.widget.TextView;
43 import net.ktnx.mobileledger.R;
44 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
45 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
46 import net.ktnx.mobileledger.model.Data;
47 import net.ktnx.mobileledger.model.LedgerAccount;
48 import net.ktnx.mobileledger.model.MobileLedgerProfile;
49 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
50 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
51 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
52 import net.ktnx.mobileledger.utils.MLDB;
54 import java.lang.ref.WeakReference;
55 import java.time.ZoneId;
56 import java.time.format.DateTimeFormatter;
57 import java.util.Date;
58 import java.util.Observable;
59 import java.util.Observer;
61 public class MainActivity extends AppCompatActivity {
62 public MobileLedgerListFragment currentFragment = null;
64 private AccountSummaryFragment accountSummaryFragment;
65 private TransactionListFragment transactionListFragment;
66 private FragmentManager fragmentManager;
67 private TextView tvLastUpdate;
68 private RetrieveTransactionsTask retrieveTransactionsTask;
69 private View bTransactionListCancelDownload;
70 private ProgressBar progressBar;
71 private LinearLayout progressLayout;
72 private SectionsPagerAdapter mSectionsPagerAdapter;
73 private ViewPager mViewPager;
76 protected void onStart() {
79 Data.lastUpdateDate.set(null);
80 updateLastUpdateTextFromDB();
81 Date lastUpdate = Data.lastUpdateDate.get();
83 long now = new Date().getTime();
84 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
85 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
87 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
88 lastUpdate.getTime() / 1000f, now / 1000f));
90 scheduleTransactionListRetrieval();
94 protected void onCreate(Bundle savedInstanceState) {
95 super.onCreate(savedInstanceState);
96 setContentView(R.layout.activity_main);
97 Toolbar toolbar = findViewById(R.id.toolbar);
98 setSupportActionBar(toolbar);
100 Data.profile.addObserver(new Observer() {
102 public void update(Observable o, Object arg) {
103 MobileLedgerProfile profile = Data.profile.get();
104 runOnUiThread(() -> {
105 if (profile == null) toolbar.setSubtitle("");
106 else toolbar.setSubtitle(profile.getName());
113 drawer = findViewById(R.id.drawer_layout);
114 ActionBarDrawerToggle toggle =
115 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
116 R.string.navigation_drawer_close);
117 drawer.addDrawerListener(toggle);
120 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
124 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
125 ver.setText(pi.versionName);
127 catch (Exception e) {
131 tvLastUpdate = findViewById(R.id.transactions_last_update);
133 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
134 progressBar = findViewById(R.id.transaction_list_progress_bar);
135 if (progressBar == null)
136 throw new RuntimeException("Can't get hold on the transaction value progress bar");
137 progressLayout = findViewById(R.id.transaction_progress_layout);
138 if (progressLayout == null) throw new RuntimeException(
139 "Can't get hold on the transaction value progress bar layout");
141 fragmentManager = getSupportFragmentManager();
142 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
144 mViewPager = findViewById(R.id.root_frame);
145 mViewPager.setAdapter(mSectionsPagerAdapter);
146 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
148 public void onPageSelected(int position) {
151 markDrawerItemCurrent(R.id.nav_account_summary);
154 markDrawerItemCurrent(R.id.nav_latest_transactions);
157 Log.e("MainActivity", String.format("Unexpected page index %d", position));
160 super.onPageSelected(position);
164 Data.lastUpdateDate.addObserver(new Observer() {
166 public void update(Observable o, Object arg) {
167 Log.d("main", "lastUpdateDate changed");
168 runOnUiThread(() -> {
169 Date date = Data.lastUpdateDate.get();
171 tvLastUpdate.setText(R.string.transaction_last_update_never);
174 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
175 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
176 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
179 tvLastUpdate.setText(date.toLocaleString());
186 private void setupProfile() {
187 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
188 MobileLedgerProfile profile = null;
190 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
191 if (profileUUID == null) {
192 if (Data.profiles.isEmpty()) {
193 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
194 profile = Data.profiles.get(0);
196 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
197 Log.d("profiles", "Migrating from preferences to profiles");
198 // migration to multiple profiles
199 if (profile.getUrl().isEmpty()) {
201 Intent intent = new Intent(this, ProfileListActivity.class);
202 startActivity(intent);
204 profile.setUrl(backend.getString("backend_url", ""));
205 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
206 profile.setAuthUserName(backend.getString("backend_auth_user", null));
207 profile.setAuthPassword(backend.getString("backend_auth_password", null));
209 SharedPreferences.Editor editor = backend.edit();
215 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
218 if (profile == null) profile = Data.profiles.get(0);
220 if (profile == null) throw new AssertionError("profile must have a value");
222 Data.profile.set(profile);
223 MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profile.getUuid());
225 if (profile.getUrl().isEmpty()) {
226 Intent intent = new Intent(this, ProfileListActivity.class);
227 Bundle args = new Bundle();
228 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
229 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
230 intent.putExtras(args);
231 startActivity(intent, args);
234 public void fab_new_transaction_clicked(View view) {
235 Intent intent = new Intent(this, NewTransactionActivity.class);
236 startActivity(intent);
237 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
240 public void nav_exit_clicked(View view) {
241 Log.w("app", "exiting");
245 public void nav_settings_clicked(View view) {
246 Intent intent = new Intent(this, SettingsActivity.class);
247 startActivity(intent);
249 public void markDrawerItemCurrent(int id) {
250 TextView item = drawer.findViewById(id);
251 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
252 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
255 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
258 setTitle(item.getText());
260 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
262 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
263 for (int i = 0; i < actions.getChildCount(); i++) {
264 View view = actions.getChildAt(i);
265 if (view.getId() != id) {
266 view.setBackgroundColor(transparent);
270 public void onOptionsMenuClicked(MenuItem menuItem) {
271 ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
272 switch (menuItem.getItemId()) {
273 case R.id.menu_acc_summary_cancel_selection:
274 if (accountSummaryFragment != null)
275 accountSummaryFragment.onCancelAccSelection(menuItem);
277 case R.id.menu_acc_summary_confirm_selection:
278 if (accountSummaryFragment != null)
279 accountSummaryFragment.onConfirmAccSelection(menuItem);
281 case R.id.menu_acc_summary_only_starred:
282 if (accountSummaryFragment != null)
283 accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
285 case R.id.menu_transaction_list_filter:
286 if (transactionListFragment != null)
287 transactionListFragment.onShowFilterClick(menuItem);
290 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
293 public void onViewClicked(View view) {
294 switch (view.getId()) {
295 case R.id.clearAccountNameFilter:
296 if (transactionListFragment != null)
297 transactionListFragment.onClearAccountNameClick(view);
300 Log.e("click", String.format("View %d click not handled", view.getId()));
303 public void onAccountSummaryClicked(View view) {
304 drawer.closeDrawers();
306 showAccountSummaryFragment();
308 private void showAccountSummaryFragment() {
309 mViewPager.setCurrentItem(0, true);
310 // FragmentTransaction ft = fragmentManager.beginTransaction();
311 // accountSummaryFragment = new AccountSummaryFragment();
312 // ft.replace(R.id.root_frame, accountSummaryFragment);
314 // currentFragment = accountSummaryFragment;
316 public void onLatestTransactionsClicked(View view) {
317 drawer.closeDrawers();
319 showTransactionsFragment(null);
321 private void resetFragmentBackStack() {
322 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
324 private void showTransactionsFragment(LedgerAccount account) {
325 mViewPager.setCurrentItem(1, true);
326 // FragmentTransaction ft = fragmentManager.beginTransaction();
327 // if (transactionListFragment == null) {
328 // Log.d("flow", "MainActivity creating TransactionListFragment");
329 // transactionListFragment = new TransactionListFragment();
331 // Bundle bundle = new Bundle();
332 // if (account != null) {
333 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
334 // account.getName());
336 // transactionListFragment.setArguments(bundle);
337 // ft.replace(R.id.root_frame, transactionListFragment);
338 // if (account != null)
339 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
342 // currentFragment = transactionListFragment;
344 public void showAccountTransactions(LedgerAccount account) {
345 showTransactionsFragment(account);
348 public void onBackPressed() {
349 DrawerLayout drawer = findViewById(R.id.drawer_layout);
350 if (drawer.isDrawerOpen(GravityCompat.START)) {
351 drawer.closeDrawer(GravityCompat.START);
355 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
357 super.onBackPressed();
360 public void updateLastUpdateTextFromDB() {
362 long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
364 Log.d("transactions", String.format("Last update = %d", last_update));
365 if (last_update == 0) {
366 Data.lastUpdateDate.set(null);
369 Data.lastUpdateDate.set(new Date(last_update));
373 public void scheduleTransactionListRetrieval() {
374 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
376 retrieveTransactionsTask.execute();
377 bTransactionListCancelDownload.setEnabled(true);
379 public void onStopTransactionRefreshClick(View view) {
380 Log.d("interactive", "Cancelling transactions refresh");
381 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
382 bTransactionListCancelDownload.setEnabled(false);
384 public void onRetrieveDone(boolean success) {
385 progressLayout.setVisibility(View.GONE);
386 updateLastUpdateTextFromDB();
388 new RefreshDescriptionsTask().execute();
390 public void onRetrieveStart() {
391 progressBar.setIndeterminate(true);
392 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
393 else progressBar.setProgress(0);
394 progressLayout.setVisibility(View.VISIBLE);
396 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
397 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
398 (progress.getTotal() == 0))
400 progressBar.setIndeterminate(true);
403 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
404 progressBar.setMin(0);
406 progressBar.setMax(progress.getTotal());
407 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
408 progressBar.setProgress(progress.getProgress(), true);
410 else progressBar.setProgress(progress.getProgress());
411 progressBar.setIndeterminate(false);
414 public void nav_profiles_clicked(View view) {
415 drawer.closeDrawers();
416 Intent intent = new Intent(this, ProfileListActivity.class);
417 startActivity(intent);
419 public class SectionsPagerAdapter extends FragmentPagerAdapter {
421 public SectionsPagerAdapter(FragmentManager fm) {
426 public Fragment getItem(int position) {
427 Log.d("main", String.format("Switching to gragment %d", position));
430 return new AccountSummaryFragment();
432 return new TransactionListFragment();
434 throw new IllegalStateException(
435 String.format("Unexpected fragment index: " + "%d", position));
440 public int getCount() {