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.v4.app.Fragment;
26 import android.support.v4.app.FragmentManager;
27 import android.support.v4.app.FragmentPagerAdapter;
28 import android.support.v4.view.GravityCompat;
29 import android.support.v4.view.ViewPager;
30 import android.support.v4.widget.DrawerLayout;
31 import android.support.v7.app.ActionBarDrawerToggle;
32 import android.support.v7.app.AppCompatActivity;
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 AppCompatActivity {
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;
67 protected void onStart() {
70 Data.lastUpdateDate.set(null);
71 updateLastUpdateTextFromDB();
72 Date lastUpdate = Data.lastUpdateDate.get();
74 long now = new Date().getTime();
75 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
76 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
78 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
79 lastUpdate.getTime() / 1000f, now / 1000f));
81 scheduleTransactionListRetrieval();
85 protected void onCreate(Bundle savedInstanceState) {
86 super.onCreate(savedInstanceState);
87 setContentView(R.layout.activity_main);
88 Toolbar toolbar = findViewById(R.id.toolbar);
89 setSupportActionBar(toolbar);
91 Data.profile.addObserver((o, arg) -> {
92 MobileLedgerProfile profile = Data.profile.get();
94 if (profile == null) setTitle(R.string.app_name);
95 else setTitle(profile.getName());
96 updateLastUpdateTextFromDB();
100 drawer = findViewById(R.id.drawer_layout);
101 ActionBarDrawerToggle toggle =
102 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
103 R.string.navigation_drawer_close);
104 drawer.addDrawerListener(toggle);
107 TextView ver = drawer.findViewById(R.id.drawer_version_text);
111 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
112 ver.setText(pi.versionName);
114 catch (Exception e) {
118 tvLastUpdate = findViewById(R.id.transactions_last_update);
120 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
121 progressBar = findViewById(R.id.transaction_list_progress_bar);
122 if (progressBar == null)
123 throw new RuntimeException("Can't get hold on the transaction value progress bar");
124 progressLayout = findViewById(R.id.transaction_progress_layout);
125 if (progressLayout == null) throw new RuntimeException(
126 "Can't get hold on the transaction value progress bar layout");
128 fragmentManager = getSupportFragmentManager();
129 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
131 markDrawerItemCurrent(R.id.nav_account_summary);
133 mViewPager = findViewById(R.id.root_frame);
134 mViewPager.setAdapter(mSectionsPagerAdapter);
135 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
137 public void onPageSelected(int position) {
140 markDrawerItemCurrent(R.id.nav_account_summary);
143 markDrawerItemCurrent(R.id.nav_latest_transactions);
146 Log.e("MainActivity", String.format("Unexpected page index %d", position));
149 super.onPageSelected(position);
153 Data.lastUpdateDate.addObserver((o, arg) -> {
154 Log.d("main", "lastUpdateDate changed");
155 runOnUiThread(() -> {
156 Date date = Data.lastUpdateDate.get();
158 tvLastUpdate.setText(R.string.transaction_last_update_never);
161 final String text = DateFormat.getDateTimeInstance().format(date);
162 tvLastUpdate.setText(text);
163 Log.d("despair", String.format("Date formatted: %s", text));
168 findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
170 findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
173 protected void onResume() {
177 private void startAddProfileActivity() {
178 Intent intent = new Intent(this, ProfileListActivity.class);
179 Bundle args = new Bundle();
180 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
181 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
182 intent.putExtras(args);
183 startActivity(intent, args);
185 private void setupProfile() {
186 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
187 MobileLedgerProfile profile;
189 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
191 if (Data.profiles.getList().isEmpty()) {
192 findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
193 findViewById(R.id.pager_layout).setVisibility(View.GONE);
197 findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
198 findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
200 if (profile == null) profile = Data.profiles.get(0);
202 if (profile == null) throw new AssertionError("profile must have a value");
204 Data.setCurrentProfile(profile);
206 public void fabNewTransactionClicked(View view) {
207 Intent intent = new Intent(this, NewTransactionActivity.class);
208 startActivity(intent);
209 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
211 public void navSettingsClicked(View view) {
212 Intent intent = new Intent(this, SettingsActivity.class);
213 startActivity(intent);
214 drawer.closeDrawers();
216 public void markDrawerItemCurrent(int id) {
217 TextView item = drawer.findViewById(id);
218 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
219 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
222 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
225 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
227 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
228 for (int i = 0; i < actions.getChildCount(); i++) {
229 View view = actions.getChildAt(i);
230 if (view.getId() != id) {
231 view.setBackgroundColor(transparent);
235 public void onAccountSummaryClicked(View view) {
236 drawer.closeDrawers();
238 showAccountSummaryFragment();
240 private void showAccountSummaryFragment() {
241 mViewPager.setCurrentItem(0, true);
242 TransactionListFragment.accountFilter.set(null);
243 // FragmentTransaction ft = fragmentManager.beginTransaction();
244 // accountSummaryFragment = new AccountSummaryFragment();
245 // ft.replace(R.id.root_frame, accountSummaryFragment);
247 // currentFragment = accountSummaryFragment;
249 public void onLatestTransactionsClicked(View view) {
250 drawer.closeDrawers();
252 showTransactionsFragment(null);
254 private void resetFragmentBackStack() {
255 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
257 private void showTransactionsFragment(LedgerAccount account) {
258 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
259 mViewPager.setCurrentItem(1, true);
260 // FragmentTransaction ft = fragmentManager.beginTransaction();
261 // if (transactionListFragment == null) {
262 // Log.d("flow", "MainActivity creating TransactionListFragment");
263 // transactionListFragment = new TransactionListFragment();
265 // Bundle bundle = new Bundle();
266 // if (account != null) {
267 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
268 // account.getName());
270 // transactionListFragment.setArguments(bundle);
271 // ft.replace(R.id.root_frame, transactionListFragment);
272 // if (account != null)
273 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
276 // currentFragment = transactionListFragment;
278 public void showAccountTransactions(LedgerAccount account) {
279 showTransactionsFragment(account);
282 public void onBackPressed() {
283 DrawerLayout drawer = findViewById(R.id.drawer_layout);
284 if (drawer.isDrawerOpen(GravityCompat.START)) {
285 drawer.closeDrawer(GravityCompat.START);
289 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
291 super.onBackPressed();
294 public void updateLastUpdateTextFromDB() {
296 final MobileLedgerProfile profile = Data.profile.get();
298 (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
300 Log.d("transactions", String.format("Last update = %d", last_update));
301 if (last_update == 0) {
302 Data.lastUpdateDate.set(null);
305 Data.lastUpdateDate.set(new Date(last_update));
309 public void scheduleTransactionListRetrieval() {
310 if (Data.profile.get() == null) return;
312 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
314 retrieveTransactionsTask.execute();
315 bTransactionListCancelDownload.setEnabled(true);
317 public void onStopTransactionRefreshClick(View view) {
318 Log.d("interactive", "Cancelling transactions refresh");
319 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
320 bTransactionListCancelDownload.setEnabled(false);
322 public void onRetrieveDone(String error) {
323 progressLayout.setVisibility(View.GONE);
326 updateLastUpdateTextFromDB();
328 new RefreshDescriptionsTask().execute();
330 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
332 public void onRetrieveStart() {
333 progressBar.setIndeterminate(true);
334 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
335 else progressBar.setProgress(0);
336 progressLayout.setVisibility(View.VISIBLE);
338 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
339 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
340 (progress.getTotal() == 0))
342 progressBar.setIndeterminate(true);
345 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
346 progressBar.setMin(0);
348 progressBar.setMax(progress.getTotal());
349 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
350 progressBar.setProgress(progress.getProgress(), true);
352 else progressBar.setProgress(progress.getProgress());
353 progressBar.setIndeterminate(false);
356 public void navProfilesClicked(View view) {
357 drawer.closeDrawers();
358 Intent intent = new Intent(this, ProfileListActivity.class);
359 startActivity(intent);
361 public class SectionsPagerAdapter extends FragmentPagerAdapter {
363 public SectionsPagerAdapter(FragmentManager fm) {
368 public Fragment getItem(int position) {
369 Log.d("main", String.format("Switching to fragment %d", position));
372 return new AccountSummaryFragment();
374 return new TransactionListFragment();
376 throw new IllegalStateException(
377 String.format("Unexpected fragment index: " + "%d", position));
382 public int getCount() {