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.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()) {
101 toolbar.setSubtitle(null);
105 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
111 drawer = findViewById(R.id.drawer_layout);
112 ActionBarDrawerToggle toggle =
113 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
114 R.string.navigation_drawer_close);
115 drawer.addDrawerListener(toggle);
118 TextView ver = drawer.findViewById(R.id.drawer_version_text);
122 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
123 ver.setText(pi.versionName);
125 catch (Exception e) {
129 tvLastUpdate = findViewById(R.id.transactions_last_update);
131 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
132 progressBar = findViewById(R.id.transaction_list_progress_bar);
133 if (progressBar == null)
134 throw new RuntimeException("Can't get hold on the transaction value progress bar");
135 progressLayout = findViewById(R.id.transaction_progress_layout);
136 if (progressLayout == null) throw new RuntimeException(
137 "Can't get hold on the transaction value progress bar layout");
139 fragmentManager = getSupportFragmentManager();
140 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
142 markDrawerItemCurrent(R.id.nav_account_summary);
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((o, arg) -> {
165 Log.d("main", "lastUpdateDate changed");
166 runOnUiThread(() -> {
167 Date date = Data.lastUpdateDate.get();
169 tvLastUpdate.setText(R.string.transaction_last_update_never);
172 final String text = DateFormat.getDateTimeInstance().format(date);
173 tvLastUpdate.setText(text);
174 Log.d("despair", String.format("Date formatted: %s", text));
179 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
181 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
184 protected void onResume() {
188 private void startAddProfileActivity() {
189 Intent intent = new Intent(this, ProfileListActivity.class);
190 Bundle args = new Bundle();
191 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
192 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
193 intent.putExtras(args);
194 startActivity(intent, args);
196 private void setupProfile() {
197 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
198 MobileLedgerProfile profile;
200 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
202 if (Data.profiles.getList().isEmpty()) {
203 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
204 findViewById(R.id.pager_layout).setVisibility(View.GONE);
208 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
209 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
211 if (profile == null) profile = Data.profiles.get(0);
213 if (profile == null) throw new AssertionError("profile must have a value");
215 Data.setCurrentProfile(profile);
217 public void fabNewTransactionClicked(View view) {
218 Intent intent = new Intent(this, NewTransactionActivity.class);
219 startActivity(intent);
220 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
222 public void navSettingsClicked(View view) {
223 Intent intent = new Intent(this, SettingsActivity.class);
224 startActivity(intent);
225 drawer.closeDrawers();
227 public void markDrawerItemCurrent(int id) {
228 TextView item = drawer.findViewById(id);
229 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
230 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
233 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
236 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
238 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
239 for (int i = 0; i < actions.getChildCount(); i++) {
240 View view = actions.getChildAt(i);
241 if (view.getId() != id) {
242 view.setBackgroundColor(transparent);
246 public void onAccountSummaryClicked(View view) {
247 drawer.closeDrawers();
249 showAccountSummaryFragment();
251 private void showAccountSummaryFragment() {
252 mViewPager.setCurrentItem(0, true);
253 TransactionListFragment.accountFilter.set(null);
254 // FragmentTransaction ft = fragmentManager.beginTransaction();
255 // accountSummaryFragment = new AccountSummaryFragment();
256 // ft.replace(R.id.root_frame, accountSummaryFragment);
258 // currentFragment = accountSummaryFragment;
260 public void onLatestTransactionsClicked(View view) {
261 drawer.closeDrawers();
263 showTransactionsFragment(null);
265 private void resetFragmentBackStack() {
266 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
268 private void showTransactionsFragment(LedgerAccount account) {
269 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
270 mViewPager.setCurrentItem(1, true);
271 // FragmentTransaction ft = fragmentManager.beginTransaction();
272 // if (transactionListFragment == null) {
273 // Log.d("flow", "MainActivity creating TransactionListFragment");
274 // transactionListFragment = new TransactionListFragment();
276 // Bundle bundle = new Bundle();
277 // if (account != null) {
278 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
279 // account.getName());
281 // transactionListFragment.setArguments(bundle);
282 // ft.replace(R.id.root_frame, transactionListFragment);
283 // if (account != null)
284 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
287 // currentFragment = transactionListFragment;
289 public void showAccountTransactions(LedgerAccount account) {
290 showTransactionsFragment(account);
293 public void onBackPressed() {
294 DrawerLayout drawer = findViewById(R.id.drawer_layout);
295 if (drawer.isDrawerOpen(GravityCompat.START)) {
296 drawer.closeDrawer(GravityCompat.START);
300 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
302 super.onBackPressed();
305 public void updateLastUpdateTextFromDB() {
307 final MobileLedgerProfile profile = Data.profile.get();
309 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
311 Log.d("transactions", String.format("Last update = %d", last_update));
312 if (last_update == 0) {
313 Data.lastUpdateDate.set(null);
316 Data.lastUpdateDate.set(new Date(last_update));
320 public void scheduleTransactionListRetrieval() {
321 if (Data.profile.get() == null) return;
323 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
325 retrieveTransactionsTask.execute();
326 bTransactionListCancelDownload.setEnabled(true);
328 public void onStopTransactionRefreshClick(View view) {
329 Log.d("interactive", "Cancelling transactions refresh");
330 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
331 bTransactionListCancelDownload.setEnabled(false);
333 public void onRetrieveDone(String error) {
334 progressLayout.setVisibility(View.GONE);
337 updateLastUpdateTextFromDB();
339 new RefreshDescriptionsTask().execute();
341 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
343 public void onRetrieveStart() {
344 progressBar.setIndeterminate(true);
345 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
346 else progressBar.setProgress(0);
347 progressLayout.setVisibility(View.VISIBLE);
349 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
350 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
351 (progress.getTotal() == 0))
353 progressBar.setIndeterminate(true);
356 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
357 progressBar.setMin(0);
359 progressBar.setMax(progress.getTotal());
360 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
361 progressBar.setProgress(progress.getProgress(), true);
363 else progressBar.setProgress(progress.getProgress());
364 progressBar.setIndeterminate(false);
367 public void navProfilesClicked(View view) {
368 drawer.closeDrawers();
369 Intent intent = new Intent(this, ProfileListActivity.class);
370 startActivity(intent);
372 public class SectionsPagerAdapter extends FragmentPagerAdapter {
374 public SectionsPagerAdapter(FragmentManager fm) {
379 public Fragment getItem(int position) {
380 Log.d("main", String.format("Switching to fragment %d", position));
383 return new AccountSummaryFragment();
385 return new TransactionListFragment();
387 throw new IllegalStateException(
388 String.format("Unexpected fragment index: " + "%d", position));
393 public int getCount() {
397 public void fabShouldShow() {
398 MobileLedgerProfile profile = Data.profile.get();
399 if (profile.isPostingPermitted()) fab.show();