我正在创建一个应用程序,用户将名称放入EditText。然后在循环中使用此文本来查看解析的JSON数据中是否存在任何匹配项。如果匹配,则匹配将添加到ArrayList。然后,该阵列列表适用于列表视图。
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
我不知道我做错了什么,但我不断收到此错误引起:java.lang.NegativeArraySizeException:-1
这是完整的代码
public class NameListActivity extends ListActivity {
private String mName;
public static final String TAG = NameListActivity.class.getSimpleName();
private JSONArray mNameArray;
private final String KEY_CONTENT = "content";
private final String KEY_CREATED_AT = "created_at";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_list);
Intent intent = getIntent();
mName = intent.getStringExtra("name");
if (networkIsON()) {
GetNameData getNameData = new GetNameData();
getNameData.execute();
} else {
}
}
private void handleJsonNameResponse() {
if (mNameArray == null) {
// TODO: handle error
} else {
try {
ArrayList<HashMap<String, String>> namePosts = new ArrayList<HashMap<String, String>>();
HashMap<String , String> namesAndCreatedHash = new HashMap<String, String>();
for (int i = 0; i < mNameArray.length(); i++) {
JSONObject namePost = mNameArray.getJSONObject(i);
String name = namePost.getString(KEY_CONTENT);
name = Html.fromHtml(name).toString();
String created = namePost.getString(KEY_CREATED_AT);
created = Html.fromHtml(created).toString();
if ( name == mName ) {
namesAndCreatedHash.put(KEY_CONTENT, name);
namesAndCreatedHash.put(KEY_CREATED_AT, created);
namePosts.add(namesAndCreatedHash);
}
}
String[] keys = { KEY_CONTENT , KEY_CREATED_AT};
int[] ids = {android.R.id.text1 , android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(NameListActivity.this , namePosts, android.R.layout.simple_list_item_2,
keys ,ids);
setListAdapter(adapter);
}catch(JSONException e){
e.printStackTrace();
}
}
}
private boolean networkIsON() {
boolean isOn = false;
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
isOn = true;
}
return isOn;
}
private class GetNameData extends AsyncTask< Object , Void , JSONArray> {
@Override
protected JSONArray doInBackground(Object... objects) {
int responseCode = -1;
JSONArray jsonResponse = null;
try {
URL nameUrl = new URL("https://fast-lowlands-9315.herokuapp.com/posts.json");
HttpURLConnection connection = (HttpURLConnection) nameUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
Log.v(TAG , "" + responseCode);
if (responseCode == 200 ) {
InputStream inputStream = connection.getInputStream();
Reader reader = new InputStreamReader(inputStream);
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
jsonResponse = new JSONArray(responseData);
} else {
Log.i(TAG , "unsuccessful HTTP response code" + responseCode);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONArray result) {
mNameArray = result;
handleJsonNameResponse();
}
}
}
这是我在logcat中得到的错误
02-08 09:38:15.190 27892-27979/com.androidy.listactivity E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.androidy.listactivity, PID: 27892
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NegativeArraySizeException: -1
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:142)
at com.androidy.listactivity.NameListActivity$GetNameData.doInBackground(NameListActivity.java:121)
答案 0 :(得分:0)
在此代码段中,
int contentLength = connection.getContentLength();
char[] charArray = new char[contentLength];
reader.read(charArray);
String responseData = new String(charArray);
你正在使用内容长度的返回值来分配一个字节数组,在你的情况下,它返回-1,导致异常。一个可能的解决方法:
StringBuilder builder = new StringBuilder();
byte[] array = new byte[8092];
int read = 0;
while ((read = inputStream.read(array)) != -1) {
builder.append(new String(array, 0, read));
}
jsonResponse = new JSONArray(builder.toString());