gpt4 book ai didi

java - 使用 Toast 处理 Fragment 类之外的异常

转载 作者:行者123 更新时间:2023-12-01 12:55:01 25 4
gpt4 key购买 nike

当前正在创建 Android 应用程序。我在 Fragment 类之上有一个名为 Pollen 的类,我正在这个第二个类中处理异常处理。

这是我的花粉类(class)。

public static class Pollen
{

@SuppressLint("SimpleDateFormat")
public Pollen(int zipcode, Context context)
{
this.context = context;
this.zipcode = zipcode;
Document doc;
try
{
// pass address to
doc = Jsoup.connect("http://www.wunderground.com/DisplayPollen.asp?Zipcode=" + this.zipcode).get();

// get "location" from XML
Element location = doc.select("div.columns").first();
this.location = location.text();

// get "pollen type" from XML
Element pollenType = doc.select("div.panel h3").first();
this.pollenType = pollenType.text();

SimpleDateFormat format = new SimpleDateFormat("EEE MMMM dd, yyyy");

// add the four items of pollen and dates
// to its respective list
for(int i = 0; i < 4; i++)
{
Element dates = doc.select("td.text-center.even-four").get(i);
Element levels = doc.select("td.levels").get(i);

try
{
pollenMap.put(format.parse(dates.text()), levels.text());
}
catch (ParseException e)
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
}
}
catch (IOException e)
{
Toast toast = Toast.makeText(context, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
return;
}
}
}

由于 Pollen 使用网络任务,因此它位于异步线程下,与此问题无关。

每当 Pollen 遇到异常时,尽管有 Toast,应用程序都会崩溃。

我想知道 - 处理主类之外的类的异常的可接受方法是什么?

最佳答案

您的应用程序正在崩溃,因为您正在从 UI 线程之外创建 toast。

您无法从不在主线程(UI 线程)上运行的类创建 Toast。但是您可以使用 runOnUiThread ( http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable) ) 在 Pollen 类的 UI 线程上执行代码。

YourActivity.this.runOnUiThread(new Runnable() {
public void run() {
Toast toast = Toast.makeText(YourActivity.this, R.string.toast_parse_fail, Toast.LENGTH_LONG);
toast.show();
}
});

为此,您必须将 Activity 的上下文传递给您的自定义类并使用上述方法,或者您可以抛出异常并从 Activity 中捕获它并在那里处理它。

关于java - 使用 Toast 处理 Fragment 类之外的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23975784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com