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.content.res.ColorStateList;
23 import android.graphics.Color;
24 import android.os.Build;
25 import android.os.Bundle;
26 import com.google.android.material.floatingactionbutton.FloatingActionButton;
27 import androidx.fragment.app.Fragment;
28 import androidx.fragment.app.FragmentManager;
29 import androidx.fragment.app.FragmentPagerAdapter;
30 import androidx.core.view.GravityCompat;
31 import androidx.viewpager.widget.ViewPager;
32 import androidx.drawerlayout.widget.DrawerLayout;
33 import androidx.appcompat.app.ActionBarDrawerToggle;
34 import androidx.appcompat.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.Colors;
51 import net.ktnx.mobileledger.utils.MLDB;
53 import java.lang.ref.WeakReference;
54 import java.text.DateFormat;
55 import java.util.Date;
57 public class MainActivity extends CrashReportingActivity {
59 private FragmentManager fragmentManager;
60 private TextView tvLastUpdate;
61 private RetrieveTransactionsTask retrieveTransactionsTask;
62 private View bTransactionListCancelDownload;
63 private ProgressBar progressBar;
64 private LinearLayout progressLayout;
65 private SectionsPagerAdapter mSectionsPagerAdapter;
66 private ViewPager mViewPager;
67 private FloatingActionButton fab;
70 protected void onStart() {
73 Data.lastUpdateDate.set(null);
74 updateLastUpdateTextFromDB();
75 Date lastUpdate = Data.lastUpdateDate.get();
77 long now = new Date().getTime();
78 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
79 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
81 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
82 lastUpdate.getTime() / 1000f, now / 1000f));
84 scheduleTransactionListRetrieval();
88 protected void onCreate(Bundle savedInstanceState) {
89 super.onCreate(savedInstanceState);
91 setContentView(R.layout.activity_main);
92 Toolbar toolbar = findViewById(R.id.toolbar);
93 setSupportActionBar(toolbar);
94 fab = findViewById(R.id.btn_add_transaction);
96 Data.profile.addObserver((o, arg) -> {
97 MobileLedgerProfile profile = Data.profile.get();
99 if (profile == null) setTitle(R.string.app_name);
100 else setTitle(profile.getName());
101 updateLastUpdateTextFromDB();
102 if (profile.isPostingPermitted()) {
103 toolbar.setSubtitle(null);
107 toolbar.setSubtitle(R.string.profile_subitlte_read_only);
111 int newProfileTheme = profile.getThemeId();
112 if (newProfileTheme != Colors.profileThemeId) {
113 Log.d("profiles", String.format("profile theme %d → %d", Colors.profileThemeId,
115 profileThemeChanged();
116 Colors.profileThemeId = newProfileTheme;
121 drawer = findViewById(R.id.drawer_layout);
122 ActionBarDrawerToggle toggle =
123 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
124 R.string.navigation_drawer_close);
125 drawer.addDrawerListener(toggle);
128 TextView ver = drawer.findViewById(R.id.drawer_version_text);
132 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
133 ver.setText(pi.versionName);
135 catch (Exception e) {
139 tvLastUpdate = findViewById(R.id.transactions_last_update);
141 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
142 progressBar = findViewById(R.id.transaction_list_progress_bar);
143 if (progressBar == null)
144 throw new RuntimeException("Can't get hold on the transaction value progress bar");
145 progressLayout = findViewById(R.id.transaction_progress_layout);
146 if (progressLayout == null) throw new RuntimeException(
147 "Can't get hold on the transaction value progress bar layout");
149 fragmentManager = getSupportFragmentManager();
150 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
152 markDrawerItemCurrent(R.id.nav_account_summary);
154 mViewPager = findViewById(R.id.root_frame);
155 mViewPager.setAdapter(mSectionsPagerAdapter);
156 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
158 public void onPageSelected(int position) {
161 markDrawerItemCurrent(R.id.nav_account_summary);
164 markDrawerItemCurrent(R.id.nav_latest_transactions);
167 Log.e("MainActivity", String.format("Unexpected page index %d", position));
170 super.onPageSelected(position);
174 Data.lastUpdateDate.addObserver((o, arg) -> {
175 Log.d("main", "lastUpdateDate changed");
176 runOnUiThread(() -> {
177 Date date = Data.lastUpdateDate.get();
179 tvLastUpdate.setText(R.string.transaction_last_update_never);
182 final String text = DateFormat.getDateTimeInstance().format(date);
183 tvLastUpdate.setText(text);
184 Log.d("despair", String.format("Date formatted: %s", text));
189 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
191 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
193 private void profileThemeChanged() {
194 setupProfileColors();
196 // restart activity to reflect theme change
198 Intent intent = new Intent(this, this.getClass());
199 startActivity(intent);
202 protected void onResume() {
206 private void startAddProfileActivity() {
207 Intent intent = new Intent(this, ProfileListActivity.class);
208 Bundle args = new Bundle();
209 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
210 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
211 intent.putExtras(args);
212 startActivity(intent, args);
214 private void setupProfile() {
215 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
216 MobileLedgerProfile profile;
218 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
220 if (Data.profiles.getList().isEmpty()) {
221 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
222 findViewById(R.id.pager_layout).setVisibility(View.GONE);
226 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
227 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
229 if (profile == null) profile = Data.profiles.get(0);
231 if (profile == null) throw new AssertionError("profile must have a value");
233 Data.setCurrentProfile(profile);
235 public void fabNewTransactionClicked(View view) {
236 Intent intent = new Intent(this, NewTransactionActivity.class);
237 startActivity(intent);
238 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
240 public void navSettingsClicked(View view) {
241 Intent intent = new Intent(this, SettingsActivity.class);
242 startActivity(intent);
243 drawer.closeDrawers();
245 public void markDrawerItemCurrent(int id) {
246 TextView item = drawer.findViewById(id);
247 item.setBackgroundColor(Colors.tableRowDarkBG);
249 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
250 for (int i = 0; i < actions.getChildCount(); i++) {
251 View view = actions.getChildAt(i);
252 if (view.getId() != id) {
253 view.setBackgroundColor(Color.TRANSPARENT);
257 public void onAccountSummaryClicked(View view) {
258 drawer.closeDrawers();
260 showAccountSummaryFragment();
262 private void showAccountSummaryFragment() {
263 mViewPager.setCurrentItem(0, true);
264 TransactionListFragment.accountFilter.set(null);
265 // FragmentTransaction ft = fragmentManager.beginTransaction();
266 // accountSummaryFragment = new AccountSummaryFragment();
267 // ft.replace(R.id.root_frame, accountSummaryFragment);
269 // currentFragment = accountSummaryFragment;
271 public void onLatestTransactionsClicked(View view) {
272 drawer.closeDrawers();
274 showTransactionsFragment(null);
276 private void resetFragmentBackStack() {
277 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
279 private void showTransactionsFragment(LedgerAccount account) {
280 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
281 mViewPager.setCurrentItem(1, true);
282 // FragmentTransaction ft = fragmentManager.beginTransaction();
283 // if (transactionListFragment == null) {
284 // Log.d("flow", "MainActivity creating TransactionListFragment");
285 // transactionListFragment = new TransactionListFragment();
287 // Bundle bundle = new Bundle();
288 // if (account != null) {
289 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
290 // account.getName());
292 // transactionListFragment.setArguments(bundle);
293 // ft.replace(R.id.root_frame, transactionListFragment);
294 // if (account != null)
295 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
298 // currentFragment = transactionListFragment;
300 public void showAccountTransactions(LedgerAccount account) {
301 showTransactionsFragment(account);
304 public void onBackPressed() {
305 DrawerLayout drawer = findViewById(R.id.drawer_layout);
306 if (drawer.isDrawerOpen(GravityCompat.START)) {
307 drawer.closeDrawer(GravityCompat.START);
311 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
313 super.onBackPressed();
316 public void updateLastUpdateTextFromDB() {
318 final MobileLedgerProfile profile = Data.profile.get();
320 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
322 Log.d("transactions", String.format("Last update = %d", last_update));
323 if (last_update == 0) {
324 Data.lastUpdateDate.set(null);
327 Data.lastUpdateDate.set(new Date(last_update));
331 public void scheduleTransactionListRetrieval() {
332 if (Data.profile.get() == null) return;
334 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
336 retrieveTransactionsTask.execute();
337 bTransactionListCancelDownload.setEnabled(true);
339 public void onStopTransactionRefreshClick(View view) {
340 Log.d("interactive", "Cancelling transactions refresh");
341 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
342 bTransactionListCancelDownload.setEnabled(false);
344 public void onRetrieveDone(String error) {
345 progressLayout.setVisibility(View.GONE);
348 updateLastUpdateTextFromDB();
350 new RefreshDescriptionsTask().execute();
352 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
354 public void onRetrieveStart() {
355 progressBar.setIndeterminateTintList(ColorStateList.valueOf(Colors.primary));
356 progressBar.setProgressTintList(ColorStateList.valueOf(Colors.primary));
357 progressBar.setIndeterminate(true);
358 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
359 else progressBar.setProgress(0);
360 progressLayout.setVisibility(View.VISIBLE);
362 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
363 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
364 (progress.getTotal() == 0))
366 progressBar.setIndeterminate(true);
369 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
370 progressBar.setMin(0);
372 progressBar.setMax(progress.getTotal());
373 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
374 progressBar.setProgress(progress.getProgress(), true);
376 else progressBar.setProgress(progress.getProgress());
377 progressBar.setIndeterminate(false);
380 public void navProfilesClicked(View view) {
381 drawer.closeDrawers();
382 Intent intent = new Intent(this, ProfileListActivity.class);
383 startActivity(intent);
385 public void fabShouldShow() {
386 MobileLedgerProfile profile = Data.profile.get();
387 if ((profile != null) && profile.isPostingPermitted()) fab.show();
390 public class SectionsPagerAdapter extends FragmentPagerAdapter {
392 public SectionsPagerAdapter(FragmentManager fm) {
397 public Fragment getItem(int position) {
398 Log.d("main", String.format("Switching to fragment %d", position));
401 return new AccountSummaryFragment();
403 return new TransactionListFragment();
405 throw new IllegalStateException(
406 String.format("Unexpected fragment index: " + "%d", position));
411 public int getCount() {