我在android 9 pie 28 API版本上测试我的应用程序时收到此错误。 它在版本8 oreo中工作。就像没有在JSONobject中获取数据一样,什么会引起问题呢?
试图在空对象引用上调用虚拟方法'int java.lang.String.length()'
private void downloadJSON(final String urlWebService) {
class DownloadJSON extends AsyncTask<Void, Void, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
// Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
DownloadJSON getJSON = new DownloadJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
String[] stocks = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
stocks[i] = obj.getString("sent_date") + "| " + obj.getString("username") + ": " + obj.getString("message");
}
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, stocks);
listView.setAdapter(arrayAdapter);
}
答案 0 :(得分:0)
这是因为您尝试访问的服务器不安全,即它使用的是HTTP(不是HTTPS)。
Android P默认使用HTTPS。这意味着,如果您在应用程序中使用未加密的HTTP请求,则该应用程序将在除Android P之外的所有Android版本中正常运行。
为避免这种安全性,请尝试对应用代码进行以下更改。
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest ... >
<application android:networkSecurityConfig="@xml/network_security_config"
... >
...
</application>
</manifest>
,然后在res / xml中添加名为network_security_config.xml
在network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config cleartextTrafficPermitted="true">
// Add host of your download URL in below line.
// ie. if url is "https://www.google.com/search?source=...."
// then just add "www.google.com"
<domain includeSubdomains="true">www.google.com</domain>
</domain-config>
</network-security-config>