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.SharedPreferences;
22 import android.content.pm.PackageInfo;
23 import android.os.Build;
24 import android.os.Bundle;
25 import android.support.annotation.ColorInt;
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;
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.MobileLedgerListFragment;
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 {
57 public MobileLedgerListFragment currentFragment = null;
59 private AccountSummaryFragment accountSummaryFragment;
60 private TransactionListFragment transactionListFragment;
61 private FragmentManager fragmentManager;
62 private TextView tvLastUpdate;
63 private RetrieveTransactionsTask retrieveTransactionsTask;
64 private View bTransactionListCancelDownload;
65 private ProgressBar progressBar;
66 private LinearLayout progressLayout;
67 private SectionsPagerAdapter mSectionsPagerAdapter;
68 private ViewPager mViewPager;
71 protected void onStart() {
74 Data.lastUpdateDate.set(null);
75 updateLastUpdateTextFromDB();
76 Date lastUpdate = Data.lastUpdateDate.get();
78 long now = new Date().getTime();
79 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
80 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
82 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
83 lastUpdate.getTime() / 1000f, now / 1000f));
85 scheduleTransactionListRetrieval();
89 protected void onCreate(Bundle savedInstanceState) {
90 super.onCreate(savedInstanceState);
91 setContentView(R.layout.activity_main);
92 Toolbar toolbar = findViewById(R.id.toolbar);
93 setSupportActionBar(toolbar);
95 Data.profile.addObserver((o, arg) -> {
96 MobileLedgerProfile profile = Data.profile.get();
98 if (profile == null) setTitle(R.string.app_name);
99 else setTitle(profile.getName());
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 android.widget.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 mViewPager = findViewById(R.id.root_frame);
137 mViewPager.setAdapter(mSectionsPagerAdapter);
138 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
140 public void onPageSelected(int position) {
143 markDrawerItemCurrent(R.id.nav_account_summary);
146 markDrawerItemCurrent(R.id.nav_latest_transactions);
149 Log.e("MainActivity", String.format("Unexpected page index %d", position));
152 super.onPageSelected(position);
156 Data.lastUpdateDate.addObserver((o, arg) -> {
157 Log.d("main", "lastUpdateDate changed");
158 runOnUiThread(() -> {
159 Date date = Data.lastUpdateDate.get();
161 tvLastUpdate.setText(R.string.transaction_last_update_never);
164 final String text = DateFormat.getDateTimeInstance().format(date);
165 tvLastUpdate.setText(text);
166 Log.d("despair", String.format("Date formatted: %s", text));
171 private void setupProfile() {
172 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
173 MobileLedgerProfile profile = null;
175 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
176 if (profileUUID == null) {
177 if (Data.profiles.isEmpty()) {
178 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
179 profile = Data.profiles.get(0);
181 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
182 Log.d("profiles", "Migrating from preferences to profiles");
183 // migration to multiple profiles
184 if (profile.getUrl().isEmpty()) {
186 Intent intent = new Intent(this, ProfileListActivity.class);
187 startActivity(intent);
189 profile.setUrl(backend.getString("backend_url", ""));
190 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
191 profile.setAuthUserName(backend.getString("backend_auth_user", null));
192 profile.setAuthPassword(backend.getString("backend_auth_password", null));
194 SharedPreferences.Editor editor = backend.edit();
200 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
203 if (profile == null) profile = Data.profiles.get(0);
205 if (profile == null) throw new AssertionError("profile must have a value");
207 Data.setCurrentProfile(profile);
209 if (profile.getUrl().isEmpty()) {
210 Intent intent = new Intent(this, ProfileListActivity.class);
211 Bundle args = new Bundle();
212 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
213 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
214 intent.putExtras(args);
215 startActivity(intent, args);
218 public void fabNewTransactionClicked(View view) {
219 Intent intent = new Intent(this, NewTransactionActivity.class);
220 startActivity(intent);
221 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
224 public void navExitClicked(View view) {
225 Log.w("app", "exiting");
229 public void navSettingsClicked(View view) {
230 Intent intent = new Intent(this, SettingsActivity.class);
231 startActivity(intent);
232 drawer.closeDrawers();
234 public void markDrawerItemCurrent(int id) {
235 TextView item = drawer.findViewById(id);
236 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
237 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
240 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
243 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
245 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
246 for (int i = 0; i < actions.getChildCount(); i++) {
247 View view = actions.getChildAt(i);
248 if (view.getId() != id) {
249 view.setBackgroundColor(transparent);
253 public void onAccountSummaryClicked(View view) {
254 drawer.closeDrawers();
256 showAccountSummaryFragment();
258 private void showAccountSummaryFragment() {
259 mViewPager.setCurrentItem(0, true);
260 TransactionListFragment.accountFilter.set(null);
261 // FragmentTransaction ft = fragmentManager.beginTransaction();
262 // accountSummaryFragment = new AccountSummaryFragment();
263 // ft.replace(R.id.root_frame, accountSummaryFragment);
265 // currentFragment = accountSummaryFragment;
267 public void onLatestTransactionsClicked(View view) {
268 drawer.closeDrawers();
270 showTransactionsFragment(null);
272 private void resetFragmentBackStack() {
273 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
275 private void showTransactionsFragment(LedgerAccount account) {
276 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
277 mViewPager.setCurrentItem(1, true);
278 // FragmentTransaction ft = fragmentManager.beginTransaction();
279 // if (transactionListFragment == null) {
280 // Log.d("flow", "MainActivity creating TransactionListFragment");
281 // transactionListFragment = new TransactionListFragment();
283 // Bundle bundle = new Bundle();
284 // if (account != null) {
285 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
286 // account.getName());
288 // transactionListFragment.setArguments(bundle);
289 // ft.replace(R.id.root_frame, transactionListFragment);
290 // if (account != null)
291 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
294 // currentFragment = transactionListFragment;
296 public void showAccountTransactions(LedgerAccount account) {
297 showTransactionsFragment(account);
300 public void onBackPressed() {
301 DrawerLayout drawer = findViewById(R.id.drawer_layout);
302 if (drawer.isDrawerOpen(GravityCompat.START)) {
303 drawer.closeDrawer(GravityCompat.START);
307 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
309 super.onBackPressed();
312 public void updateLastUpdateTextFromDB() {
314 long last_update = Data.profile.get().getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
316 Log.d("transactions", String.format("Last update = %d", last_update));
317 if (last_update == 0) {
318 Data.lastUpdateDate.set(null);
321 Data.lastUpdateDate.set(new Date(last_update));
325 public void scheduleTransactionListRetrieval() {
326 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
328 retrieveTransactionsTask.execute();
329 bTransactionListCancelDownload.setEnabled(true);
331 public void onStopTransactionRefreshClick(View view) {
332 Log.d("interactive", "Cancelling transactions refresh");
333 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
334 bTransactionListCancelDownload.setEnabled(false);
336 public void onRetrieveDone(boolean success) {
337 progressLayout.setVisibility(View.GONE);
338 updateLastUpdateTextFromDB();
340 new RefreshDescriptionsTask().execute();
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 gragment %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() {