]> git.ktnx.net Git - mobile-ledger.git/blob - app/src/main/java/net/ktnx/mobileledger/ui/activity/MainActivity.java
fix crash when profile has no value yet
[mobile-ledger.git] / app / src / main / java / net / ktnx / mobileledger / ui / activity / MainActivity.java
1 /*
2  * Copyright © 2019 Damyan Ivanov.
3  * This file is part of MoLe.
4  * MoLe 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.
8  *
9  * MoLe 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.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with MoLe. If not, see <https://www.gnu.org/licenses/>.
16  */
17
18 package net.ktnx.mobileledger.ui.activity;
19
20 import android.content.Intent;
21 import android.content.pm.PackageInfo;
22 import android.os.Build;
23 import android.os.Bundle;
24 import android.support.annotation.ColorInt;
25 import android.support.design.widget.FloatingActionButton;
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.widget.Toolbar;
34 import android.util.Log;
35 import android.view.View;
36 import android.widget.LinearLayout;
37 import android.widget.ProgressBar;
38 import android.widget.TextView;
39 import android.widget.Toast;
40
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.account_summary.AccountSummaryFragment;
48 import net.ktnx.mobileledger.ui.transaction_list.TransactionListFragment;
49 import net.ktnx.mobileledger.utils.MLDB;
50
51 import java.lang.ref.WeakReference;
52 import java.text.DateFormat;
53 import java.util.Date;
54
55 public class MainActivity extends CrashReportingActivity {
56     DrawerLayout drawer;
57     private FragmentManager fragmentManager;
58     private TextView tvLastUpdate;
59     private RetrieveTransactionsTask retrieveTransactionsTask;
60     private View bTransactionListCancelDownload;
61     private ProgressBar progressBar;
62     private LinearLayout progressLayout;
63     private SectionsPagerAdapter mSectionsPagerAdapter;
64     private ViewPager mViewPager;
65     private FloatingActionButton fab;
66
67     @Override
68     protected void onStart() {
69         super.onStart();
70
71         Data.lastUpdateDate.set(null);
72         updateLastUpdateTextFromDB();
73         Date lastUpdate = Data.lastUpdateDate.get();
74
75         long now = new Date().getTime();
76         if ((lastUpdate == null) || (now > (lastUpdate.getTime() + (24 * 3600 * 1000)))) {
77             if (lastUpdate == null) Log.d("db::", "WEB data never fetched. scheduling a fetch");
78             else Log.d("db",
79                     String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
80                             lastUpdate.getTime() / 1000f, now / 1000f));
81
82             scheduleTransactionListRetrieval();
83         }
84     }
85     @Override
86     protected void onCreate(Bundle savedInstanceState) {
87         super.onCreate(savedInstanceState);
88         setContentView(R.layout.activity_main);
89         Toolbar toolbar = findViewById(R.id.toolbar);
90         setSupportActionBar(toolbar);
91         fab = findViewById(R.id.btn_add_transaction);
92
93         Data.profile.addObserver((o, arg) -> {
94             MobileLedgerProfile profile = Data.profile.get();
95             runOnUiThread(() -> {
96                 if (profile == null) setTitle(R.string.app_name);
97                 else setTitle(profile.getName());
98                 updateLastUpdateTextFromDB();
99                 if (profile.isPostingPermitted()) {
100                     toolbar.setSubtitle(null);
101                     fab.show();
102                 }
103                 else {
104                     toolbar.setSubtitle(R.string.profile_subitlte_read_only);
105                     fab.hide();
106                 }
107             });
108         });
109
110         drawer = findViewById(R.id.drawer_layout);
111         ActionBarDrawerToggle toggle =
112                 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
113                         R.string.navigation_drawer_close);
114         drawer.addDrawerListener(toggle);
115         toggle.syncState();
116
117         TextView ver = drawer.findViewById(R.id.drawer_version_text);
118
119         try {
120             PackageInfo pi =
121                     getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
122             ver.setText(pi.versionName);
123         }
124         catch (Exception e) {
125             e.printStackTrace();
126         }
127
128         tvLastUpdate = findViewById(R.id.transactions_last_update);
129
130         bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
131         progressBar = findViewById(R.id.transaction_list_progress_bar);
132         if (progressBar == null)
133             throw new RuntimeException("Can't get hold on the transaction value progress bar");
134         progressLayout = findViewById(R.id.transaction_progress_layout);
135         if (progressLayout == null) throw new RuntimeException(
136                 "Can't get hold on the transaction value progress bar layout");
137
138         fragmentManager = getSupportFragmentManager();
139         mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
140
141         markDrawerItemCurrent(R.id.nav_account_summary);
142
143         mViewPager = findViewById(R.id.root_frame);
144         mViewPager.setAdapter(mSectionsPagerAdapter);
145         mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
146             @Override
147             public void onPageSelected(int position) {
148                 switch (position) {
149                     case 0:
150                         markDrawerItemCurrent(R.id.nav_account_summary);
151                         break;
152                     case 1:
153                         markDrawerItemCurrent(R.id.nav_latest_transactions);
154                         break;
155                     default:
156                         Log.e("MainActivity", String.format("Unexpected page index %d", position));
157                 }
158
159                 super.onPageSelected(position);
160             }
161         });
162
163         Data.lastUpdateDate.addObserver((o, arg) -> {
164             Log.d("main", "lastUpdateDate changed");
165             runOnUiThread(() -> {
166                 Date date = Data.lastUpdateDate.get();
167                 if (date == null) {
168                     tvLastUpdate.setText(R.string.transaction_last_update_never);
169                 }
170                 else {
171                     final String text = DateFormat.getDateTimeInstance().format(date);
172                     tvLastUpdate.setText(text);
173                     Log.d("despair", String.format("Date formatted: %s", text));
174                 }
175             });
176         });
177
178         findViewById(R.id.btn_no_profiles_add).setOnClickListener(v -> startAddProfileActivity());
179
180         findViewById(R.id.btn_add_transaction).setOnClickListener(this::fabNewTransactionClicked);
181     }
182     @Override
183     protected void onResume() {
184         super.onResume();
185         setupProfile();
186     }
187     private void startAddProfileActivity() {
188         Intent intent = new Intent(this, ProfileListActivity.class);
189         Bundle args = new Bundle();
190         args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
191         args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, ProfileListActivity.PROFILE_INDEX_NONE);
192         intent.putExtras(args);
193         startActivity(intent, args);
194     }
195     private void setupProfile() {
196         String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
197         MobileLedgerProfile profile;
198
199         profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
200
201         if (Data.profiles.getList().isEmpty()) {
202             findViewById(R.id.no_profiles_layout).setVisibility(View.VISIBLE);
203             findViewById(R.id.pager_layout).setVisibility(View.GONE);
204             return;
205         }
206
207         findViewById(R.id.pager_layout).setVisibility(View.VISIBLE);
208         findViewById(R.id.no_profiles_layout).setVisibility(View.GONE);
209
210         if (profile == null) profile = Data.profiles.get(0);
211
212         if (profile == null) throw new AssertionError("profile must have a value");
213
214         Data.setCurrentProfile(profile);
215     }
216     public void fabNewTransactionClicked(View view) {
217         Intent intent = new Intent(this, NewTransactionActivity.class);
218         startActivity(intent);
219         overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
220     }
221     public void navSettingsClicked(View view) {
222         Intent intent = new Intent(this, SettingsActivity.class);
223         startActivity(intent);
224         drawer.closeDrawers();
225     }
226     public void markDrawerItemCurrent(int id) {
227         TextView item = drawer.findViewById(id);
228         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
229             item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
230         }
231         else {
232             item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
233         }
234
235         @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
236
237         LinearLayout actions = drawer.findViewById(R.id.nav_actions);
238         for (int i = 0; i < actions.getChildCount(); i++) {
239             View view = actions.getChildAt(i);
240             if (view.getId() != id) {
241                 view.setBackgroundColor(transparent);
242             }
243         }
244     }
245     public void onAccountSummaryClicked(View view) {
246         drawer.closeDrawers();
247
248         showAccountSummaryFragment();
249     }
250     private void showAccountSummaryFragment() {
251         mViewPager.setCurrentItem(0, true);
252         TransactionListFragment.accountFilter.set(null);
253 //        FragmentTransaction ft = fragmentManager.beginTransaction();
254 //        accountSummaryFragment = new AccountSummaryFragment();
255 //        ft.replace(R.id.root_frame, accountSummaryFragment);
256 //        ft.commit();
257 //        currentFragment = accountSummaryFragment;
258     }
259     public void onLatestTransactionsClicked(View view) {
260         drawer.closeDrawers();
261
262         showTransactionsFragment(null);
263     }
264     private void resetFragmentBackStack() {
265 //        fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
266     }
267     private void showTransactionsFragment(LedgerAccount account) {
268         if (account != null) TransactionListFragment.accountFilter.set(account.getName());
269         mViewPager.setCurrentItem(1, true);
270 //        FragmentTransaction ft = fragmentManager.beginTransaction();
271 //        if (transactionListFragment == null) {
272 //            Log.d("flow", "MainActivity creating TransactionListFragment");
273 //            transactionListFragment = new TransactionListFragment();
274 //        }
275 //        Bundle bundle = new Bundle();
276 //        if (account != null) {
277 //            bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
278 //                    account.getName());
279 //        }
280 //        transactionListFragment.setArguments(bundle);
281 //        ft.replace(R.id.root_frame, transactionListFragment);
282 //        if (account != null)
283 //            ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
284 //        ft.commit();
285 //
286 //        currentFragment = transactionListFragment;
287     }
288     public void showAccountTransactions(LedgerAccount account) {
289         showTransactionsFragment(account);
290     }
291     @Override
292     public void onBackPressed() {
293         DrawerLayout drawer = findViewById(R.id.drawer_layout);
294         if (drawer.isDrawerOpen(GravityCompat.START)) {
295             drawer.closeDrawer(GravityCompat.START);
296         }
297         else {
298             Log.d("fragments",
299                     String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
300
301             super.onBackPressed();
302         }
303     }
304     public void updateLastUpdateTextFromDB() {
305         {
306             final MobileLedgerProfile profile = Data.profile.get();
307             long last_update =
308                     (profile != null) ? profile.getLongOption(MLDB.OPT_LAST_SCRAPE, 0L) : 0;
309
310             Log.d("transactions", String.format("Last update = %d", last_update));
311             if (last_update == 0) {
312                 Data.lastUpdateDate.set(null);
313             }
314             else {
315                 Data.lastUpdateDate.set(new Date(last_update));
316             }
317         }
318     }
319     public void scheduleTransactionListRetrieval() {
320         if (Data.profile.get() == null) return;
321
322         retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
323
324         retrieveTransactionsTask.execute();
325         bTransactionListCancelDownload.setEnabled(true);
326     }
327     public void onStopTransactionRefreshClick(View view) {
328         Log.d("interactive", "Cancelling transactions refresh");
329         if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
330         bTransactionListCancelDownload.setEnabled(false);
331     }
332     public void onRetrieveDone(String error) {
333         progressLayout.setVisibility(View.GONE);
334
335         if (error == null) {
336             updateLastUpdateTextFromDB();
337
338             new RefreshDescriptionsTask().execute();
339         }
340         else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
341     }
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);
347     }
348     public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
349         if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
350             (progress.getTotal() == 0))
351         {
352             progressBar.setIndeterminate(true);
353         }
354         else {
355             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
356                 progressBar.setMin(0);
357             }
358             progressBar.setMax(progress.getTotal());
359             if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
360                 progressBar.setProgress(progress.getProgress(), true);
361             }
362             else progressBar.setProgress(progress.getProgress());
363             progressBar.setIndeterminate(false);
364         }
365     }
366     public void navProfilesClicked(View view) {
367         drawer.closeDrawers();
368         Intent intent = new Intent(this, ProfileListActivity.class);
369         startActivity(intent);
370     }
371     public class SectionsPagerAdapter extends FragmentPagerAdapter {
372
373         public SectionsPagerAdapter(FragmentManager fm) {
374             super(fm);
375         }
376
377         @Override
378         public Fragment getItem(int position) {
379             Log.d("main", String.format("Switching to fragment %d", position));
380             switch (position) {
381                 case 0:
382                     return new AccountSummaryFragment();
383                 case 1:
384                     return new TransactionListFragment();
385                 default:
386                     throw new IllegalStateException(
387                             String.format("Unexpected fragment index: " + "%d", position));
388             }
389         }
390
391         @Override
392         public int getCount() {
393             return 2;
394         }
395     }
396     public void fabShouldShow() {
397         MobileLedgerProfile profile = Data.profile.get();
398         if ((profile != null) && profile.isPostingPermitted()) fab.show();
399     }
400 }