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);
224 public void navSettingsClicked(View view) {
225 Intent intent = new Intent(this, SettingsActivity.class);
226 startActivity(intent);
227 drawer.closeDrawers();
229 public void markDrawerItemCurrent(int id) {
230 TextView item = drawer.findViewById(id);
231 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
232 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
235 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
238 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
240 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
241 for (int i = 0; i < actions.getChildCount(); i++) {
242 View view = actions.getChildAt(i);
243 if (view.getId() != id) {
244 view.setBackgroundColor(transparent);
248 public void onAccountSummaryClicked(View view) {
249 drawer.closeDrawers();
251 showAccountSummaryFragment();
253 private void showAccountSummaryFragment() {
254 mViewPager.setCurrentItem(0, true);
255 TransactionListFragment.accountFilter.set(null);
256 // FragmentTransaction ft = fragmentManager.beginTransaction();
257 // accountSummaryFragment = new AccountSummaryFragment();
258 // ft.replace(R.id.root_frame, accountSummaryFragment);
260 // currentFragment = accountSummaryFragment;
262 public void onLatestTransactionsClicked(View view) {
263 drawer.closeDrawers();
265 showTransactionsFragment(null);
267 private void resetFragmentBackStack() {
268 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
270 private void showTransactionsFragment(LedgerAccount account) {
271 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
272 mViewPager.setCurrentItem(1, true);
273 // FragmentTransaction ft = fragmentManager.beginTransaction();
274 // if (transactionListFragment == null) {
275 // Log.d("flow", "MainActivity creating TransactionListFragment");
276 // transactionListFragment = new TransactionListFragment();
278 // Bundle bundle = new Bundle();
279 // if (account != null) {
280 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
281 // account.getName());
283 // transactionListFragment.setArguments(bundle);
284 // ft.replace(R.id.root_frame, transactionListFragment);
285 // if (account != null)
286 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
289 // currentFragment = transactionListFragment;
291 public void showAccountTransactions(LedgerAccount account) {
292 showTransactionsFragment(account);
295 public void onBackPressed() {
296 DrawerLayout drawer = findViewById(R.id.drawer_layout);
297 if (drawer.isDrawerOpen(GravityCompat.START)) {
298 drawer.closeDrawer(GravityCompat.START);
302 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
304 super.onBackPressed();
307 public void updateLastUpdateTextFromDB() {
309 long last_update = Data.profile.get().getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
311 Log.d("transactions", String.format("Last update = %d", last_update));
312 if (last_update == 0) {
313 Data.lastUpdateDate.set(null);
316 Data.lastUpdateDate.set(new Date(last_update));
320 public void scheduleTransactionListRetrieval() {
321 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
323 retrieveTransactionsTask.execute();
324 bTransactionListCancelDownload.setEnabled(true);
326 public void onStopTransactionRefreshClick(View view) {
327 Log.d("interactive", "Cancelling transactions refresh");
328 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
329 bTransactionListCancelDownload.setEnabled(false);
331 public void onRetrieveDone(String error) {
332 progressLayout.setVisibility(View.GONE);
335 updateLastUpdateTextFromDB();
337 new RefreshDescriptionsTask().execute();
339 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
341 public void onRetrieveStart() {
342 progressBar.setIndeterminate(true);
343 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
344 else progressBar.setProgress(0);
345 progressLayout.setVisibility(View.VISIBLE);
347 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
348 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
349 (progress.getTotal() == 0))
351 progressBar.setIndeterminate(true);
354 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
355 progressBar.setMin(0);
357 progressBar.setMax(progress.getTotal());
358 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
359 progressBar.setProgress(progress.getProgress(), true);
361 else progressBar.setProgress(progress.getProgress());
362 progressBar.setIndeterminate(false);
365 public void navProfilesClicked(View view) {
366 drawer.closeDrawers();
367 Intent intent = new Intent(this, ProfileListActivity.class);
368 startActivity(intent);
370 public class SectionsPagerAdapter extends FragmentPagerAdapter {
372 public SectionsPagerAdapter(FragmentManager fm) {
377 public Fragment getItem(int position) {
378 Log.d("main", String.format("Switching to gragment %d", position));
381 return new AccountSummaryFragment();
383 return new TransactionListFragment();
385 throw new IllegalStateException(
386 String.format("Unexpected fragment index: " + "%d", position));
391 public int getCount() {