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.time.ZoneId;
55 import java.time.format.DateTimeFormatter;
56 import java.util.Date;
58 public class MainActivity extends AppCompatActivity {
59 public MobileLedgerListFragment currentFragment = null;
61 private AccountSummaryFragment accountSummaryFragment;
62 private TransactionListFragment transactionListFragment;
63 private FragmentManager fragmentManager;
64 private TextView tvLastUpdate;
65 private RetrieveTransactionsTask retrieveTransactionsTask;
66 private View bTransactionListCancelDownload;
67 private ProgressBar progressBar;
68 private LinearLayout progressLayout;
69 private SectionsPagerAdapter mSectionsPagerAdapter;
70 private ViewPager mViewPager;
73 protected void onStart() {
76 Data.lastUpdateDate.set(null);
77 updateLastUpdateTextFromDB();
78 Date lastUpdate = Data.lastUpdateDate.get();
80 long now = new Date().getTime();
81 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
82 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
84 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
85 lastUpdate.getTime() / 1000f, now / 1000f));
87 scheduleTransactionListRetrieval();
91 protected void onCreate(Bundle savedInstanceState) {
92 super.onCreate(savedInstanceState);
93 setContentView(R.layout.activity_main);
94 Toolbar toolbar = findViewById(R.id.toolbar);
95 setSupportActionBar(toolbar);
97 Data.profile.addObserver((o, arg) -> {
98 MobileLedgerProfile profile = Data.profile.get();
100 if (profile == null) toolbar.setSubtitle("");
101 else toolbar.setSubtitle(profile.getName());
107 drawer = findViewById(R.id.drawer_layout);
108 ActionBarDrawerToggle toggle =
109 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
110 R.string.navigation_drawer_close);
111 drawer.addDrawerListener(toggle);
114 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
118 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
119 ver.setText(pi.versionName);
121 catch (Exception e) {
125 tvLastUpdate = findViewById(R.id.transactions_last_update);
127 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
128 progressBar = findViewById(R.id.transaction_list_progress_bar);
129 if (progressBar == null)
130 throw new RuntimeException("Can't get hold on the transaction value progress bar");
131 progressLayout = findViewById(R.id.transaction_progress_layout);
132 if (progressLayout == null) throw new RuntimeException(
133 "Can't get hold on the transaction value progress bar layout");
135 fragmentManager = getSupportFragmentManager();
136 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
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 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
167 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
168 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
171 tvLastUpdate.setText(DateFormat.getDateTimeInstance().format(date));
177 private void setupProfile() {
178 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
179 MobileLedgerProfile profile = null;
181 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
182 if (profileUUID == null) {
183 if (Data.profiles.isEmpty()) {
184 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
185 profile = Data.profiles.get(0);
187 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
188 Log.d("profiles", "Migrating from preferences to profiles");
189 // migration to multiple profiles
190 if (profile.getUrl().isEmpty()) {
192 Intent intent = new Intent(this, ProfileListActivity.class);
193 startActivity(intent);
195 profile.setUrl(backend.getString("backend_url", ""));
196 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
197 profile.setAuthUserName(backend.getString("backend_auth_user", null));
198 profile.setAuthPassword(backend.getString("backend_auth_password", null));
200 SharedPreferences.Editor editor = backend.edit();
206 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
209 if (profile == null) profile = Data.profiles.get(0);
211 if (profile == null) throw new AssertionError("profile must have a value");
213 Data.setCurrentProfile(profile);
215 if (profile.getUrl().isEmpty()) {
216 Intent intent = new Intent(this, ProfileListActivity.class);
217 Bundle args = new Bundle();
218 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
219 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
220 intent.putExtras(args);
221 startActivity(intent, args);
224 public void fab_new_transaction_clicked(View view) {
225 Intent intent = new Intent(this, NewTransactionActivity.class);
226 startActivity(intent);
227 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
230 public void nav_exit_clicked(View view) {
231 Log.w("app", "exiting");
235 public void nav_settings_clicked(View view) {
236 Intent intent = new Intent(this, SettingsActivity.class);
237 startActivity(intent);
238 drawer.closeDrawers();
240 public void markDrawerItemCurrent(int id) {
241 TextView item = drawer.findViewById(id);
242 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
243 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
246 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
249 setTitle(item.getText());
251 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
253 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
254 for (int i = 0; i < actions.getChildCount(); i++) {
255 View view = actions.getChildAt(i);
256 if (view.getId() != id) {
257 view.setBackgroundColor(transparent);
261 public void onViewClicked(View view) {
262 switch (view.getId()) {
263 case R.id.clearAccountNameFilter:
264 if (transactionListFragment != null)
265 transactionListFragment.onClearAccountNameClick(view);
268 Log.e("click", String.format("View %d click not handled", view.getId()));
271 public void onAccountSummaryClicked(View view) {
272 drawer.closeDrawers();
274 showAccountSummaryFragment();
276 private void showAccountSummaryFragment() {
277 mViewPager.setCurrentItem(0, true);
278 // FragmentTransaction ft = fragmentManager.beginTransaction();
279 // accountSummaryFragment = new AccountSummaryFragment();
280 // ft.replace(R.id.root_frame, accountSummaryFragment);
282 // currentFragment = accountSummaryFragment;
284 public void onLatestTransactionsClicked(View view) {
285 drawer.closeDrawers();
287 showTransactionsFragment(null);
289 private void resetFragmentBackStack() {
290 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
292 private void showTransactionsFragment(LedgerAccount account) {
293 mViewPager.setCurrentItem(1, true);
294 // FragmentTransaction ft = fragmentManager.beginTransaction();
295 // if (transactionListFragment == null) {
296 // Log.d("flow", "MainActivity creating TransactionListFragment");
297 // transactionListFragment = new TransactionListFragment();
299 // Bundle bundle = new Bundle();
300 // if (account != null) {
301 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
302 // account.getName());
304 // transactionListFragment.setArguments(bundle);
305 // ft.replace(R.id.root_frame, transactionListFragment);
306 // if (account != null)
307 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
310 // currentFragment = transactionListFragment;
312 public void showAccountTransactions(LedgerAccount account) {
313 showTransactionsFragment(account);
316 public void onBackPressed() {
317 DrawerLayout drawer = findViewById(R.id.drawer_layout);
318 if (drawer.isDrawerOpen(GravityCompat.START)) {
319 drawer.closeDrawer(GravityCompat.START);
323 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
325 super.onBackPressed();
328 public void updateLastUpdateTextFromDB() {
330 long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
332 Log.d("transactions", String.format("Last update = %d", last_update));
333 if (last_update == 0) {
334 Data.lastUpdateDate.set(null);
337 Data.lastUpdateDate.set(new Date(last_update));
341 public void scheduleTransactionListRetrieval() {
342 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
344 retrieveTransactionsTask.execute();
345 bTransactionListCancelDownload.setEnabled(true);
347 public void onStopTransactionRefreshClick(View view) {
348 Log.d("interactive", "Cancelling transactions refresh");
349 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
350 bTransactionListCancelDownload.setEnabled(false);
352 public void onRetrieveDone(boolean success) {
353 progressLayout.setVisibility(View.GONE);
354 updateLastUpdateTextFromDB();
356 new RefreshDescriptionsTask().execute();
358 public void onRetrieveStart() {
359 progressBar.setIndeterminate(true);
360 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
361 else progressBar.setProgress(0);
362 progressLayout.setVisibility(View.VISIBLE);
364 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
365 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
366 (progress.getTotal() == 0))
368 progressBar.setIndeterminate(true);
371 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
372 progressBar.setMin(0);
374 progressBar.setMax(progress.getTotal());
375 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
376 progressBar.setProgress(progress.getProgress(), true);
378 else progressBar.setProgress(progress.getProgress());
379 progressBar.setIndeterminate(false);
382 public void nav_profiles_clicked(View view) {
383 drawer.closeDrawers();
384 Intent intent = new Intent(this, ProfileListActivity.class);
385 startActivity(intent);
387 public class SectionsPagerAdapter extends FragmentPagerAdapter {
389 public SectionsPagerAdapter(FragmentManager fm) {
394 public Fragment getItem(int position) {
395 Log.d("main", String.format("Switching to gragment %d", position));
398 return new AccountSummaryFragment();
400 return new TransactionListFragment();
402 throw new IllegalStateException(
403 String.format("Unexpected fragment index: " + "%d", position));
408 public int getCount() {