pull/783/head
gedoor 4 years ago
parent 795623d1ff
commit 16d29aeb55
  1. 5
      app/src/main/java/io/legado/app/base/BaseDialogFragment.kt
  2. 19
      app/src/main/java/io/legado/app/data/entities/BookSource.kt
  3. 4
      app/src/main/java/io/legado/app/help/ImageLoader.kt
  4. 50
      app/src/main/java/io/legado/app/help/storage/ImportOldData.kt
  5. 10
      app/src/main/java/io/legado/app/lib/webdav/WebDav.kt
  6. 4
      app/src/main/java/io/legado/app/ui/about/AboutActivity.kt
  7. 6
      app/src/main/java/io/legado/app/ui/about/AboutFragment.kt
  8. 14
      app/src/main/java/io/legado/app/ui/book/read/TextActionMenu.kt
  9. 4
      app/src/main/java/io/legado/app/ui/book/read/page/ReadView.kt
  10. 4
      app/src/main/java/io/legado/app/ui/book/read/page/provider/ChapterProvider.kt
  11. 20
      app/src/main/java/io/legado/app/ui/filepicker/FilePicker.kt
  12. 4
      app/src/main/java/io/legado/app/ui/filepicker/entity/JavaBean.kt
  13. 20
      app/src/main/java/io/legado/app/ui/filepicker/utils/ConvertUtils.kt
  14. 6
      app/src/main/java/io/legado/app/ui/replace/ReplaceRuleActivity.kt
  15. 6
      app/src/main/java/io/legado/app/ui/rss/source/manage/RssSourceActivity.kt
  16. 8
      app/src/main/java/io/legado/app/ui/widget/font/FontAdapter.kt
  17. 7
      app/src/main/java/io/legado/app/ui/widget/text/BadgeView.kt
  18. 16
      app/src/main/java/io/legado/app/utils/StringUtils.kt
  19. 6
      app/src/main/java/io/legado/app/utils/SystemUtils.kt
  20. 8
      app/src/main/java/io/legado/app/utils/ViewExtensions.kt

@ -32,13 +32,10 @@ abstract class BaseDialogFragment : DialogFragment(), CoroutineScope {
abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?) abstract fun onFragmentCreated(view: View, savedInstanceState: Bundle?)
override fun show(manager: FragmentManager, tag: String?) { override fun show(manager: FragmentManager, tag: String?) {
try { kotlin.runCatching {
//在每个add事务前增加一个remove事务,防止连续的add //在每个add事务前增加一个remove事务,防止连续的add
manager.beginTransaction().remove(this).commit() manager.beginTransaction().remove(this).commit()
super.show(manager, tag) super.show(manager, tag)
} catch (e: Exception) {
//同一实例使用不同的tag会异常,这里捕获一下
e.printStackTrace()
} }
} }

