2 * Copyright © 2019 Damyan Ivanov.
3 * This file is part of MoLe.
4 * MoLe 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 * MoLe 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 MoLe. If not, see <https://www.gnu.org/licenses/>.
18 package net.ktnx.mobileledger.ui.activity;
20 import android.content.Intent;
21 import android.content.pm.PackageInfo;
22 import android.os.Build;
23 import android.os.Bundle;
24 import android.support.annotation.ColorInt;
25 import android.support.design.widget.FloatingActionButton;
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.widget.Toolbar;
34 import android.util.Log;
35 import android.view.View;
36 import android.widget.LinearLayout;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39 import android.widget.Toast;
41 import net.ktnx.mobileledger.R;
42 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
43 import net.ktnx.mobileledger.async.RetrieveTransactionsTask;
44 import net.ktnx.mobileledger.model.Data;
45 import net.ktnx.mobileledger.model.LedgerAccount;
46 import net.ktnx.mobileledger.model.MobileLedgerProfile;
47 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
48 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
49 import net.ktnx.mobileledger.utils.MLDB;
51 import java.lang.ref.WeakReference;
52 import java.text.DateFormat;
53 import java.util.Date;
55 public class MainActivity extends CrashReportingActivity {
57 private FragmentManager fragmentManager;
58 private TextView tvLastUpdate;
59 private RetrieveTransactionsTask retrieveTransactionsTask;
60 private View bTransactionListCancelDownload;
61 private ProgressBar progressBar;
62 private LinearLayout progressLayout;
63 private SectionsPagerAdapter mSectionsPagerAdapter;
64 private ViewPager mViewPager;
65 private FloatingActionButton fab;
68 protected void onStart() {
71 Data.lastUpdateDate.set(null);
72 updateLastUpdateTextFromDB();
73 Date lastUpdate = Data.lastUpdateDate.get();
75 long now = new Date().getTime();
76 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
77 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
79 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
80 lastUpdate.getTime() / 1000f, now / 1000f));
82 scheduleTransactionListRetrieval();
86 protected void onCreate(Bundle savedInstanceState) {
87 super.onCreate(savedInstanceState);
88 setContentView(R.layout.activity_main);
89 Toolbar toolbar = findViewById(R.id.toolbar);
90 setSupportActionBar(toolbar);
91 fab = findViewById(R.id.btn_add_transaction);
93 Data.profile.addObserver((o, arg) -> {
94 MobileLedgerProfile profile = Data.profile.get();
96 if (profile == null) setTitle(R.string.app_name);
97 else setTitle(profile.getName());
98 updateLastUpdateTextFromDB();
99 if (profile.isPostingPermitted()) {
100 toolbar.setSubtitle(null);
104 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
110 drawer = findViewById(R.id.drawer_layout);
111 ActionBarDrawerToggle toggle =
112 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
113 R.string.navigation_drawer_close);
114 drawer.addDrawerListener(toggle);
117 TextView ver = drawer.findViewById(R.id.drawer_version_text);
121 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
122 ver.setText(pi.versionName);
124 catch (Exception e) {
128 tvLastUpdate = findViewById(R.id.transactions_last_update);
130 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
131 progressBar = findViewById(R.id.transaction_list_progress_bar);
132 if (progressBar == null)
133 throw new RuntimeException("Can't get hold on the transaction value progress bar");
134 progressLayout = findViewById(R.id.transaction_progress_layout);
135 if (progressLayout == null) throw new RuntimeException(
136 "Can't get hold on the transaction value progress bar layout");
138 fragmentManager = getSupportFragmentManager();
139 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
141 markDrawerItemCurrent(R.id.nav_account_summary);
143 mViewPager = findViewById(R.id.root_frame);
144 mViewPager.setAdapter(mSectionsPagerAdapter);
145 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
147 public void onPageSelected(int position) {
150 markDrawerItemCurrent(R.id.nav_account_summary);
153 markDrawerItemCurrent(R.id.nav_latest_transactions);
156 Log.e("MainActivity", String.format("Unexpected page index %d", position));
159 super.onPageSelected(position);
163 Data.lastUpdateDate.addObserver((o, arg) -> {
164 Log.d("main", "lastUpdateDate changed");
165 runOnUiThread(() -> {
166 Date date = Data.lastUpdateDate.get();
168 tvLastUpdate.setText(R.string.transaction_last_update_never);
171 final String text = DateFormat.getDateTimeInstance().format(date);
172 tvLastUpdate.setText(text);
173 Log.d("despair", String.format("Date formatted: %s", text));
178 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
180 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
183 protected void onResume() {
187 private void startAddProfileActivity() {
188 Intent intent = new Intent(this, ProfileListActivity.class);
189 Bundle args = new Bundle();
190 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
191 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
192 intent.putExtras(args);
193 startActivity(intent, args);
195 private void setupProfile() {
196 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
197 MobileLedgerProfile profile;
199 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
201 if (Data.profiles.getList().isEmpty()) {
202 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
203 findViewById(R.id.pager_layout).setVisibility(View.GONE);
207 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
208 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
210 if (profile == null) profile = Data.profiles.get(0);
212 if (profile == null) throw new AssertionError("profile must have a value");
214 Data.setCurrentProfile(profile);
216 public void fabNewTransactionClicked(View view) {
217 Intent intent = new Intent(this, NewTransactionActivity.class);
218 startActivity(intent);
219 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
221 public void navSettingsClicked(View view) {
222 Intent intent = new Intent(this, SettingsActivity.class);
223 startActivity(intent);
224 drawer.closeDrawers();
226 public void markDrawerItemCurrent(int id) {
227 TextView item = drawer.findViewById(id);
228 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
229 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
232 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
235 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
237 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
238 for (int i = 0; i < actions.getChildCount(); i++) {
239 View view = actions.getChildAt(i);
240 if (view.getId() != id) {
241 view.setBackgroundColor(transparent);
245 public void onAccountSummaryClicked(View view) {
246 drawer.closeDrawers();
248 showAccountSummaryFragment();
250 private void showAccountSummaryFragment() {
251 mViewPager.setCurrentItem(0, true);
252 TransactionListFragment.accountFilter.set(null);
253 // FragmentTransaction ft = fragmentManager.beginTransaction();
254 // accountSummaryFragment = new AccountSummaryFragment();
255 // ft.replace(R.id.root_frame, accountSummaryFragment);
257 // currentFragment = accountSummaryFragment;
259 public void onLatestTransactionsClicked(View view) {
260 drawer.closeDrawers();
262 showTransactionsFragment(null);
264 private void resetFragmentBackStack() {
265 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
267 private void showTransactionsFragment(LedgerAccount account) {
268 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
269 mViewPager.setCurrentItem(1, true);
270 // FragmentTransaction ft = fragmentManager.beginTransaction();
271 // if (transactionListFragment == null) {
272 // Log.d("flow", "MainActivity creating TransactionListFragment");
273 // transactionListFragment = new TransactionListFragment();
275 // Bundle bundle = new Bundle();
276 // if (account != null) {
277 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
278 // account.getName());
280 // transactionListFragment.setArguments(bundle);
281 // ft.replace(R.id.root_frame, transactionListFragment);
282 // if (account != null)
283 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
286 // currentFragment = transactionListFragment;
288 public void showAccountTransactions(LedgerAccount account) {
289 showTransactionsFragment(account);
292 public void onBackPressed() {
293 DrawerLayout drawer = findViewById(R.id.drawer_layout);
294 if (drawer.isDrawerOpen(GravityCompat.START)) {
295 drawer.closeDrawer(GravityCompat.START);
299 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
301 super.onBackPressed();
304 public void updateLastUpdateTextFromDB() {
306 final MobileLedgerProfile profile = Data.profile.get();
308 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
310 Log.d("transactions", String.format("Last update = %d", last_update));
311 if (last_update == 0) {
312 Data.lastUpdateDate.set(null);
315 Data.lastUpdateDate.set(new Date(last_update));
319 public void scheduleTransactionListRetrieval() {
320 if (Data.profile.get() == null) return;
322 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
324 retrieveTransactionsTask.execute();
325 bTransactionListCancelDownload.setEnabled(true);
327 public void onStopTransactionRefreshClick(View view) {
328 Log.d("interactive", "Cancelling transactions refresh");
329 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
330 bTransactionListCancelDownload.setEnabled(false);
332 public void onRetrieveDone(String error) {
333 progressLayout.setVisibility(View.GONE);
336 updateLastUpdateTextFromDB();
338 new RefreshDescriptionsTask().execute();
340 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
342 public void onRetrieveStart() {
343 progressBar.setIndeterminate(true);
344 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
345 else progressBar.setProgress(0);
346 progressLayout.setVisibility(View.VISIBLE);
348 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
349 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
350 (progress.getTotal() == 0))
352 progressBar.setIndeterminate(true);
355 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
356 progressBar.setMin(0);
358 progressBar.setMax(progress.getTotal());
359 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
360 progressBar.setProgress(progress.getProgress(), true);
362 else progressBar.setProgress(progress.getProgress());
363 progressBar.setIndeterminate(false);
366 public void navProfilesClicked(View view) {
367 drawer.closeDrawers();
368 Intent intent = new Intent(this, ProfileListActivity.class);
369 startActivity(intent);
371 public class SectionsPagerAdapter extends FragmentPagerAdapter {
373 public SectionsPagerAdapter(FragmentManager fm) {
378 public Fragment getItem(int position) {
379 Log.d("main", String.format("Switching to fragment %d", position));
382 return new AccountSummaryFragment();
384 return new TransactionListFragment();
386 throw new IllegalStateException(
387 String.format("Unexpected fragment index: " + "%d", position));
392 public int getCount() {
396 public void fabShouldShow() {
397 MobileLedgerProfile profile = Data.profile.get();
398 if ((profile != null) && profile.isPostingPermitted()) fab.show();