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.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.app.AppCompatActivity;
34 import android.support.v7.widget.Toolbar;
35 import android.util.Log;
36 import android.view.View;
37 import android.widget.LinearLayout;
38 import android.widget.ProgressBar;
39 import android.widget.TextView;
40 import android.widget.Toast;
42 import net.ktnx.mobileledger.R;
43 import net.ktnx.mobileledger.async.RefreshDescriptionsTask;
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.account_summary.AccountSummaryFragment;
49 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
50 import net.ktnx.mobileledger.utils.MLDB;
52 import java.lang.ref.WeakReference;
53 import java.text.DateFormat;
54 import java.util.Date;
56 public class MainActivity extends AppCompatActivity {
58 private FragmentManager fragmentManager;
59 private TextView tvLastUpdate;
60 private RetrieveTransactionsTask retrieveTransactionsTask;
61 private View bTransactionListCancelDownload;
62 private ProgressBar progressBar;
63 private LinearLayout progressLayout;
64 private SectionsPagerAdapter mSectionsPagerAdapter;
65 private ViewPager mViewPager;
66 private FloatingActionButton fab;
69 protected void onStart() {
72 Data.lastUpdateDate.set(null);
73 updateLastUpdateTextFromDB();
74 Date lastUpdate = Data.lastUpdateDate.get();
76 long now = new Date().getTime();
77 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
78 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
80 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
81 lastUpdate.getTime() / 1000f, now / 1000f));
83 scheduleTransactionListRetrieval();
87 protected void onCreate(Bundle savedInstanceState) {
88 super.onCreate(savedInstanceState);
89 setContentView(R.layout.activity_main);
90 Toolbar toolbar = findViewById(R.id.toolbar);
91 setSupportActionBar(toolbar);
92 fab = findViewById(R.id.btn_add_transaction);
94 Data.profile.addObserver((o, arg) -> {
95 MobileLedgerProfile profile = Data.profile.get();
97 if (profile == null) setTitle(R.string.app_name);
98 else setTitle(profile.getName());
99 updateLastUpdateTextFromDB();
100 if (profile.isPostingPermitted()) fab.show();
105 drawer = findViewById(R.id.drawer_layout);
106 ActionBarDrawerToggle toggle =
107 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
108 R.string.navigation_drawer_close);
109 drawer.addDrawerListener(toggle);
112 TextView ver = drawer.findViewById(R.id.drawer_version_text);
116 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
117 ver.setText(pi.versionName);
119 catch (Exception e) {
123 tvLastUpdate = findViewById(R.id.transactions_last_update);
125 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
126 progressBar = findViewById(R.id.transaction_list_progress_bar);
127 if (progressBar == null)
128 throw new RuntimeException("Can't get hold on the transaction value progress bar");
129 progressLayout = findViewById(R.id.transaction_progress_layout);
130 if (progressLayout == null) throw new RuntimeException(
131 "Can't get hold on the transaction value progress bar layout");
133 fragmentManager = getSupportFragmentManager();
134 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
136 markDrawerItemCurrent(R.id.nav_account_summary);
138 mViewPager = findViewById(R.id.root_frame);
139 mViewPager.setAdapter(mSectionsPagerAdapter);
140 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
142 public void onPageSelected(int position) {
145 markDrawerItemCurrent(R.id.nav_account_summary);
148 markDrawerItemCurrent(R.id.nav_latest_transactions);
151 Log.e("MainActivity", String.format("Unexpected page index %d", position));
154 super.onPageSelected(position);
158 Data.lastUpdateDate.addObserver((o, arg) -> {
159 Log.d("main", "lastUpdateDate changed");
160 runOnUiThread(() -> {
161 Date date = Data.lastUpdateDate.get();
163 tvLastUpdate.setText(R.string.transaction_last_update_never);
166 final String text = DateFormat.getDateTimeInstance().format(date);
167 tvLastUpdate.setText(text);
168 Log.d("despair", String.format("Date formatted: %s", text));
173 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
175 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
178 protected void onResume() {
182 private void startAddProfileActivity() {
183 Intent intent = new Intent(this, ProfileListActivity.class);
184 Bundle args = new Bundle();
185 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
186 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
187 intent.putExtras(args);
188 startActivity(intent, args);
190 private void setupProfile() {
191 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
192 MobileLedgerProfile profile;
194 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
196 if (Data.profiles.getList().isEmpty()) {
197 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
198 findViewById(R.id.pager_layout).setVisibility(View.GONE);
202 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
203 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
205 if (profile == null) profile = Data.profiles.get(0);
207 if (profile == null) throw new AssertionError("profile must have a value");
209 Data.setCurrentProfile(profile);
211 public void fabNewTransactionClicked(View view) {
212 Intent intent = new Intent(this, NewTransactionActivity.class);
213 startActivity(intent);
214 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
216 public void navSettingsClicked(View view) {
217 Intent intent = new Intent(this, SettingsActivity.class);
218 startActivity(intent);
219 drawer.closeDrawers();
221 public void markDrawerItemCurrent(int id) {
222 TextView item = drawer.findViewById(id);
223 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
224 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
227 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
230 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
232 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
233 for (int i = 0; i < actions.getChildCount(); i++) {
234 View view = actions.getChildAt(i);
235 if (view.getId() != id) {
236 view.setBackgroundColor(transparent);
240 public void onAccountSummaryClicked(View view) {
241 drawer.closeDrawers();
243 showAccountSummaryFragment();
245 private void showAccountSummaryFragment() {
246 mViewPager.setCurrentItem(0, true);
247 TransactionListFragment.accountFilter.set(null);
248 // FragmentTransaction ft = fragmentManager.beginTransaction();
249 // accountSummaryFragment = new AccountSummaryFragment();
250 // ft.replace(R.id.root_frame, accountSummaryFragment);
252 // currentFragment = accountSummaryFragment;
254 public void onLatestTransactionsClicked(View view) {
255 drawer.closeDrawers();
257 showTransactionsFragment(null);
259 private void resetFragmentBackStack() {
260 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
262 private void showTransactionsFragment(LedgerAccount account) {
263 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
264 mViewPager.setCurrentItem(1, true);
265 // FragmentTransaction ft = fragmentManager.beginTransaction();
266 // if (transactionListFragment == null) {
267 // Log.d("flow", "MainActivity creating TransactionListFragment");
268 // transactionListFragment = new TransactionListFragment();
270 // Bundle bundle = new Bundle();
271 // if (account != null) {
272 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
273 // account.getName());
275 // transactionListFragment.setArguments(bundle);
276 // ft.replace(R.id.root_frame, transactionListFragment);
277 // if (account != null)
278 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
281 // currentFragment = transactionListFragment;
283 public void showAccountTransactions(LedgerAccount account) {
284 showTransactionsFragment(account);
287 public void onBackPressed() {
288 DrawerLayout drawer = findViewById(R.id.drawer_layout);
289 if (drawer.isDrawerOpen(GravityCompat.START)) {
290 drawer.closeDrawer(GravityCompat.START);
294 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
296 super.onBackPressed();
299 public void updateLastUpdateTextFromDB() {
301 final MobileLedgerProfile profile = Data.profile.get();
303 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
305 Log.d("transactions", String.format("Last update = %d", last_update));
306 if (last_update == 0) {
307 Data.lastUpdateDate.set(null);
310 Data.lastUpdateDate.set(new Date(last_update));
314 public void scheduleTransactionListRetrieval() {
315 if (Data.profile.get() == null) return;
317 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
319 retrieveTransactionsTask.execute();
320 bTransactionListCancelDownload.setEnabled(true);
322 public void onStopTransactionRefreshClick(View view) {
323 Log.d("interactive", "Cancelling transactions refresh");
324 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
325 bTransactionListCancelDownload.setEnabled(false);
327 public void onRetrieveDone(String error) {
328 progressLayout.setVisibility(View.GONE);
331 updateLastUpdateTextFromDB();
333 new RefreshDescriptionsTask().execute();
335 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
337 public void onRetrieveStart() {
338 progressBar.setIndeterminate(true);
339 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
340 else progressBar.setProgress(0);
341 progressLayout.setVisibility(View.VISIBLE);
343 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
344 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
345 (progress.getTotal() == 0))
347 progressBar.setIndeterminate(true);
350 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
351 progressBar.setMin(0);
353 progressBar.setMax(progress.getTotal());
354 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
355 progressBar.setProgress(progress.getProgress(), true);
357 else progressBar.setProgress(progress.getProgress());
358 progressBar.setIndeterminate(false);
361 public void navProfilesClicked(View view) {
362 drawer.closeDrawers();
363 Intent intent = new Intent(this, ProfileListActivity.class);
364 startActivity(intent);
366 public class SectionsPagerAdapter extends FragmentPagerAdapter {
368 public SectionsPagerAdapter(FragmentManager fm) {
373 public Fragment getItem(int position) {
374 Log.d("main", String.format("Switching to fragment %d", position));
377 return new AccountSummaryFragment();
379 return new TransactionListFragment();
381 throw new IllegalStateException(
382 String.format("Unexpected fragment index: " + "%d", position));
387 public int getCount() {
391 public void fabShouldShow() {
392 MobileLedgerProfile profile = Data.profile.get();
393 if (profile.isPostingPermitted()) fab.show();