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;
57 import java.util.Observable;
58 import java.util.Observer;
60 public class MainActivity extends AppCompatActivity {
61 public MobileLedgerListFragment currentFragment = null;
63 private AccountSummaryFragment accountSummaryFragment;
64 private TransactionListFragment transactionListFragment;
65 private FragmentManager fragmentManager;
66 private TextView tvLastUpdate;
67 private RetrieveTransactionsTask retrieveTransactionsTask;
68 private View bTransactionListCancelDownload;
69 private ProgressBar progressBar;
70 private LinearLayout progressLayout;
71 private SectionsPagerAdapter mSectionsPagerAdapter;
72 private ViewPager mViewPager;
75 protected void onStart() {
78 Data.lastUpdateDate.set(null);
79 updateLastUpdateTextFromDB();
80 Date lastUpdate = Data.lastUpdateDate.get();
82 long now = new Date().getTime();
83 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
84 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
86 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
87 lastUpdate.getTime() / 1000f, now / 1000f));
89 scheduleTransactionListRetrieval();
93 protected void onCreate(Bundle savedInstanceState) {
94 super.onCreate(savedInstanceState);
95 setContentView(R.layout.activity_main);
96 Toolbar toolbar = findViewById(R.id.toolbar);
97 setSupportActionBar(toolbar);
99 Data.profile.addObserver(new Observer() {
101 public void update(Observable o, Object arg) {
102 MobileLedgerProfile profile = Data.profile.get();
103 runOnUiThread(() -> {
104 if (profile == null) toolbar.setSubtitle("");
105 else toolbar.setSubtitle(profile.getName());
112 drawer = findViewById(R.id.drawer_layout);
113 ActionBarDrawerToggle toggle =
114 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
115 R.string.navigation_drawer_close);
116 drawer.addDrawerListener(toggle);
119 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
123 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
124 ver.setText(pi.versionName);
126 catch (Exception e) {
130 tvLastUpdate = findViewById(R.id.transactions_last_update);
132 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
133 progressBar = findViewById(R.id.transaction_list_progress_bar);
134 if (progressBar == null)
135 throw new RuntimeException("Can't get hold on the transaction value progress bar");
136 progressLayout = findViewById(R.id.transaction_progress_layout);
137 if (progressLayout == null) throw new RuntimeException(
138 "Can't get hold on the transaction value progress bar layout");
140 fragmentManager = getSupportFragmentManager();
141 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
143 mViewPager = findViewById(R.id.root_frame);
144 mViewPager.setAdapter(mSectionsPagerAdapter);
145 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
147 public void onPageSelected(int position) {
150 markDrawerItemCurrent(R.id.nav_account_summary);
153 markDrawerItemCurrent(R.id.nav_latest_transactions);
156 Log.e("MainActivity", String.format("Unexpected page index %d", position));
159 super.onPageSelected(position);
163 Data.lastUpdateDate.addObserver((o, arg) -> {
164 Log.d("main", "lastUpdateDate changed");
165 runOnUiThread(() -> {
166 Date date = Data.lastUpdateDate.get();
168 tvLastUpdate.setText(R.string.transaction_last_update_never);
171 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
172 tvLastUpdate.setText(date.toInstant().atZone(ZoneId.systemDefault())
173 .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
176 tvLastUpdate.setText(DateFormat.getDateTimeInstance().format(date));
182 private void setupProfile() {
183 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
184 MobileLedgerProfile profile = null;
186 String profileUUID = MLDB.get_option_value(MLDB.OPT_PROFILE_UUID, null);
187 if (profileUUID == null) {
188 if (Data.profiles.isEmpty()) {
189 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
190 profile = Data.profiles.get(0);
192 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
193 Log.d("profiles", "Migrating from preferences to profiles");
194 // migration to multiple profiles
195 if (profile.getUrl().isEmpty()) {
197 Intent intent = new Intent(this, ProfileListActivity.class);
198 startActivity(intent);
200 profile.setUrl(backend.getString("backend_url", ""));
201 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
202 profile.setAuthUserName(backend.getString("backend_auth_user", null));
203 profile.setAuthPassword(backend.getString("backend_auth_password", null));
205 SharedPreferences.Editor editor = backend.edit();
211 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
214 if (profile == null) profile = Data.profiles.get(0);
216 if (profile == null) throw new AssertionError("profile must have a value");
218 Data.profile.set(profile);
219 MLDB.set_option_value(MLDB.OPT_PROFILE_UUID, profile.getUuid());
221 if (profile.getUrl().isEmpty()) {
222 Intent intent = new Intent(this, ProfileListActivity.class);
223 Bundle args = new Bundle();
224 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
225 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
226 intent.putExtras(args);
227 startActivity(intent, args);
230 public void fab_new_transaction_clicked(View view) {
231 Intent intent = new Intent(this, NewTransactionActivity.class);
232 startActivity(intent);
233 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
236 public void nav_exit_clicked(View view) {
237 Log.w("app", "exiting");
241 public void nav_settings_clicked(View view) {
242 Intent intent = new Intent(this, SettingsActivity.class);
243 startActivity(intent);
244 drawer.closeDrawers();
246 public void markDrawerItemCurrent(int id) {
247 TextView item = drawer.findViewById(id);
248 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
249 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg, getTheme()));
252 item.setBackgroundColor(getResources().getColor(R.color.table_row_even_bg));
255 setTitle(item.getText());
257 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
259 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
260 for (int i = 0; i < actions.getChildCount(); i++) {
261 View view = actions.getChildAt(i);
262 if (view.getId() != id) {
263 view.setBackgroundColor(transparent);
267 public void onViewClicked(View view) {
268 switch (view.getId()) {
269 case R.id.clearAccountNameFilter:
270 if (transactionListFragment != null)
271 transactionListFragment.onClearAccountNameClick(view);
274 Log.e("click", String.format("View %d click not handled", view.getId()));
277 public void onAccountSummaryClicked(View view) {
278 drawer.closeDrawers();
280 showAccountSummaryFragment();
282 private void showAccountSummaryFragment() {
283 mViewPager.setCurrentItem(0, true);
284 // FragmentTransaction ft = fragmentManager.beginTransaction();
285 // accountSummaryFragment = new AccountSummaryFragment();
286 // ft.replace(R.id.root_frame, accountSummaryFragment);
288 // currentFragment = accountSummaryFragment;
290 public void onLatestTransactionsClicked(View view) {
291 drawer.closeDrawers();
293 showTransactionsFragment(null);
295 private void resetFragmentBackStack() {
296 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
298 private void showTransactionsFragment(LedgerAccount account) {
299 mViewPager.setCurrentItem(1, true);
300 // FragmentTransaction ft = fragmentManager.beginTransaction();
301 // if (transactionListFragment == null) {
302 // Log.d("flow", "MainActivity creating TransactionListFragment");
303 // transactionListFragment = new TransactionListFragment();
305 // Bundle bundle = new Bundle();
306 // if (account != null) {
307 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
308 // account.getName());
310 // transactionListFragment.setArguments(bundle);
311 // ft.replace(R.id.root_frame, transactionListFragment);
312 // if (account != null)
313 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
316 // currentFragment = transactionListFragment;
318 public void showAccountTransactions(LedgerAccount account) {
319 showTransactionsFragment(account);
322 public void onBackPressed() {
323 DrawerLayout drawer = findViewById(R.id.drawer_layout);
324 if (drawer.isDrawerOpen(GravityCompat.START)) {
325 drawer.closeDrawer(GravityCompat.START);
329 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
331 super.onBackPressed();
334 public void updateLastUpdateTextFromDB() {
336 long last_update = Data.profile.get().get_option_value(MLDB.OPT_LAST_SCRAPE, 0L);
338 Log.d("transactions", String.format("Last update = %d", last_update));
339 if (last_update == 0) {
340 Data.lastUpdateDate.set(null);
343 Data.lastUpdateDate.set(new Date(last_update));
347 public void scheduleTransactionListRetrieval() {
348 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
350 retrieveTransactionsTask.execute();
351 bTransactionListCancelDownload.setEnabled(true);
353 public void onStopTransactionRefreshClick(View view) {
354 Log.d("interactive", "Cancelling transactions refresh");
355 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
356 bTransactionListCancelDownload.setEnabled(false);
358 public void onRetrieveDone(boolean success) {
359 progressLayout.setVisibility(View.GONE);
360 updateLastUpdateTextFromDB();
362 new RefreshDescriptionsTask().execute();
364 public void onRetrieveStart() {
365 progressBar.setIndeterminate(true);
366 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
367 else progressBar.setProgress(0);
368 progressLayout.setVisibility(View.VISIBLE);
370 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
371 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
372 (progress.getTotal() == 0))
374 progressBar.setIndeterminate(true);
377 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
378 progressBar.setMin(0);
380 progressBar.setMax(progress.getTotal());
381 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
382 progressBar.setProgress(progress.getProgress(), true);
384 else progressBar.setProgress(progress.getProgress());
385 progressBar.setIndeterminate(false);
388 public void nav_profiles_clicked(View view) {
389 drawer.closeDrawers();
390 Intent intent = new Intent(this, ProfileListActivity.class);
391 startActivity(intent);
393 public class SectionsPagerAdapter extends FragmentPagerAdapter {
395 public SectionsPagerAdapter(FragmentManager fm) {
400 public Fragment getItem(int position) {
401 Log.d("main", String.format("Switching to gragment %d", position));
404 return new AccountSummaryFragment();
406 return new TransactionListFragment();
408 throw new IllegalStateException(
409 String.format("Unexpected fragment index: " + "%d", position));
414 public int getCount() {