@ -46,13 +46,14 @@ data class BookSource(
var ruleBookInfo: BookInfoRule? = null, // 书籍信息页规则 var ruleBookInfo: BookInfoRule? = null, // 书籍信息页规则
var ruleToc: TocRule? = null, // 目录页规则 var ruleToc: TocRule? = null, // 目录页规则
var ruleContent: ContentRule? = null // 正文页规则 var ruleContent: ContentRule? = null // 正文页规则
): Parcelable, JsExtensions { ) : Parcelable, JsExtensions {
override fun hashCode(): Int { override fun hashCode(): Int {
return bookSourceUrl.hashCode() return bookSourceUrl.hashCode()
} }
override fun equals(other: Any?) = if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false override fun equals(other: Any?) =
if (other is BookSource) other.bookSourceUrl == bookSourceUrl else false
@Throws(Exception::class) @Throws(Exception::class)
fun getHeaderMap() = (HashMap<String, String>().apply { fun getHeaderMap() = (HashMap<String, String>().apply {
@ -100,11 +101,11 @@ data class BookSource(
} }
fun getExploreKinds() = arrayListOf<ExploreKind>().apply { fun getExploreKinds() = arrayListOf<ExploreKind>().apply {
exploreUrl?.let { exploreUrl?.let { urlRule ->
var a = it var a = urlRule
if (a.isNotBlank()) { if (a.isNotBlank()) {
try { kotlin.runCatching {
if (it.startsWith("<js>", false)) { if (urlRule.startsWith("<js>", false)) {
val aCache = ACache.get(App.INSTANCE, "explore") val aCache = ACache.get(App.INSTANCE, "explore")
a = aCache.getAsString(bookSourceUrl) ?: "" a = aCache.getAsString(bookSourceUrl) ?: ""
if (a.isBlank()) { if (a.isBlank()) {
@ -114,7 +115,7 @@ data class BookSource(
bindings["cookie"] = CookieStore bindings["cookie"] = CookieStore
bindings["cache"] = CacheManager bindings["cache"] = CacheManager
a = AppConst.SCRIPT_ENGINE.eval( a = AppConst.SCRIPT_ENGINE.eval(
it.substring(4, it.lastIndexOf("<")), urlRule.substring(4, urlRule.lastIndexOf("<")),
bindings bindings
).toString() ).toString()
aCache.put(bookSourceUrl, a) aCache.put(bookSourceUrl, a)
@ -126,8 +127,8 @@ data class BookSource(
if (d.size > 1) if (d.size > 1)
add(ExploreKind(d[0], d[1])) add(ExploreKind(d[0], d[1]))
} }
} catch (e: Exception) { }.onFailure {
add(ExploreKind(e.localizedMessage ?: "")) add(ExploreKind(it.localizedMessage ?: ""))
} }
} }
} }

@ -22,9 +22,9 @@ object ImageLoader {
path.isNullOrEmpty() -> Glide.with(context).load(path) path.isNullOrEmpty() -> Glide.with(context).load(path)
path.isAbsUrl() -> Glide.with(context).load(AnalyzeUrl(path).getGlideUrl()) path.isAbsUrl() -> Glide.with(context).load(AnalyzeUrl(path).getGlideUrl())
path.isContentScheme() -> Glide.with(context).load(Uri.parse(path)) path.isContentScheme() -> Glide.with(context).load(Uri.parse(path))
else -> try { else -> kotlin.runCatching {
Glide.with(context).load(File(path)) Glide.with(context).load(File(path))
} catch (e: Exception) { }.getOrElse {
Glide.with(context).load(path) Glide.with(context).load(path)
} }
} }

@ -15,61 +15,61 @@ object ImportOldData {
fun importUri(context: Context, uri: Uri) { fun importUri(context: Context, uri: Uri) {
if (uri.isContentScheme()) { if (uri.isContentScheme()) {
DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach { DocumentFile.fromTreeUri(context, uri)?.listFiles()?.forEach { doc ->
when (it.name) { when (doc.name) {
"myBookShelf.json" -> "myBookShelf.json" ->
try { kotlin.runCatching {
DocumentUtils.readText(context, it.uri)?.let { json -> DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldBookshelf(json) val importCount = importOldBookshelf(json)
context.toast("成功导入书籍${importCount}") context.toast("成功导入书籍${importCount}")
} }
} catch (e: java.lang.Exception) { }.onFailure {
context.toast("导入书籍失败\n${e.localizedMessage}") context.toast("导入书籍失败\n${it.localizedMessage}")
} }
"myBookSource.json" -> "myBookSource.json" ->
try { kotlin.runCatching {
DocumentUtils.readText(context, it.uri)?.let { json -> DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldSource(json) val importCount = importOldSource(json)
context.toast("成功导入书源${importCount}") context.toast("成功导入书源${importCount}")
} }
} catch (e: Exception) { }.onFailure {
context.toast("导入源失败\n${e.localizedMessage}") context.toast("导入源失败\n${it.localizedMessage}")
} }
"myBookReplaceRule.json" -> "myBookReplaceRule.json" ->
try { kotlin.runCatching {
DocumentUtils.readText(context, it.uri)?.let { json -> DocumentUtils.readText(context, doc.uri)?.let { json ->
val importCount = importOldReplaceRule(json) val importCount = importOldReplaceRule(json)
context.toast("成功导入替换规则${importCount}") context.toast("成功导入替换规则${importCount}")
} }
} catch (e: Exception) { }.onFailure {
context.toast("导入替换规则失败\n${e.localizedMessage}") context.toast("导入替换规则失败\n${it.localizedMessage}")
} }
} }
} }
} else { } else {
uri.path?.let { uri.path?.let { path ->
val file = File(it) val file = File(path)
try {// 导入书架 kotlin.runCatching {// 导入书架
val shelfFile = val shelfFile =
FileUtils.createFileIfNotExist(file, "myBookShelf.json") FileUtils.createFileIfNotExist(file, "myBookShelf.json")
val json = shelfFile.readText() val json = shelfFile.readText()
val importCount = importOldBookshelf(json) val importCount = importOldBookshelf(json)
context.toast("成功导入书籍${importCount}") context.toast("成功导入书籍${importCount}")
} catch (e: Exception) { }.onFailure {
context.toast("导入书籍失败\n${e.localizedMessage}") context.toast("导入书籍失败\n${it.localizedMessage}")
} }
try {// Book source kotlin.runCatching {// Book source
val sourceFile = val sourceFile =
FileUtils.getFile(file, "myBookSource.json") FileUtils.getFile(file, "myBookSource.json")
val json = sourceFile.readText() val json = sourceFile.readText()
val importCount = importOldSource(json) val importCount = importOldSource(json)
context.toast("成功导入书源${importCount}") context.toast("成功导入书源${importCount}")
} catch (e: Exception) { }.onFailure {
context.toast("导入源失败\n${e.localizedMessage}") context.toast("导入源失败\n${it.localizedMessage}")
} }
try {// Replace rules kotlin.runCatching {// Replace rules
val ruleFile = FileUtils.getFile(file, "myBookReplaceRule.json") val ruleFile = FileUtils.getFile(file, "myBookReplaceRule.json")
if (ruleFile.exists()) { if (ruleFile.exists()) {
val json = ruleFile.readText() val json = ruleFile.readText()
@ -78,8 +78,8 @@ object ImportOldData {
} else { } else {
context.toast("未找到替换规则") context.toast("未找到替换规则")
} }
} catch (e: Exception) { }.onFailure {
context.toast("导入替换规则失败\n${e.localizedMessage}") context.toast("导入替换规则失败\n${it.localizedMessage}")
} }
} }
} }

@ -12,7 +12,6 @@ import rxhttp.wrapper.param.toInputStream
import java.io.File import java.io.File
import java.io.IOException import java.io.IOException
import java.io.InputStream import java.io.InputStream
import java.io.UnsupportedEncodingException
import java.net.MalformedURLException import java.net.MalformedURLException
import java.net.URL import java.net.URL
import java.net.URLEncoder import java.net.URLEncoder
@ -39,15 +38,12 @@ class WebDav(urlStr: String) {
private val url: URL = URL(urlStr) private val url: URL = URL(urlStr)
private val httpUrl: String? by lazy { private val httpUrl: String? by lazy {
val raw = url.toString().replace("davs://", "https://").replace("dav://", "http://") val raw = url.toString().replace("davs://", "https://").replace("dav://", "http://")
try { return@lazy kotlin.runCatching {
return@lazy URLEncoder.encode(raw, "UTF-8") URLEncoder.encode(raw, "UTF-8")
.replace("\\+".toRegex(), "%20") .replace("\\+".toRegex(), "%20")
.replace("%3A".toRegex(), ":") .replace("%3A".toRegex(), ":")
.replace("%2F".toRegex(), "/") .replace("%2F".toRegex(), "/")
} catch (e: UnsupportedEncodingException) { }.getOrNull()
e.printStackTrace()
return@lazy null
}
} }
val host: String? get() = url.host val host: String? get() = url.host
val path get() = url.toString() val path get() = url.toString()

@ -30,7 +30,7 @@ class AboutActivity : BaseActivity<ActivityAboutBinding>() {
.replace(R.id.fl_fragment, aboutFragment, fTag) .replace(R.id.fl_fragment, aboutFragment, fTag)
.commit() .commit()
binding.tvAppSummary.post { binding.tvAppSummary.post {
try { kotlin.runCatching {
val span = ForegroundColorSpan(accentColor) val span = ForegroundColorSpan(accentColor)
val spannableString = SpannableString(binding.tvAppSummary.text) val spannableString = SpannableString(binding.tvAppSummary.text)
val gzh = getString(R.string.legado_gzh) val gzh = getString(R.string.legado_gzh)
@ -40,8 +40,6 @@ class AboutActivity : BaseActivity<ActivityAboutBinding>() {
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE Spannable.SPAN_EXCLUSIVE_EXCLUSIVE
) )
binding.tvAppSummary.text = spannableString binding.tvAppSummary.text = spannableString
} catch (e: Exception) {
e.printStackTrace()
} }
} }
} }

@ -93,12 +93,10 @@ class AboutFragment : PreferenceFragmentCompat() {
Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key") Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26k%3D$key")
// 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面 // 此Flag可根据具体产品需要自定义,如设置,则在加群界面按返回,返回手Q主界面,不设置,按返回会返回到呼起产品界面
// intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) // intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return try { return kotlin.runCatching {
startActivity(intent) startActivity(intent)
true true
} catch (e: java.lang.Exception) { }.getOrDefault(false)
false
}
} }
} }

@ -130,7 +130,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
readAloud(callBack.selectedText) readAloud(callBack.selectedText)
} }
R.id.menu_browser -> { R.id.menu_browser -> {
try { kotlin.runCatching {
val intent = if (callBack.selectedText.isAbsUrl()) { val intent = if (callBack.selectedText.isAbsUrl()) {
Intent(Intent.ACTION_VIEW).apply { Intent(Intent.ACTION_VIEW).apply {
data = Uri.parse(callBack.selectedText) data = Uri.parse(callBack.selectedText)
@ -141,9 +141,9 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
} }
} }
context.startActivity(intent) context.startActivity(intent)
} catch (e: Exception) { }.onFailure {
e.printStackTrace() it.printStackTrace()
context.toast(e.localizedMessage ?: "ERROR") context.toast(it.localizedMessage ?: "ERROR")
} }
} }
else -> item.intent?.let { else -> item.intent?.let {
@ -210,7 +210,7 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
*/ */
@RequiresApi(Build.VERSION_CODES.M) @RequiresApi(Build.VERSION_CODES.M)
private fun onInitializeMenu(menu: Menu) { private fun onInitializeMenu(menu: Menu) {
try { kotlin.runCatching {
var menuItemOrder = 100 var menuItemOrder = 100
for (resolveInfo in getSupportedActivities()) { for (resolveInfo in getSupportedActivities()) {
menu.add( menu.add(
@ -218,8 +218,8 @@ class TextActionMenu(private val context: Context, private val callBack: CallBac
menuItemOrder++, resolveInfo.loadLabel(context.packageManager) menuItemOrder++, resolveInfo.loadLabel(context.packageManager)
).intent = createProcessTextIntentForResolveInfo(resolveInfo) ).intent = createProcessTextIntentForResolveInfo(resolveInfo)
} }
} catch (e: Exception) { }.onFailure {
context.toast("获取文字操作菜单出错:${e.localizedMessage}") context.toast("获取文字操作菜单出错:${it.localizedMessage}")
} }
} }

@ -338,10 +338,10 @@ class ReadView(context: Context, attrs: AttributeSet) :
} }
end -= 1 end -= 1
} }
try { kotlin.runCatching {
curPage.selectStartMoveIndex(firstRelativePage, lineStart, start) curPage.selectStartMoveIndex(firstRelativePage, lineStart, start)
curPage.selectEndMoveIndex(firstRelativePage, lineEnd, end) curPage.selectEndMoveIndex(firstRelativePage, lineEnd, end)
} catch (e: Exception) { }.onFailure {
print( print(
""" """
curPage.selectStartMoveIndex($firstRelativePage, $lineStart, $start) curPage.selectStartMoveIndex($firstRelativePage, $lineStart, $start)

@ -352,7 +352,7 @@ object ChapterProvider {
} }
private fun getTypeface(fontPath: String): Typeface { private fun getTypeface(fontPath: String): Typeface {
return try { return kotlin.runCatching {
when { when {
fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> { fontPath.isContentScheme() && Build.VERSION.SDK_INT >= Build.VERSION_CODES.O -> {
val fd = App.INSTANCE.contentResolver val fd = App.INSTANCE.contentResolver
@ -370,7 +370,7 @@ object ChapterProvider {
else -> Typeface.SANS_SERIF else -> Typeface.SANS_SERIF
} }
} }
} catch (e: Exception) { }.getOrElse {
ReadBookConfig.textFont = "" ReadBookConfig.textFont = ""
ReadBookConfig.save() ReadBookConfig.save()
Typeface.SANS_SERIF Typeface.SANS_SERIF

@ -30,11 +30,10 @@ object FilePicker {
items(selectList) { _, index -> items(selectList) { _, index ->
when (index) { when (index) {
0 -> { 0 -> {
try { kotlin.runCatching {
val intent = createSelectDirIntent() val intent = createSelectDirIntent()
activity.startActivityForResult(intent, requestCode) activity.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) { }.onFailure {
e.printStackTrace()
checkPermissions(activity) { checkPermissions(activity) {
FilePickerDialog.show( FilePickerDialog.show(
activity.supportFragmentManager, activity.supportFragmentManager,
@ -81,11 +80,10 @@ object FilePicker {
items(selectList) { _, index -> items(selectList) { _, index ->
when (index) { when (index) {
0 -> { 0 -> {
try { kotlin.runCatching {
val intent = createSelectDirIntent() val intent = createSelectDirIntent()
fragment.startActivityForResult(intent, requestCode) fragment.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) { }.onFailure {
e.printStackTrace()
checkPermissions(fragment) { checkPermissions(fragment) {
FilePickerDialog.show( FilePickerDialog.show(
fragment.childFragmentManager, fragment.childFragmentManager,
@ -133,15 +131,14 @@ object FilePicker {
items(selectList) { _, index -> items(selectList) { _, index ->
when (index) { when (index) {
0 -> { 0 -> {
try { kotlin.runCatching {
val intent = createSelectFileIntent() val intent = createSelectFileIntent()
intent.putExtra( intent.putExtra(
Intent.EXTRA_MIME_TYPES, Intent.EXTRA_MIME_TYPES,
typesOfExtensions(allowExtensions) typesOfExtensions(allowExtensions)
) )
activity.startActivityForResult(intent, requestCode) activity.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) { }.onFailure {
e.printStackTrace()
checkPermissions(activity) { checkPermissions(activity) {
FilePickerDialog.show( FilePickerDialog.show(
activity.supportFragmentManager, activity.supportFragmentManager,
@ -191,15 +188,14 @@ object FilePicker {
items(selectList) { _, index -> items(selectList) { _, index ->
when (index) { when (index) {
0 -> { 0 -> {
try { kotlin.runCatching {
val intent = createSelectFileIntent() val intent = createSelectFileIntent()
intent.putExtra( intent.putExtra(
Intent.EXTRA_MIME_TYPES, Intent.EXTRA_MIME_TYPES,
typesOfExtensions(allowExtensions) typesOfExtensions(allowExtensions)
) )
fragment.startActivityForResult(intent, requestCode) fragment.startActivityForResult(intent, requestCode)
} catch (e: java.lang.Exception) { }.onFailure {
e.printStackTrace()
checkPermissions(fragment) { checkPermissions(fragment) {
FilePickerDialog.show( FilePickerDialog.show(
fragment.childFragmentManager, fragment.childFragmentManager,

@ -34,15 +34,13 @@ open class JavaBean : Serializable {
val fields = list.toTypedArray() val fields = list.toTypedArray()
for (field in fields) { for (field in fields) {
val fieldName = field.name val fieldName = field.name
try { kotlin.runCatching {
val obj = field.get(this) val obj = field.get(this)
sb.append(fieldName) sb.append(fieldName)
sb.append("=") sb.append("=")
sb.append(obj) sb.append(obj)
sb.append("\n") sb.append("\n")
} catch (ignored: IllegalAccessException) {
} }
} }
return sb.toString() return sb.toString()
} }

@ -6,7 +6,6 @@ import android.graphics.BitmapFactory
import android.graphics.drawable.BitmapDrawable import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable import android.graphics.drawable.Drawable
import java.io.BufferedReader import java.io.BufferedReader
import java.io.IOException
import java.io.InputStream import java.io.InputStream
import java.io.InputStreamReader import java.io.InputStreamReader
import java.text.DecimalFormat import java.text.DecimalFormat
@ -24,11 +23,9 @@ object ConvertUtils {
const val KB: Long = 1024 const val KB: Long = 1024
fun toInt(obj: Any): Int { fun toInt(obj: Any): Int {
return try { return kotlin.runCatching {
Integer.parseInt(obj.toString()) Integer.parseInt(obj.toString())
} catch (e: NumberFormatException) { }.getOrDefault(-1)
-1
}
} }
fun toInt(bytes: ByteArray): Int { fun toInt(bytes: ByteArray): Int {
@ -42,11 +39,9 @@ object ConvertUtils {
} }
fun toFloat(obj: Any): Float { fun toFloat(obj: Any): Float {
return try { return kotlin.runCatching {
java.lang.Float.parseFloat(obj.toString()) java.lang.Float.parseFloat(obj.toString())
} catch (e: NumberFormatException) { }.getOrDefault(-1f)
-1f
}
} }
fun toString(objects: Array<Any>, tag: String): String { fun toString(objects: Array<Any>, tag: String): String {
@ -62,7 +57,7 @@ object ConvertUtils {
fun toBitmap(bytes: ByteArray, width: Int = -1, height: Int = -1): Bitmap? { fun toBitmap(bytes: ByteArray, width: Int = -1, height: Int = -1): Bitmap? {
var bitmap: Bitmap? = null var bitmap: Bitmap? = null
if (bytes.isNotEmpty()) { if (bytes.isNotEmpty()) {
try { kotlin.runCatching {
val options = BitmapFactory.Options() val options = BitmapFactory.Options()
// 设置让解码器以最佳方式解码 // 设置让解码器以最佳方式解码
options.inPreferredConfig = null options.inPreferredConfig = null
@ -72,7 +67,6 @@ object ConvertUtils {
} }
bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options) bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, options)
bitmap!!.density = 96// 96 dpi bitmap!!.density = 96// 96 dpi
} catch (e: Exception) {
} }
} }
return bitmap return bitmap
@ -101,7 +95,7 @@ object ConvertUtils {
@JvmOverloads @JvmOverloads
fun toString(`is`: InputStream, charset: String = "utf-8"): String { fun toString(`is`: InputStream, charset: String = "utf-8"): String {
val sb = StringBuilder() val sb = StringBuilder()
try { kotlin.runCatching {
val reader = BufferedReader(InputStreamReader(`is`, charset)) val reader = BufferedReader(InputStreamReader(`is`, charset))
while (true) { while (true) {
val line = reader.readLine() val line = reader.readLine()
@ -113,9 +107,7 @@ object ConvertUtils {
} }
reader.close() reader.close()
`is`.close() `is`.close()
} catch (e: IOException) {
} }
return sb.toString() return sb.toString()
} }

@ -246,13 +246,13 @@ class ReplaceRuleActivity : VMBaseActivity<ActivityReplaceRuleBinding, ReplaceRu
when (requestCode) { when (requestCode) {
importRequestCode -> if (resultCode == Activity.RESULT_OK) { importRequestCode -> if (resultCode == Activity.RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
try { kotlin.runCatching {
uri.readText(this)?.let { uri.readText(this)?.let {
val dataKey = IntentDataHelp.putData(it) val dataKey = IntentDataHelp.putData(it)
startActivity<ImportReplaceRuleActivity>("dataKey" to dataKey) startActivity<ImportReplaceRuleActivity>("dataKey" to dataKey)
} }
} catch (e: Exception) { }.onFailure {
toast("readTextError:${e.localizedMessage}") toast("readTextError:${it.localizedMessage}")
} }
} }
} }

@ -257,13 +257,13 @@ class RssSourceActivity : VMBaseActivity<ActivityRssSourceBinding, RssSourceView
when (requestCode) { when (requestCode) {
importRequestCode -> if (resultCode == Activity.RESULT_OK) { importRequestCode -> if (resultCode == Activity.RESULT_OK) {
data?.data?.let { uri -> data?.data?.let { uri ->
try { kotlin.runCatching {
uri.readText(this)?.let { uri.readText(this)?.let {
val dataKey = IntentDataHelp.putData(it) val dataKey = IntentDataHelp.putData(it)
startActivity<ImportRssSourceActivity>("dataKey" to dataKey) startActivity<ImportRssSourceActivity>("dataKey" to dataKey)
} }
} catch (e: Exception) { }.onFailure {
toast("readTextError:${e.localizedMessage}") toast("readTextError:${it.localizedMessage}")
} }
} }
} }

@ -29,7 +29,7 @@ class FontAdapter(context: Context, val callBack: CallBack) :
payloads: MutableList<Any> payloads: MutableList<Any>
) { ) {
with(binding) { with(binding) {
try { kotlin.runCatching {
val typeface: Typeface? = if (item.isContentPath) { val typeface: Typeface? = if (item.isContentPath) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.contentResolver context.contentResolver
@ -44,9 +44,9 @@ class FontAdapter(context: Context, val callBack: CallBack) :
Typeface.createFromFile(item.uri.toString()) Typeface.createFromFile(item.uri.toString())
} }
tvFont.typeface = typeface tvFont.typeface = typeface
} catch (e: Exception) { }.onFailure {
e.printStackTrace() it.printStackTrace()
context.toast("Read ${item.name} Error: ${e.localizedMessage}") context.toast("Read ${item.name} Error: ${it.localizedMessage}")
} }
tvFont.text = item.name tvFont.text = item.name
root.onClick { callBack.onClick(item) } root.onClick { callBack.onClick(item) }

@ -43,12 +43,9 @@ class BadgeView @JvmOverloads constructor(
return null return null
} }
val text = text.toString() val text = text.toString()
return try { return kotlin.runCatching {
Integer.parseInt(text) Integer.parseInt(text)
} catch (e: NumberFormatException) { }.getOrNull()
null
}
} }
var badgeGravity: Int var badgeGravity: Int

@ -3,7 +3,6 @@ package io.legado.app.utils
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.text.TextUtils.isEmpty import android.text.TextUtils.isEmpty
import java.text.DecimalFormat import java.text.DecimalFormat
import java.text.ParseException
import java.text.SimpleDateFormat import java.text.SimpleDateFormat
import java.util.* import java.util.*
import java.util.regex.Matcher import java.util.regex.Matcher
@ -56,7 +55,7 @@ object StringUtils {
@SuppressLint("SimpleDateFormat") @SuppressLint("SimpleDateFormat")
val format = SimpleDateFormat(pattern) val format = SimpleDateFormat(pattern)
val calendar = Calendar.getInstance() val calendar = Calendar.getInstance()
try { kotlin.runCatching {
val date = format.parse(source) ?: return "" val date = format.parse(source) ?: return ""
val curTime = calendar.timeInMillis val curTime = calendar.timeInMillis
calendar.time = date calendar.time = date
@ -95,8 +94,8 @@ object StringUtils {
convertFormat.format(date) convertFormat.format(date)
} }
} }
} catch (e: ParseException) { }.onFailure {
e.printStackTrace() it.printStackTrace()
} }
return "" return ""
@ -173,7 +172,7 @@ object StringUtils {
} }
// "一千零二十五", "一千二" 形式 // "一千零二十五", "一千二" 形式
try { return kotlin.runCatching {
for (i in cn.indices) { for (i in cn.indices) {
val tmpNum = ChnMap[cn[i]]!! val tmpNum = ChnMap[cn[i]]!!
when { when {
@ -204,11 +203,8 @@ object StringUtils {
} }
} }
result += tmp + billion result += tmp + billion
return result result
} catch (e: Exception) { }.getOrDefault(-1)
return -1
}
} }
fun stringToInt(str: String?): Int { fun stringToInt(str: String?): Int {

@ -19,13 +19,13 @@ object SystemUtils {
fun getScreenOffTime(context: Context): Int { fun getScreenOffTime(context: Context): Int {
var screenOffTime = 0 var screenOffTime = 0
try { kotlin.runCatching {
screenOffTime = Settings.System.getInt( screenOffTime = Settings.System.getInt(
context.contentResolver, context.contentResolver,
Settings.System.SCREEN_OFF_TIMEOUT Settings.System.SCREEN_OFF_TIMEOUT
) )
} catch (e: Exception) { }.onFailure {
e.printStackTrace() it.printStackTrace()
} }
return screenOffTime return screenOffTime

@ -107,13 +107,11 @@ fun RadioGroup.checkByIndex(index: Int) {
@SuppressLint("RestrictedApi") @SuppressLint("RestrictedApi")
fun PopupMenu.show(x: Int, y: Int) { fun PopupMenu.show(x: Int, y: Int) {
try { kotlin.runCatching {
val field: Field = this.javaClass.getDeclaredField("mPopup") val field: Field = this.javaClass.getDeclaredField("mPopup")
field.isAccessible = true field.isAccessible = true
(field.get(this) as MenuPopupHelper).show(x, y) (field.get(this) as MenuPopupHelper).show(x, y)
} catch (e: NoSuchFieldException) { }.onFailure {
e.printStackTrace() it.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} }
} }
Loading…
Cancel
Save