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.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.util.Date;
56 public class MainActivity extends AppCompatActivity {
58 private FragmentManager fragmentManager;
59 private TextView tvLastUpdate;
60 private RetrieveTransactionsTask retrieveTransactionsTask;
61 private View bTransactionListCancelDownload;
62 private ProgressBar progressBar;
63 private LinearLayout progressLayout;
64 private SectionsPagerAdapter mSectionsPagerAdapter;
65 private ViewPager mViewPager;
68 protected void onStart() {
71 Data.lastUpdateDate.set(null);
72 updateLastUpdateTextFromDB();
73 Date lastUpdate = Data.lastUpdateDate.get();
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");
79 String.format("WEB data last fetched at %1.3f and now is %1.3f. re-fetching",
80 lastUpdate.getTime() / 1000f, now / 1000f));
82 scheduleTransactionListRetrieval();
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);
92 Data.profile.addObserver((o, arg) -> {
93 MobileLedgerProfile profile = Data.profile.get();
95 if (profile == null) setTitle(R.string.app_name);
96 else setTitle(profile.getName());
102 drawer = findViewById(R.id.drawer_layout);
103 ActionBarDrawerToggle toggle =
104 new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open,
105 R.string.navigation_drawer_close);
106 drawer.addDrawerListener(toggle);
109 TextView ver = drawer.findViewById(R.id.drawer_version_text);
113 getApplicationContext().getPackageManager().getPackageInfo(getPackageName(), 0);
114 ver.setText(pi.versionName);
116 catch (Exception e) {
120 tvLastUpdate = findViewById(R.id.transactions_last_update);
122 bTransactionListCancelDownload = findViewById(R.id.transaction_list_cancel_download);
123 progressBar = findViewById(R.id.transaction_list_progress_bar);
124 if (progressBar == null)
125 throw new RuntimeException("Can't get hold on the transaction value progress bar");
126 progressLayout = findViewById(R.id.transaction_progress_layout);
127 if (progressLayout == null) throw new RuntimeException(
128 "Can't get hold on the transaction value progress bar layout");
130 fragmentManager = getSupportFragmentManager();
131 mSectionsPagerAdapter = new SectionsPagerAdapter(fragmentManager);
133 mViewPager = findViewById(R.id.root_frame);
134 mViewPager.setAdapter(mSectionsPagerAdapter);
135 mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
137 public void onPageSelected(int position) {
140 markDrawerItemCurrent(R.id.nav_account_summary);
143 markDrawerItemCurrent(R.id.nav_latest_transactions);
146 Log.e("MainActivity", String.format("Unexpected page index %d", position));
149 super.onPageSelected(position);
153 Data.lastUpdateDate.addObserver((o, arg) -> {
154 Log.d("main", "lastUpdateDate changed");
155 runOnUiThread(() -> {
156 Date date = Data.lastUpdateDate.get();
158 tvLastUpdate.setText(R.string.transaction_last_update_never);
161 final String text = DateFormat.getDateTimeInstance().format(date);
162 tvLastUpdate.setText(text);
163 Log.d("despair", String.format("Date formatted: %s", text));
168 private void setupProfile() {
169 String profileUUID = MLDB.getOption(MLDB.OPT_PROFILE_UUID, null);
170 MobileLedgerProfile profile;
172 if (profileUUID == null) {
173 if (Data.profiles.isEmpty()) {
174 Data.profiles.setList(MobileLedgerProfile.createInitialProfileList());
175 profile = Data.profiles.get(0);
177 SharedPreferences backend = getSharedPreferences("backend", MODE_PRIVATE);
178 Log.d("profiles", "Migrating from preferences to profiles");
179 // migration to multiple profiles
180 if (profile.getUrl().isEmpty()) {
182 Intent intent = new Intent(this, ProfileListActivity.class);
183 startActivity(intent);
185 profile.setUrl(backend.getString("backend_url", ""));
186 profile.setAuthEnabled(backend.getBoolean("backend_use_http_auth", false));
187 profile.setAuthUserName(backend.getString("backend_auth_user", null));
188 profile.setAuthPassword(backend.getString("backend_auth_password", null));
190 SharedPreferences.Editor editor = backend.edit();
194 else profile = Data.profiles.get(0);
197 profile = MobileLedgerProfile.loadAllFromDB(profileUUID);
200 if (profile == null) profile = Data.profiles.get(0);
202 if (profile == null) throw new AssertionError("profile must have a value");
204 Data.setCurrentProfile(profile);
206 if (profile.getUrl().isEmpty()) {
207 Intent intent = new Intent(this, ProfileListActivity.class);
208 Bundle args = new Bundle();
209 args.putInt(ProfileListActivity.ARG_ACTION, ProfileListActivity.ACTION_EDIT_PROFILE);
210 args.putInt(ProfileListActivity.ARG_PROFILE_INDEX, 0);
211 intent.putExtras(args);
212 startActivity(intent, args);
215 public void fabNewTransactionClicked(View view) {
216 Intent intent = new Intent(this, NewTransactionActivity.class);
217 startActivity(intent);
218 overridePendingTransition(R.anim.slide_in_right, R.anim.dummy);
220 public void navSettingsClicked(View view) {
221 Intent intent = new Intent(this, SettingsActivity.class);
222 startActivity(intent);
223 drawer.closeDrawers();
225 public void markDrawerItemCurrent(int id) {
226 TextView item = drawer.findViewById(id);
227 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
228 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg, getTheme()));
231 item.setBackgroundColor(getResources().getColor(R.color.table_row_dark_bg));
234 @ColorInt int transparent = getResources().getColor(android.R.color.transparent);
236 LinearLayout actions = drawer.findViewById(R.id.nav_actions);
237 for (int i = 0; i < actions.getChildCount(); i++) {
238 View view = actions.getChildAt(i);
239 if (view.getId() != id) {
240 view.setBackgroundColor(transparent);
244 public void onAccountSummaryClicked(View view) {
245 drawer.closeDrawers();
247 showAccountSummaryFragment();
249 private void showAccountSummaryFragment() {
250 mViewPager.setCurrentItem(0, true);
251 TransactionListFragment.accountFilter.set(null);
252 // FragmentTransaction ft = fragmentManager.beginTransaction();
253 // accountSummaryFragment = new AccountSummaryFragment();
254 // ft.replace(R.id.root_frame, accountSummaryFragment);
256 // currentFragment = accountSummaryFragment;
258 public void onLatestTransactionsClicked(View view) {
259 drawer.closeDrawers();
261 showTransactionsFragment(null);
263 private void resetFragmentBackStack() {
264 // fragmentManager.popBackStack(0, FragmentManager.POP_BACK_STACK_INCLUSIVE);
266 private void showTransactionsFragment(LedgerAccount account) {
267 if (account != null) TransactionListFragment.accountFilter.set(account.getName());
268 mViewPager.setCurrentItem(1, true);
269 // FragmentTransaction ft = fragmentManager.beginTransaction();
270 // if (transactionListFragment == null) {
271 // Log.d("flow", "MainActivity creating TransactionListFragment");
272 // transactionListFragment = new TransactionListFragment();
274 // Bundle bundle = new Bundle();
275 // if (account != null) {
276 // bundle.putString(TransactionListFragment.BUNDLE_KEY_FILTER_ACCOUNT_NAME,
277 // account.getName());
279 // transactionListFragment.setArguments(bundle);
280 // ft.replace(R.id.root_frame, transactionListFragment);
281 // if (account != null)
282 // ft.addToBackStack(getResources().getString(R.string.title_activity_transaction_list));
285 // currentFragment = transactionListFragment;
287 public void showAccountTransactions(LedgerAccount account) {
288 showTransactionsFragment(account);
291 public void onBackPressed() {
292 DrawerLayout drawer = findViewById(R.id.drawer_layout);
293 if (drawer.isDrawerOpen(GravityCompat.START)) {
294 drawer.closeDrawer(GravityCompat.START);
298 String.format("manager stack: %d", fragmentManager.getBackStackEntryCount()));
300 super.onBackPressed();
303 public void updateLastUpdateTextFromDB() {
305 long last_update = Data.profile.get().getLongOption(MLDB.OPT_LAST_SCRAPE, 0L);
307 Log.d("transactions", String.format("Last update = %d", last_update));
308 if (last_update == 0) {
309 Data.lastUpdateDate.set(null);
312 Data.lastUpdateDate.set(new Date(last_update));
316 public void scheduleTransactionListRetrieval() {
317 retrieveTransactionsTask = new RetrieveTransactionsTask(new WeakReference<>(this));
319 retrieveTransactionsTask.execute();
320 bTransactionListCancelDownload.setEnabled(true);
322 public void onStopTransactionRefreshClick(View view) {
323 Log.d("interactive", "Cancelling transactions refresh");
324 if (retrieveTransactionsTask != null) retrieveTransactionsTask.cancel(false);
325 bTransactionListCancelDownload.setEnabled(false);
327 public void onRetrieveDone(String error) {
328 progressLayout.setVisibility(View.GONE);
331 updateLastUpdateTextFromDB();
333 new RefreshDescriptionsTask().execute();
335 else Toast.makeText(this, error, Toast.LENGTH_LONG).show();
337 public void onRetrieveStart() {
338 progressBar.setIndeterminate(true);
339 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) progressBar.setProgress(0, false);
340 else progressBar.setProgress(0);
341 progressLayout.setVisibility(View.VISIBLE);
343 public void onRetrieveProgress(RetrieveTransactionsTask.Progress progress) {
344 if ((progress.getTotal() == RetrieveTransactionsTask.Progress.INDETERMINATE) ||
345 (progress.getTotal() == 0))
347 progressBar.setIndeterminate(true);
350 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
351 progressBar.setMin(0);
353 progressBar.setMax(progress.getTotal());
354 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
355 progressBar.setProgress(progress.getProgress(), true);
357 else progressBar.setProgress(progress.getProgress());
358 progressBar.setIndeterminate(false);
361 public void navProfilesClicked(View view) {
362 drawer.closeDrawers();
363 Intent intent = new Intent(this, ProfileListActivity.class);
364 startActivity(intent);
366 public class SectionsPagerAdapter extends FragmentPagerAdapter {
368 public SectionsPagerAdapter(FragmentManager fm) {
373 public Fragment getItem(int position) {
374 Log.d("main", String.format("Switching to gragment %d", position));
377 return new AccountSummaryFragment();
379 return new TransactionListFragment();
381 throw new IllegalStateException(
382 String.format("Unexpected fragment index: " + "%d", position));
387 public int getCount() {