我正在使用 commons-lang3-3.0.1.jar,以便利用 StrSubstitutor
类。检查一下...
以下代码是从我的 SyncAdapter 调用的,它在构建 StrSubstitutor 时崩溃了:
public static String makeGetPlansQueryString(Bundle params)
{
Map<String, String> valuesMap = new HashMap<String, String>();
valuesMap.put(REQUEST_PARAM_APIUSERNAME, API_USERNAME);
valuesMap.put(REQUEST_PARAM_APIPASSWORD, API_PASSWORD);
//... etc. etc.
String xmlTemplate = VendApplication.getContext().getString(R.string.XMLREQUEST_GET_PLANS);
StrSubstitutor subst = new StrSubstitutor(valuesMap); // <-- Crashes in here.
return subst.replace(xmlTemplate);
}
错误输出:
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): FATAL EXCEPTION: SyncAdapterThread-1
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): java.lang.ExceptionInInitializerError
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at com.conducthq.android.vend.webapi.WebAPIRequestHelper.makeGetPlansQueryString(WebAPIRequestHelper.java:68)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at com.conducthq.android.vend.webapi.WebAPIClient.createHTTPRequest(WebAPIClient.java:121)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at com.conducthq.android.vend.webapi.WebAPIClient.processRequest(WebAPIClient.java:55)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at com.conducthq.android.vend.webapi.SyncAdapter.onPerformSync(SyncAdapter.java:39)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at android.content.AbstractThreadedSyncAdapter$SyncThread.run(AbstractThreadedSyncAdapter.java:163)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): Caused by: java.lang.ExceptionInInitializerError
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at org.apache.commons.lang3.text.StrMatcher.stringMatcher(StrMatcher.java:206)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at org.apache.commons.lang3.text.StrSubstitutor.<clinit>(StrSubstitutor.java:112)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): ... 5 more
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): Caused by: java.lang.NullPointerException
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): at org.apache.commons.lang3.StringUtils.<clinit>(StringUtils.java:717)
11-02 14:36:08.439: ERROR/AndroidRuntime(9244): ... 7 more
如果我将此一行添加到我的 HomeActivity(在应用程序启动时启动),上面的代码将完美运行:
StrSubstitutor sub = new StrSubstitutor(new HashMap<String, String>());
很奇怪吧?此行如何影响在不同时间点在不同线程上运行的不同代码?那里有任何 Android 专家可以阐明这一点吗?是否有一些我不知道的奇怪的 Android JAR 加载错误? @_@
我在 LG-P350 上使用 Android 2.1 SDK。我已经使用 StrSubstitutor 上的 Apache Commons API 文档中的 super 简单示例代码重现了此行为:http://commons.apache.org/lang/api-3.0.1/org/apache/commons/lang3/text/StrSubstitutor.html
最佳答案
您的崩溃发生在 StringUtils 的静态初始值设定项中,它试图从当前线程获取上下文类加载器 - 显然是为了获取 java.text.Normalizer$Form 类。所以,是的,getContextClassLoader() 返回 null
是个奇怪的问题。
更新
显然在 this bug 中提到了错误,所以我猜你可以强行设置上下文类加载器,你应该没问题。
Thread.currentThread().setContextClassLoader(this.getClassLoader());
关于android - 在 Android 中使用 Apache Commons lib 时的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7975571/