不确定如何处理 Android 应用程序中没有连接的情况

发布于 2024-12-16 18:23:07 字数 253 浏览 3 评论 0原文

我正在制作一个应用程序,它将 RSS Feed 解析到 SQLite 数据库中,然后读取该数据库以填充帖子列表。数据库就在那里,因此即使没有连接,用户也可以查看之前检索到的帖子。

我已将所有解析放入 try-catch 中;但是,当它捕获异常时,应用程序就会崩溃。有没有一种方法可以优雅地处理此异常,以便它只是跳到读取数据库中的内容?我研究过使用 SocketException 和 XmlPullParserException ,但这些要么会带来更多错误,要么不会影响问题。

I am making an app that parses an RSS Feed into a SQLite database which is then read from to populate a list of posts. The database is there so that even without a connection, the user can view posts that have been retrieved earlier.

I have put all the parsing into a try-catch; however, when it catches the exception, the application crashes. Is there a way to gracefully handle this exception so it just skips to reading what is in the database? I have looked into using SocketException and XmlPullParserException, but these either bring more errors or don't affect the problem.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

你对谁都笑 2024-12-23 18:23:07

抛出哪个异常?您可以在 try/catch 语句末尾添加通用异常处理程序。例如,

try {
  //...your code here
} catch (XmlPullParseException xe) {
  //log error
} catch (SocketException se) {
  //log error
} catch (Exception e) {
  //log error
}

您还可以在使用以下静态方法进行调用之前检查有效连接:

public static boolean isOnline(Context context) {
   ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnectedOrConnecting())
      return true;
   else
      return false;
}

如果您使用该调用,请确保将 : 添加

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

到您的 android 清单中

Which exception is being thrown? You could add a generic Exception handler at the end of your try/catch statement. e.g.

try {
  //...your code here
} catch (XmlPullParseException xe) {
  //log error
} catch (SocketException se) {
  //log error
} catch (Exception e) {
  //log error
}

You could also check for a valid connection before you make the call using the following static method:

public static boolean isOnline(Context context) {
   ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
   NetworkInfo netInfo = cm.getActiveNetworkInfo();
   if (netInfo != null && netInfo.isConnectedOrConnecting())
      return true;
   else
      return false;
}

Make sure you add :

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

to your android manifest if you use that call

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文