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;
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.MobileLedgerListFragment;
49 import net.ktnx.mobileledger.ui.account_summary.AccountSummaryFragment;
50 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
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 AppCompatActivity {
58 public MobileLedgerListFragment currentFragment = null;
60 private AccountSummaryFragment accountSummaryFragment;
61 private TransactionListFragment transactionListFragment;
62 private FragmentManager fragmentManager;
63 private TextView tvLastUpdate;
64 private RetrieveTransactionsTask retrieveTransactionsTask;
65 private View bTransactionListCancelDownload;
66 private ProgressBar progressBar;
67 private LinearLayout progressLayout;
68 private SectionsPagerAdapter mSectionsPagerAdapter;
69 private ViewPager mViewPager;
72 protected void onStart() {
75 Data.lastUpdateDate.set(null);
76 updateLastUpdateTextFromDB();
77 Date lastUpdate = Data.lastUpdateDate.get();
79 long now = new Date().getTime();
80 if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
81 if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
83 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
84 lastUpdate.getTime() / 1000f, now / 1000f));
86 scheduleTransactionListRetrieval();
90 protected void onCreate(Bundle savedInstanceState) {
91 super.onCreate(savedInstanceState);
92 setContentView(R.layout.activity_main);
93 Toolbar toolbar = findViewById(R.id.toolbar);
94 setSupportActionBar(toolbar);
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());
106 drawer = findViewById(R.id.drawer_layout);
107 ActionBarDrawerToggle toggle =
108 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
109 R.string.navigation_drawer_close);
110 drawer.addDrawerListener(toggle);
113 android.widget.TextView ver = drawer.findViewById(R.id.drawer_version_text);
117 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
118 ver.setText(pi.versionName);
120 catch (Exception e) {
124 tvLastUpdate = findViewById(R.id.transactions_last_update);
126 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
127 progressBar = findViewById(R.id.transaction_list_progress_bar);
128 if (progressBar == null)
129 throw new RuntimeException("Can't get hold on the transaction value progress bar");
130 progressLayout = findViewById(R.id.transaction_progress_layout);
131 if (progressLayout == null) throw new RuntimeException(
132 "Can't get hold on the transaction value progress bar layout");
134 fragmentManager = getSupportFragmentManager();
135 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
137 mViewPager = findViewById(R.id.root_frame);
138 mViewPager.setAdapter(mSectionsPagerAdapter);
139 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
141 public void onPageSelected(int position) {
144 markDrawerItemCurrent(R.id.nav_account_summary);
147 markDrawerItemCurrent(R.id.nav_latest_transactions);
150 Log.e("MainActivity", String.format("Unexpected page index %d", position));
153 super.onPageSelected(position);
157 Data.lastUpdateDate.addObserver((o, arg) -> {
158 Log.d("main", "lastUpdateDate changed");
159 runOnUiThread(() -> {
160 Date date = Data.lastUpdateDate.get();
162 tvLastUpdate.setText(R.string.transaction_last_update_never);
165 final String text = DateFormat.getDateTimeInstance().format(date);
166 tvLastUpdate.setText(text);
167 Log.d("despair", String.format("Date formatted: %s", text));
172 private void setupProfile() {
173 Data.profiles.setList(MobileLedgerProfile.loadAllFromDB());
174 MobileLedgerProfile profile = null;
176 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
177 if (profileUUID == null) {
178 if (Data.profiles.isEmpty()) {
179 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
180 profile = Data.profiles.get(0);
182 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
183 Log.d("profiles", "Migrating from preferences to profiles");
184 // migration to multiple profiles
185 if (profile.getUrl().isEmpty()) {
187 Intent intent = new Intent(this, ProfileListActivity.class);
188 startActivity(intent);
190 profile.setUrl(backend.getString("backend_url", ""));
191 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
192 profile.setAuthUserName(backend.getString("backend_auth_user", null));
193 profile.setAuthPassword(backend.getString("backend_auth_password", null));
195 SharedPreferences.Editor editor = backend.edit();
201 profile = MobileLedgerProfile.loadUUIDFromDB(profileUUID);
204 if (profile == null) profile = Data.profiles.get(0);
206 if (profile == null) throw new AssertionError("profile must have a value");
208 Data.setCurrentProfile(profile);
210 if (profile.getUrl().isEmpty()) {
211 Intent intent = new Intent(this, ProfileListActivity.class);
212 Bundle args = new Bundle();
213 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
214 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
215 intent.putExtras(args);
216 startActivity(intent, args);
219 public void fabNewTransactionClicked(View view) {
220 Intent intent = new Intent(this, NewTransactionActivity.class);
221 startActivity(intent);
222 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
225 public void navExitClicked(View view) {
226 Log.w("app", "exiting");
230 public void navSettingsClicked(View view) {
231 Intent intent = new Intent(this, SettingsActivity.class);
232 startActivity(intent);
233 drawer.closeDrawers();
235 public void markDrawerItemCurrent(int id) {
236 TextView item = drawer.findViewById(id);
237 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
238 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
241 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
244 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
246 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
247 for (int i = 0; i < actions.getChildCount(); i++) {
248 View view = actions.getChildAt(i);
249 if (view.getId() != id) {
250 view.setBackgroundColor(transparent);
254 public void onAccountSummaryClicked(View view) {
255 drawer.closeDrawers();
257 showAccountSummaryFragment();
259 private void showAccountSummaryFragment() {
260 mViewPager.setCurrentItem(0, true);
261 TransactionListFragment.accountFilter.set(null);
262 // FragmentTransaction ft = fragmentManager.beginTransaction();
263 // accountSummaryFragment = new AccountSummaryFragment();
264 // ft.replace(R.id.root_frame, accountSummaryFragment);
266 // currentFragment = accountSummaryFragment;
268 public void onLatestTransactionsClicked(View view) {
269 drawer.closeDrawers();
271 showTransactionsFragment(null);
273 private void resetFragmentBackStack() {
274 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
276 private void showTransactionsFragment(LedgerAccount account) {
277 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
278 mViewPager.setCurrentItem(1, true);
279 // FragmentTransaction ft = fragmentManager.beginTransaction();
280 // if (transactionListFragment == null) {
281 // Log.d("flow", "MainActivity creating TransactionListFragment");
282 // transactionListFragment = new TransactionListFragment();
284 // Bundle bundle = new Bundle();
285 // if (account != null) {
286 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
287 // account.getName());
289 // transactionListFragment.setArguments(bundle);
290 // ft.replace(R.id.root_frame, transactionListFragment);
291 // if (account != null)
292 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
295 // currentFragment = transactionListFragment;
297 public void showAccountTransactions(LedgerAccount account) {
298 showTransactionsFragment(account);
301 public void onBackPressed() {
302 DrawerLayout drawer = findViewById(R.id.drawer_layout);
303 if (drawer.isDrawerOpen(GravityCompat.START)) {
304 drawer.closeDrawer(GravityCompat.START);
308 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
310 super.onBackPressed();
313 public void updateLastUpdateTextFromDB() {
315 long last_update = Data.profile.get().getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
317 Log.d("transactions", String.format("Last update = %d", last_update));
318 if (last_update == 0) {
319 Data.lastUpdateDate.set(null);
322 Data.lastUpdateDate.set(new Date(last_update));
326 public void scheduleTransactionListRetrieval() {
327 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
329 retrieveTransactionsTask.execute();
330 bTransactionListCancelDownload.setEnabled(true);
332 public void onStopTransactionRefreshClick(View view) {
333 Log.d("interactive", "Cancelling transactions refresh");
334 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
335 bTransactionListCancelDownload.setEnabled(false);
337 public void onRetrieveDone(String error) {
338 progressLayout.setVisibility(View.GONE);
341 updateLastUpdateTextFromDB();
343 new RefreshDescriptionsTask().execute();
345 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
347 public void onRetrieveStart() {
348 progressBar.setIndeterminate(true);
349 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
350 else progressBar.setProgress(0);
351 progressLayout.setVisibility(View.VISIBLE);
353 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
354 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
355 (progress.getTotal() == 0))
357 progressBar.setIndeterminate(true);
360 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
361 progressBar.setMin(0);
363 progressBar.setMax(progress.getTotal());
364 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
365 progressBar.setProgress(progress.getProgress(), true);
367 else progressBar.setProgress(progress.getProgress());
368 progressBar.setIndeterminate(false);
371 public void navProfilesClicked(View view) {
372 drawer.closeDrawers();
373 Intent intent = new Intent(this, ProfileListActivity.class);
374 startActivity(intent);
376 public class SectionsPagerAdapter extends FragmentPagerAdapter {
378 public SectionsPagerAdapter(FragmentManager fm) {
383 public Fragment getItem(int position) {
384 Log.d("main", String.format("Switching to gragment %d", position));
387 return new AccountSummaryFragment();
389 return new TransactionListFragment();
391 throw new IllegalStateException(
392 String.format("Unexpected fragment index: " + "%d", position));
397 public int getCount() {