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.RetrieveTransactionsTask;
45 import net.ktnx.mobileledger.model.Data;
46 import net.ktnx.mobileledger.model.LedgerAccount;
47 import net.ktnx.mobileledger.model.MobileLedgerProfile;
48 import net.ktnx.mobileledger.ui.MobileLedgerListFragment;
49 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
50 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
51 import net.ktnx.mobileledger.utils.MLDB;
53 import java.lang.ref.WeakReference;
54 import java.time.ZoneId;
55 import java.time.format.DateTimeFormatter;
56 import java.util.Date;
57 import java.util.Observable;
58 import java.util.Observer;
59 import java.util.UUID;
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());
111 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
112 if (profileUUID == null) {
113 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
114 Log.d("profiles", "Migrating from preferences to profiles");
115 // migration to multiple profiles
116 profileUUID = UUID.randomUUID().toString();
117 MobileLedgerProfile profile = new MobileLedgerProfile(profileUUID, "default",
118 backend.getString("backend_url", ""),
119 backend.getBoolean("backend_use_http_auth", false),
120 backend.getString("backend_auth_user", null),
121 backend.getString("backend_auth_password", null));
123 SharedPreferences.Editor editor = backend.edit();
126 Data.profile.set(profile);
127 MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profileUUID);
130 MobileLedgerProfile profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
131 Data.profile.set(profile);
134 drawer = findViewById(R.id.drawer_layout);
135 ActionBarDrawerToggle toggle =
136 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
137 R.string.navigation_drawer_close);
138 drawer.addDrawerListener(toggle);
141 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
145 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
146 ver.setText(pi.versionName);
148 catch (Exception e) {
152 tvLastUpdate = findViewById(R.id.transactions_last_update);
154 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
155 progressBar = findViewById(R.id.transaction_list_progress_bar);
156 if (progressBar == null)
157 throw new RuntimeException("Can't get hold on the transaction value progress bar");
158 progressLayout = findViewById(R.id.transaction_progress_layout);
159 if (progressLayout == null) throw new RuntimeException(
160 "Can't get hold on the transaction value progress bar layout");
162 fragmentManager = getSupportFragmentManager();
163 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
165 mViewPager = findViewById(R.id.root_frame);
166 mViewPager.setAdapter(mSectionsPagerAdapter);
167 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
169 public void onPageSelected(int position) {
172 markDrawerItemCurrent(R.id.nav_account_summary);
175 markDrawerItemCurrent(R.id.nav_latest_transactions);
178 Log.e("MainActivity", String.format("Unexpected page index %d", position));
181 super.onPageSelected(position);
185 Data.lastUpdateDate.addObserver(new Observer() {
187 public void update(Observable o, Object arg) {
188 Log.d("main", "lastUpdateDate changed");
189 runOnUiThread(() -> {
190 Date date = Data.lastUpdateDate.get();
192 tvLastUpdate.setText(R.string.transaction_last_update_never);
195 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
196 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
197 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
200 tvLastUpdate.setText(date.toLocaleString());
207 public void fab_new_transaction_clicked(View view) {
208 Intent intent = new Intent(this, NewTransactionActivity.class);
209 startActivity(intent);
210 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
213 public void nav_exit_clicked(View view) {
214 Log.w("app", "exiting");
218 public void nav_settings_clicked(View view) {
219 Intent intent = new Intent(this, SettingsActivity.class);
220 startActivity(intent);
222 public void markDrawerItemCurrent(int id) {
223 TextView item = drawer.findViewById(id);
224 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
225 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
228 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
231 setTitle(item.getText());
233 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
235 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
236 for (int i = 0; i < actions.getChildCount(); i++) {
237 View view = actions.getChildAt(i);
238 if (view.getId() != id) {
239 view.setBackgroundColor(transparent);
243 public void onOptionsMenuClicked(MenuItem menuItem) {
244 ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
245 switch (menuItem.getItemId()) {
246 case R.id.menu_acc_summary_cancel_selection:
247 if (accountSummaryFragment != null)
248 accountSummaryFragment.onCancelAccSelection(menuItem);
250 case R.id.menu_acc_summary_confirm_selection:
251 if (accountSummaryFragment != null)
252 accountSummaryFragment.onConfirmAccSelection(menuItem);
254 case R.id.menu_acc_summary_only_starred:
255 if (accountSummaryFragment != null)
256 accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
258 case R.id.menu_transaction_list_filter:
259 if (transactionListFragment != null)
260 transactionListFragment.onShowFilterClick(menuItem);
263 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
266 public void onViewClicked(View view) {
267 switch (view.getId()) {
268 case R.id.clearAccountNameFilter:
269 if (transactionListFragment != null)
270 transactionListFragment.onClearAccountNameClick(view);
273 Log.e("click", String.format("View %d click not handled", view.getId()));
276 public void onAccountSummaryClicked(View view) {
277 drawer.closeDrawers();
279 showAccountSummaryFragment();
281 private void showAccountSummaryFragment() {
282 mViewPager.setCurrentItem(0, true);
283 // FragmentTransaction ft = fragmentManager.beginTransaction();
284 // accountSummaryFragment = new AccountSummaryFragment();
285 // ft.replace(R.id.root_frame, accountSummaryFragment);
287 // currentFragment = accountSummaryFragment;
289 public void onLatestTransactionsClicked(View view) {
290 drawer.closeDrawers();
292 showTransactionsFragment(null);
294 private void resetFragmentBackStack() {
295 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
297 private void showTransactionsFragment(LedgerAccount account) {
298 mViewPager.setCurrentItem(1, true);
299 // FragmentTransaction ft = fragmentManager.beginTransaction();
300 // if (transactionListFragment == null) {
301 // Log.d("flow", "MainActivity creating TransactionListFragment");
302 // transactionListFragment = new TransactionListFragment();
304 // Bundle bundle = new Bundle();
305 // if (account != null) {
306 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
307 // account.getName());
309 // transactionListFragment.setArguments(bundle);
310 // ft.replace(R.id.root_frame, transactionListFragment);
311 // if (account != null)
312 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
315 // currentFragment = transactionListFragment;
317 public void showAccountTransactions(LedgerAccount account) {
318 showTransactionsFragment(account);
321 public void onBackPressed() {
322 DrawerLayout drawer = findViewById(R.id.drawer_layout);
323 if (drawer.isDrawerOpen(GravityCompat.START)) {
324 drawer.closeDrawer(GravityCompat.START);
328 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
330 super.onBackPressed();
333 public void updateLastUpdateTextFromDB() {
335 long last_update = MLDB.get_option_value(MLDB.OPT_TRANSACTION_LIST_STAMP, 0L);
337 Log.d("transactions", String.format("Last update = %d", last_update));
338 if (last_update == 0) {
339 Data.lastUpdateDate.set(null);
342 Data.lastUpdateDate.set(new Date(last_update));
346 public void scheduleTransactionListRetrieval() {
347 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
349 retrieveTransactionsTask.execute();
350 bTransactionListCancelDownload.setEnabled(true);
352 public void onStopTransactionRefreshClick(View view) {
353 Log.d("interactive", "Cancelling transactions refresh");
354 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
355 bTransactionListCancelDownload.setEnabled(false);
357 public void onRetrieveDone(boolean success) {
358 progressLayout.setVisibility(View.GONE);
359 updateLastUpdateTextFromDB();
361 public void onRetrieveStart() {
362 progressBar.setIndeterminate(true);
363 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
364 else progressBar.setProgress(0);
365 progressLayout.setVisibility(View.VISIBLE);
367 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
368 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
369 (progress.getTotal() == 0))
371 progressBar.setIndeterminate(true);
374 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
375 progressBar.setMin(0);
377 progressBar.setMax(progress.getTotal());
378 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
379 progressBar.setProgress(progress.getProgress(), true);
381 else progressBar.setProgress(progress.getProgress());
382 progressBar.setIndeterminate(false);
385 public class SectionsPagerAdapter extends FragmentPagerAdapter {
387 public SectionsPagerAdapter(FragmentManager fm) {
392 public Fragment getItem(int position) {
393 Log.d("main", String.format("Switching to gragment %d", position));
396 return new AccountSummaryFragment();
398 return new TransactionListFragment();
400 throw new IllegalStateException(
401 String.format("Unexpected fragment index: " + "%d", position));
406 public int getCount() {