From deb789bc1bbbcc86ec10ce4c6186363fb91f46f5 Mon Sep 17 00:00:00 2001 From: Amine Date: Sat, 4 Nov 2017 11:33:22 +0100 Subject: [PATCH] Some code cleaning. --- .../bou/readerforselfoss/AddSourceActivity.kt | 91 ++++++++++--------- .../bou/readerforselfoss/HomeActivity.kt | 69 ++++++++------ .../bou/readerforselfoss/LoginActivity.kt | 34 ++++--- .../api/selfoss/SelfossApi.kt | 3 - .../api/selfoss/SelfossService.kt | 2 - .../settings/AppCompatPreferenceActivity.java | 3 +- .../settings/SettingsActivity.java | 7 +- .../bou/readerforselfoss/utils/LinksUtils.kt | 53 ++++++----- .../utils/customtabs/CustomTabsHelper.java | 2 +- app/src/main/res/values/strings.xml | 1 + 10 files changed, 150 insertions(+), 115 deletions(-) diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/AddSourceActivity.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/AddSourceActivity.kt index e12c55f..077a6fe 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/AddSourceActivity.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/AddSourceActivity.kt @@ -50,17 +50,22 @@ class AddSourceActivity : AppCompatActivity() { mustLoginToAddSource() } - val intent = intent - if (Intent.ACTION_SEND == intent.action && "text/plain" == intent.type) { - mSourceUri.setText(intent.getStringExtra(Intent.EXTRA_TEXT)) - mNameInput.setText(intent.getStringExtra(Intent.EXTRA_TITLE)) - } + maybeGetDetailsFromIntentSharing(intent, mSourceUri, mNameInput) mSaveBtn.setOnClickListener { handleSaveSource(mTags, mNameInput.text.toString(), mSourceUri.text.toString(), api!!) } + val config = Config(this) + if (config.baseUrl.isEmpty() || !config.baseUrl.isBaseUrlValid()) { + mustLoginToAddSource() + } else { + handleSpoutsSpinner(mSpoutsSpinner, api, mProgress, mForm) + } + } + + private fun handleSpoutsSpinner(mSpoutsSpinner: Spinner, api: SelfossApi?, mProgress: ProgressBar, mForm: ConstraintLayout) { val spoutsKV = HashMap() mSpoutsSpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onItemSelected(adapterView: AdapterView<*>, view: View, i: Int, l: Long) { @@ -73,48 +78,48 @@ class AddSourceActivity : AppCompatActivity() { } } - val config = Config(this) + var items: Map + api!!.spouts().enqueue(object : Callback> { + override fun onResponse(call: Call>, response: Response>) { + if (response.body() != null) { + items = response.body()!! - if (config.baseUrl.isEmpty() || !config.baseUrl.isBaseUrlValid()) { - mustLoginToAddSource() - } else { - - var items: Map - api!!.spouts().enqueue(object : Callback> { - override fun onResponse(call: Call>, response: Response>) { - if (response.body() != null) { - items = response.body()!! - - val itemsStrings = items.map { it.value.name } - for ((key, value) in items) { - spoutsKV.put(value.name, key) - } - - mProgress.visibility = View.GONE - mForm.visibility = View.VISIBLE - - val spinnerArrayAdapter = - ArrayAdapter( - this@AddSourceActivity, - android.R.layout.simple_spinner_item, - itemsStrings) - spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) - mSpoutsSpinner.adapter = spinnerArrayAdapter - - } else { - handleProblemWithSpouts() + val itemsStrings = items.map { it.value.name } + for ((key, value) in items) { + spoutsKV.put(value.name, key) } - } - override fun onFailure(call: Call>, t: Throwable) { + mProgress.visibility = View.GONE + mForm.visibility = View.VISIBLE + + val spinnerArrayAdapter = + ArrayAdapter( + this@AddSourceActivity, + android.R.layout.simple_spinner_item, + itemsStrings) + spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) + mSpoutsSpinner.adapter = spinnerArrayAdapter + + } else { handleProblemWithSpouts() } + } - private fun handleProblemWithSpouts() { - Toast.makeText(this@AddSourceActivity, R.string.cant_get_spouts, Toast.LENGTH_SHORT).show() - mProgress.visibility = View.GONE - } - }) + override fun onFailure(call: Call>, t: Throwable) { + handleProblemWithSpouts() + } + + private fun handleProblemWithSpouts() { + Toast.makeText(this@AddSourceActivity, R.string.cant_get_spouts, Toast.LENGTH_SHORT).show() + mProgress.visibility = View.GONE + } + }) + } + + private fun maybeGetDetailsFromIntentSharing(intent: Intent, mSourceUri: EditText, mNameInput: EditText) { + if (Intent.ACTION_SEND == intent.action && "text/plain" == intent.type) { + mSourceUri.setText(intent.getStringExtra(Intent.EXTRA_TEXT)) + mNameInput.setText(intent.getStringExtra(Intent.EXTRA_TITLE)) } } @@ -127,7 +132,9 @@ class AddSourceActivity : AppCompatActivity() { private fun handleSaveSource(mTags: EditText, title: String, url: String, api: SelfossApi) { - if (title.isEmpty() || url.isEmpty() || mSpoutsValue == null || mSpoutsValue!!.isEmpty()) { + val sourceDetailsAvailable = title.isEmpty() || url.isEmpty() || mSpoutsValue == null || mSpoutsValue!!.isEmpty() + + if (sourceDetailsAvailable) { Toast.makeText(this, R.string.form_not_complete, Toast.LENGTH_SHORT).show() } else { api.createSource( diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/HomeActivity.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/HomeActivity.kt index bc5443b..8c29161 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/HomeActivity.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/HomeActivity.kt @@ -62,6 +62,7 @@ import apps.amine.bou.readerforselfoss.utils.longHash import com.ashokvarma.bottomnavigation.BottomNavigationBar import com.ashokvarma.bottomnavigation.BottomNavigationItem import com.ashokvarma.bottomnavigation.TextBadgeItem +import com.crashlytics.android.Crashlytics import com.ftinc.scoop.Scoop import com.heinrichreimersoftware.androidissuereporter.IssueReporterLauncher import com.mikepenz.materialdrawer.AccountHeader @@ -172,6 +173,10 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { reloadLayoutManager() + handleSwipeRefreshLayout() + } + + private fun handleSwipeRefreshLayout() { swipeRefreshLayout.setColorSchemeResources( R.color.refresh_progress_1, R.color.refresh_progress_2, @@ -189,7 +194,7 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { override fun onMove(recyclerView: RecyclerView, viewHolder: RecyclerView.ViewHolder, - target: RecyclerView.ViewHolder): Boolean = false + target: RecyclerView.ViewHolder): Boolean = false override fun onSwiped(viewHolder: RecyclerView.ViewHolder, swipeDir: Int) { try { @@ -219,7 +224,11 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { getElementsAccordingToTab(appendResults = true) } - } catch (e: IndexOutOfBoundsException) {} + } catch (e: IndexOutOfBoundsException) { + Crashlytics.setUserIdentifier(userIdentifier) + Crashlytics.log(100, "SWIPE_INDEX_OUT_OF_BOUND", "IndexOutOfBoundsException when swiping") + Crashlytics.logException(e) + } } } @@ -578,7 +587,7 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { drawer.addItem(PrimaryDrawerItem().withName(getString(R.string.drawer_loading)).withSelectable(false)) - val resultType = object : TypeToken() {}.type + val resultType = object : TypeToken() {}.type //NOSONAR Reservoir.getAsync("drawerData", resultType, object: ReservoirGetCallback { override fun onSuccess(maybeDrawerData: DrawerData?) { handleDrawerData(maybeDrawerData, loadedFromCache = true) @@ -605,31 +614,14 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { recyclerView.setHasFixedSize(true) if (infiniteScroll) { - if (recyclerViewScrollListener == null) - recyclerViewScrollListener = object: RecyclerView.OnScrollListener() { - override fun onScrolled(localRecycler: RecyclerView?, dx: Int, dy: Int) { - if (dy > 0) { - if (localRecycler != null) { - val manager = recyclerView.layoutManager - val lastVisibleItem: Int = when (manager) { - is StaggeredGridLayoutManager -> manager.findLastCompletelyVisibleItemPositions(null).last() - is GridLayoutManager -> manager.findLastCompletelyVisibleItemPosition() - else -> 0 - } - - if (lastVisibleItem == (items.size - 1)) { - getElementsAccordingToTab(appendResults = true) - } - } - } - } - } - - recyclerView.clearOnScrollListeners() - recyclerView.addOnScrollListener(recyclerViewScrollListener) + handleInfiniteScroll() } - bottomBar.setTabSelectedListener(object: BottomNavigationBar.OnTabSelectedListener { + handleBottomBarActions(mLayoutManager) + } + + private fun handleBottomBarActions(mLayoutManager: RecyclerView.LayoutManager) { + bottomBar.setTabSelectedListener(object : BottomNavigationBar.OnTabSelectedListener { override fun onTabUnselected(position: Int) = Unit override fun onTabReselected(position: Int) = @@ -650,7 +642,7 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { } override fun onTabSelected(position: Int) = - when(position) { + when (position) { 0 -> getUnRead() 1 -> getRead() 2 -> getStarred() @@ -660,6 +652,29 @@ class HomeActivity : AppCompatActivity(), SearchView.OnQueryTextListener { }) } + private fun handleInfiniteScroll() { + if (recyclerViewScrollListener == null) + recyclerViewScrollListener = object : RecyclerView.OnScrollListener() { + override fun onScrolled(localRecycler: RecyclerView?, dx: Int, dy: Int) { + if (localRecycler != null && dy > 0) { + val manager = recyclerView.layoutManager + val lastVisibleItem: Int = when (manager) { + is StaggeredGridLayoutManager -> manager.findLastCompletelyVisibleItemPositions(null).last() + is GridLayoutManager -> manager.findLastCompletelyVisibleItemPosition() + else -> 0 + } + + if (lastVisibleItem == (items.size - 1)) { + getElementsAccordingToTab(appendResults = true) + } + } + } + } + + recyclerView.clearOnScrollListeners() + recyclerView.addOnScrollListener(recyclerViewScrollListener) + } + fun mayBeEmpty() = if (items.isEmpty()) { emptyText.visibility = View.VISIBLE diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/LoginActivity.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/LoginActivity.kt index 1054e80..94674bc 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/LoginActivity.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/LoginActivity.kt @@ -60,16 +60,7 @@ class LoginActivity : AppCompatActivity() { val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) - if (intent.getBooleanExtra("baseUrlFail", false)) { - val alertDialog = AlertDialog.Builder(this).create() - alertDialog.setTitle(getString(R.string.warning_wrong_url)) - alertDialog.setMessage(getString(R.string.base_url_error)) - alertDialog.setButton( - AlertDialog.BUTTON_NEUTRAL, - "OK", - { dialog, _ -> dialog.dismiss() }) - alertDialog.show() - } + handleBaseUrlFail() settings = getSharedPreferences(Config.settingsName, Context.MODE_PRIVATE) @@ -91,6 +82,10 @@ class LoginActivity : AppCompatActivity() { mLoginFormView = findViewById(R.id.login_form) mProgressView = findViewById(R.id.login_progress) + handleActions() + } + + private fun handleActions() { val mSwitch: Switch = findViewById(R.id.withLogin) val mHTTPSwitch: Switch = findViewById(R.id.withHttpLogin) val mLoginLayout: TextInputLayout = findViewById(R.id.loginLayout) @@ -101,7 +96,7 @@ class LoginActivity : AppCompatActivity() { val selfHostedSwitch: Switch = findViewById(R.id.withSelfhostedCert) val warningTextview: TextView = findViewById(R.id.warningText) - selfHostedSwitch.setOnCheckedChangeListener {_, b -> + selfHostedSwitch.setOnCheckedChangeListener { _, b -> isWithSelfSignedCert = !isWithSelfSignedCert val visi: Int = if (b) View.VISIBLE else View.GONE @@ -135,6 +130,19 @@ class LoginActivity : AppCompatActivity() { } } + private fun handleBaseUrlFail() { + if (intent.getBooleanExtra("baseUrlFail", false)) { + val alertDialog = AlertDialog.Builder(this).create() + alertDialog.setTitle(getString(R.string.warning_wrong_url)) + alertDialog.setMessage(getString(R.string.base_url_error)) + alertDialog.setButton( + AlertDialog.BUTTON_NEUTRAL, + "OK", + { dialog, _ -> dialog.dismiss() }) + alertDialog.show() + } + } + private fun goToMain() { val intent = Intent(this, HomeActivity::class.java) startActivity(intent) @@ -244,9 +252,7 @@ class LoginActivity : AppCompatActivity() { } } - /** - * Shows the progress UI and hides the login form. - */ + private fun showProgress(show: Boolean) { val shortAnimTime = resources.getInteger(android.R.integer.config_shortAnimTime) diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossApi.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossApi.kt index 9039ef8..051f817 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossApi.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossApi.kt @@ -24,7 +24,6 @@ import okhttp3.logging.HttpLoggingInterceptor -// codebeat:disable[ARITY,TOO_MANY_FUNCTIONS] class SelfossApi(c: Context, callingActivity: Activity, isWithSelfSignedCert: Boolean, shouldLog: Boolean) { private lateinit var service: SelfossService @@ -148,5 +147,3 @@ class SelfossApi(c: Context, callingActivity: Activity, isWithSelfSignedCert: Bo service.createSource(title, url, spout, tags, filter, userName, password) } - -// codebeat:enable[ARITY,TOO_MANY_FUNCTIONS] \ No newline at end of file diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossService.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossService.kt index dc088ff..03c4b9c 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossService.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/api/selfoss/SelfossService.kt @@ -4,7 +4,6 @@ import retrofit2.Call import retrofit2.http.* -// codebeat:disable[ARITY] internal interface SelfossService { @GET("login") @@ -98,4 +97,3 @@ internal interface SelfossService { @Query("username") username: String, @Query("password") password: String): Call } -// codebeat:disable[ARITY] \ No newline at end of file diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/settings/AppCompatPreferenceActivity.java b/app/src/main/java/apps/amine/bou/readerforselfoss/settings/AppCompatPreferenceActivity.java index 1a77cee..013d5ee 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/settings/AppCompatPreferenceActivity.java +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/settings/AppCompatPreferenceActivity.java @@ -24,7 +24,7 @@ import com.ftinc.scoop.Scoop; * A {@link PreferenceActivity} which implements and proxies the necessary calls * to be used with AppCompat. */ -public abstract class AppCompatPreferenceActivity extends PreferenceActivity { +public abstract class AppCompatPreferenceActivity extends PreferenceActivity { //NOSONAR private AppCompatDelegate mDelegate; @@ -116,6 +116,7 @@ public abstract class AppCompatPreferenceActivity extends PreferenceActivity { getDelegate().onDestroy(); } + @Override public void invalidateOptionsMenu() { getDelegate().invalidateOptionsMenu(); } diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/settings/SettingsActivity.java b/app/src/main/java/apps/amine/bou/readerforselfoss/settings/SettingsActivity.java index 555c934..61e900e 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/settings/SettingsActivity.java +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/settings/SettingsActivity.java @@ -44,7 +44,7 @@ import com.ftinc.scoop.ui.ScoopSettingsActivity; * href="http://developer.android.com/guide/topics/ui/settings.html">Settings * API Guide for more information on developing a Settings UI. */ -public class SettingsActivity extends AppCompatPreferenceActivity { +public class SettingsActivity extends AppCompatPreferenceActivity { //NOSONAR /** * A preference value change listener that updates the preference's summary * to reflect its new value. @@ -126,6 +126,7 @@ public class SettingsActivity extends AppCompatPreferenceActivity { * This method stops fragment injection in malicious applications. * Make sure to deny any unknown fragments here. */ + @Override protected boolean isValidFragment(String fragmentName) { return PreferenceFragment.class.getName().equals(fragmentName) || GeneralPreferenceFragment.class.getName().equals(fragmentName) @@ -166,7 +167,9 @@ public class SettingsActivity extends AppCompatPreferenceActivity { int input = Integer.parseInt(dest.toString() + source.toString()); if (input <= 200 && input >0) return null; - } catch (NumberFormatException nfe) { } + } catch (NumberFormatException nfe) { + Toast.makeText(getActivity(), R.string.items_number_should_be_number, Toast.LENGTH_LONG).show(); + } return ""; } } diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/utils/LinksUtils.kt b/app/src/main/java/apps/amine/bou/readerforselfoss/utils/LinksUtils.kt index 2ca0be3..996c2c9 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/utils/LinksUtils.kt +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/utils/LinksUtils.kt @@ -50,6 +50,35 @@ fun Context.buildCustomTabsIntent(): CustomTabsIntent { return intentBuilder.build() } +fun Context.openItemUrlInternally(linkDecoded: String, + customTabsIntent: CustomTabsIntent, + articleViewer: Boolean, + app: Activity) { + if (articleViewer) { + val intent = Intent(this, ReaderActivity::class.java) + + DragDismissIntentBuilder(this) + .setFullscreenOnTablets(true) // defaults to false, tablets will have padding on each side + .setDragElasticity(DragDismissIntentBuilder.DragElasticity.NORMAL) // Larger elasticities will make it easier to dismiss. + .setDrawUnderStatusBar(true) + .build(intent) + + intent.putExtra("url", linkDecoded) + app.startActivity(intent) + } else { + try { + CustomTabActivityHelper.openCustomTab(app, customTabsIntent, Uri.parse(linkDecoded) + ) { _, uri -> + val intent = Intent(Intent.ACTION_VIEW, uri) + intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK + startActivity(intent) + } + } catch (e: Exception) { + openInBrowser(linkDecoded, app) + } + } +} + fun Context.openItemUrl(linkDecoded: String, customTabsIntent: CustomTabsIntent, internalBrowser: Boolean, @@ -62,29 +91,7 @@ fun Context.openItemUrl(linkDecoded: String, if (!internalBrowser) { openInBrowser(linkDecoded, app) } else { - if (articleViewer) { - val intent = Intent(this, ReaderActivity::class.java) - - DragDismissIntentBuilder(this) - .setFullscreenOnTablets(true) // defaults to false, tablets will have padding on each side - .setDragElasticity(DragDismissIntentBuilder.DragElasticity.NORMAL) // Larger elasticities will make it easier to dismiss. - .setDrawUnderStatusBar(true) - .build(intent) - - intent.putExtra("url", linkDecoded) - app.startActivity(intent) - } else { - try { - CustomTabActivityHelper.openCustomTab(app, customTabsIntent, Uri.parse(linkDecoded) - ) { _, uri -> - val intent = Intent(Intent.ACTION_VIEW, uri) - intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK - startActivity(intent) - } - } catch (e: Exception) { - openInBrowser(linkDecoded, app) - } - } + this.openItemUrlInternally(linkDecoded, customTabsIntent, articleViewer, app) } } } diff --git a/app/src/main/java/apps/amine/bou/readerforselfoss/utils/customtabs/CustomTabsHelper.java b/app/src/main/java/apps/amine/bou/readerforselfoss/utils/customtabs/CustomTabsHelper.java index 19ac086..6aaa523 100644 --- a/app/src/main/java/apps/amine/bou/readerforselfoss/utils/customtabs/CustomTabsHelper.java +++ b/app/src/main/java/apps/amine/bou/readerforselfoss/utils/customtabs/CustomTabsHelper.java @@ -101,7 +101,7 @@ class CustomTabsHelper { List handlers = pm.queryIntentActivities( intent, PackageManager.GET_RESOLVED_FILTER); - if (handlers == null || handlers.size() == 0) { + if (handlers == null || handlers.isEmpty()) { return false; } for (ResolveInfo resolveInfo : handlers) { diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac1548e..e21a684 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -157,4 +157,5 @@ aminecmi ReaderforSelfoss Report a bug + The items number should be an integer. \ No newline at end of file