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.text.DateFormat;
56 import java.time.ZoneId;
57 import java.time.format.DateTimeFormatter;
58 import java.util.Date;
59 import java.util.Observable;
60 import java.util.Observer;
62 public class MainActivity extends AppCompatActivity {
63 public MobileLedgerListFragment currentFragment = null;
65 private AccountSummaryFragment accountSummaryFragment;
66 private TransactionListFragment transactionListFragment;
67 private FragmentManager fragmentManager;
68 private TextView tvLastUpdate;
69 private RetrieveTransactionsTask retrieveTransactionsTask;
70 private View bTransactionListCancelDownload;
71 private ProgressBar progressBar;
72 private LinearLayout progressLayout;
73 private SectionsPagerAdapter mSectionsPagerAdapter;
74 private ViewPager mViewPager;
77 protected void onStart() {
80 Data.lastUpdateDate.set(null);
81 updateLastUpdateTextFromDB();
82 Date lastUpdate = Data.lastUpdateDate.get();
84 long now = new Date().getTime();
85 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
86 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
88 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
89 lastUpdate.getTime() / 1000f, now / 1000f));
91 scheduleTransactionListRetrieval();
95 protected void onCreate(Bundle savedInstanceState) {
96 super.onCreate(savedInstanceState);
97 setContentView(R.layout.activity_main);
98 Toolbar toolbar = findViewById(R.id.toolbar);
99 setSupportActionBar(toolbar);
101 Data.profile.addObserver(new Observer() {
103 public void update(Observable o, Object arg) {
104 MobileLedgerProfile profile = Data.profile.get();
105 runOnUiThread(() -> {
106 if (profile == null) toolbar.setSubtitle("");
107 else toolbar.setSubtitle(profile.getName());
114 drawer = findViewById(R.id.drawer_layout);
115 ActionBarDrawerToggle toggle =
116 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
117 R.string.navigation_drawer_close);
118 drawer.addDrawerListener(toggle);
121 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
125 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
126 ver.setText(pi.versionName);
128 catch (Exception e) {
132 tvLastUpdate = findViewById(R.id.transactions_last_update);
134 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
135 progressBar = findViewById(R.id.transaction_list_progress_bar);
136 if (progressBar == null)
137 throw new RuntimeException("Can't get hold on the transaction value progress bar");
138 progressLayout = findViewById(R.id.transaction_progress_layout);
139 if (progressLayout == null) throw new RuntimeException(
140 "Can't get hold on the transaction value progress bar layout");
142 fragmentManager = getSupportFragmentManager();
143 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
145 mViewPager = findViewById(R.id.root_frame);
146 mViewPager.setAdapter(mSectionsPagerAdapter);
147 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
149 public void onPageSelected(int position) {
152 markDrawerItemCurrent(R.id.nav_account_summary);
155 markDrawerItemCurrent(R.id.nav_latest_transactions);
158 Log.e("MainActivity", String.format("Unexpected page index %d", position));
161 super.onPageSelected(position);
165 Data.lastUpdateDate.addObserver((o, arg) -> {
166 Log.d("main", "lastUpdateDate changed");
167 runOnUiThread(() -> {
168 Date date = Data.lastUpdateDate.get();
170 tvLastUpdate.setText(R.string.transaction_last_update_never);
173 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
174 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
175 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
178 tvLastUpdate.setText(DateFormat.getDateTimeInstance().format(date));
184 private void setupProfile() {
185 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
186 MobileLedgerProfile profile = null;
188 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
189 if (profileUUID == null) {
190 if (Data.profiles.isEmpty()) {
191 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
192 profile = Data.profiles.get(0);
194 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
195 Log.d("profiles", "Migrating from preferences to profiles");
196 // migration to multiple profiles
197 if (profile.getUrl().isEmpty()) {
199 Intent intent = new Intent(this, ProfileListActivity.class);
200 startActivity(intent);
202 profile.setUrl(backend.getString("backend_url", ""));
203 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
204 profile.setAuthUserName(backend.getString("backend_auth_user", null));
205 profile.setAuthPassword(backend.getString("backend_auth_password", null));
207 SharedPreferences.Editor editor = backend.edit();
213 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
216 if (profile == null) profile = Data.profiles.get(0);
218 if (profile == null) throw new AssertionError("profile must have a value");
220 Data.profile.set(profile);
221 MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profile.getUuid());
223 if (profile.getUrl().isEmpty()) {
224 Intent intent = new Intent(this, ProfileListActivity.class);
225 Bundle args = new Bundle();
226 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
227 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
228 intent.putExtras(args);
229 startActivity(intent, args);
232 public void fab_new_transaction_clicked(View view) {
233 Intent intent = new Intent(this, NewTransactionActivity.class);
234 startActivity(intent);
235 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
238 public void nav_exit_clicked(View view) {
239 Log.w("app", "exiting");
243 public void nav_settings_clicked(View view) {
244 Intent intent = new Intent(this, SettingsActivity.class);
245 startActivity(intent);
247 public void markDrawerItemCurrent(int id) {
248 TextView item = drawer.findViewById(id);
249 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
250 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
253 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
256 setTitle(item.getText());
258 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
260 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
261 for (int i = 0; i < actions.getChildCount(); i++) {
262 View view = actions.getChildAt(i);
263 if (view.getId() != id) {
264 view.setBackgroundColor(transparent);
268 public void onOptionsMenuClicked(MenuItem menuItem) {
269 ContextMenu.ContextMenuInfo info = menuItem.getMenuInfo();
270 switch (menuItem.getItemId()) {
271 case R.id.menu_acc_summary_cancel_selection:
272 if (accountSummaryFragment != null)
273 accountSummaryFragment.onCancelAccSelection(menuItem);
275 case R.id.menu_acc_summary_confirm_selection:
276 if (accountSummaryFragment != null)
277 accountSummaryFragment.onConfirmAccSelection(menuItem);
279 case R.id.menu_acc_summary_only_starred:
280 if (accountSummaryFragment != null)
281 accountSummaryFragment.onShowOnlyStarredClicked(menuItem);
283 case R.id.menu_transaction_list_filter:
284 if (transactionListFragment != null)
285 transactionListFragment.onShowFilterClick(menuItem);
288 Log.e("menu", String.format("Menu item %d not handled", menuItem.getItemId()));
291 public void onViewClicked(View view) {
292 switch (view.getId()) {
293 case R.id.clearAccountNameFilter:
294 if (transactionListFragment != null)
295 transactionListFragment.onClearAccountNameClick(view);
298 Log.e("click", String.format("View %d click not handled", view.getId()));
301 public void onAccountSummaryClicked(View view) {
302 drawer.closeDrawers();
304 showAccountSummaryFragment();
306 private void showAccountSummaryFragment() {
307 mViewPager.setCurrentItem(0, true);
308 // FragmentTransaction ft = fragmentManager.beginTransaction();
309 // accountSummaryFragment = new AccountSummaryFragment();
310 // ft.replace(R.id.root_frame, accountSummaryFragment);
312 // currentFragment = accountSummaryFragment;
314 public void onLatestTransactionsClicked(View view) {
315 drawer.closeDrawers();
317 showTransactionsFragment(null);
319 private void resetFragmentBackStack() {
320 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
322 private void showTransactionsFragment(LedgerAccount account) {
323 mViewPager.setCurrentItem(1, true);
324 // FragmentTransaction ft = fragmentManager.beginTransaction();
325 // if (transactionListFragment == null) {
326 // Log.d("flow", "MainActivity creating TransactionListFragment");
327 // transactionListFragment = new TransactionListFragment();
329 // Bundle bundle = new Bundle();
330 // if (account != null) {
331 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
332 // account.getName());
334 // transactionListFragment.setArguments(bundle);
335 // ft.replace(R.id.root_frame, transactionListFragment);
336 // if (account != null)
337 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
340 // currentFragment = transactionListFragment;
342 public void showAccountTransactions(LedgerAccount account) {
343 showTransactionsFragment(account);
346 public void onBackPressed() {
347 DrawerLayout drawer = findViewById(R.id.drawer_layout);
348 if (drawer.isDrawerOpen(GravityCompat.START)) {
349 drawer.closeDrawer(GravityCompat.START);
353 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
355 super.onBackPressed();
358 public void updateLastUpdateTextFromDB() {
360 long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
362 Log.d("transactions", String.format("Last update = %d", last_update));
363 if (last_update == 0) {
364 Data.lastUpdateDate.set(null);
367 Data.lastUpdateDate.set(new Date(last_update));
371 public void scheduleTransactionListRetrieval() {
372 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
374 retrieveTransactionsTask.execute();
375 bTransactionListCancelDownload.setEnabled(true);
377 public void onStopTransactionRefreshClick(View view) {
378 Log.d("interactive", "Cancelling transactions refresh");
379 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
380 bTransactionListCancelDownload.setEnabled(false);
382 public void onRetrieveDone(boolean success) {
383 progressLayout.setVisibility(View.GONE);
384 updateLastUpdateTextFromDB();
386 new RefreshDescriptionsTask().execute();
388 public void onRetrieveStart() {
389 progressBar.setIndeterminate(true);
390 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
391 else progressBar.setProgress(0);
392 progressLayout.setVisibility(View.VISIBLE);
394 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
395 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
396 (progress.getTotal() == 0))
398 progressBar.setIndeterminate(true);
401 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
402 progressBar.setMin(0);
404 progressBar.setMax(progress.getTotal());
405 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
406 progressBar.setProgress(progress.getProgress(), true);
408 else progressBar.setProgress(progress.getProgress());
409 progressBar.setIndeterminate(false);
412 public void nav_profiles_clicked(View view) {
413 drawer.closeDrawers();
414 Intent intent = new Intent(this, ProfileListActivity.class);
415 startActivity(intent);
417 public class SectionsPagerAdapter extends FragmentPagerAdapter {
419 public SectionsPagerAdapter(FragmentManager fm) {
424 public Fragment getItem(int position) {
425 Log.d("main", String.format("Switching to gragment %d", position));
428 return new AccountSummaryFragment();
430 return new TransactionListFragment();
432 throw new IllegalStateException(
433 String.format("Unexpected fragment index: " + "%d", position));
438 public int getCount() {