我需要一些操作JSON數據的建議。我已經得出了一個絕對的結論,即我用於博客的JSON數據有問題。JSON數據不會加載到我的Android應用程序
我供給JSON數據轉換成一個機器人應用程序來顯示上的應用程序的信息。我遇到的問題是,當我使用我的JSON數據時,我得到一個 negativearysize異常。
現在你怪代碼之前,知道我得到了應用程序使用teamtreehouse博客JSON代碼來這裏做工精細的工作:
http://blog.teamtreehouse.com/api/get_recent_summary/
所以這個工作得很好。我讓我的JSON代碼看起來幾乎完全像這個代碼。該數組嵌套使用相同的,相同的命名約定...等等。
這裏是我的JSONcode帶來回來時,它在我的Android代碼插入例外。
http://www.evotechmachine.com/api/get_recent_posts/?include=title,url,status,id,date
如果你比較兩個JSON代碼,你會看到,他們幾乎就在裏面一樣。我在參考的唯一的東西是帖子,標題和網址。我相信它不是名稱不匹配。我處於全面虧損狀態。在此先感謝人。
public static final int NUMBER_OF_POSTS = 20;
public static final String TAG = MainListActivity.class.getSimpleName();
protected JSONObject mBlogData;
protected ProgressBar mProgressBar;
private final String KEY_TITLE = "title";
private final String KEY_AUTHOR = "author";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_list);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar1);
if (isNetworkAvailable()) {
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();
}
else {Toast.makeText(this, "network is unavailable", Toast.LENGTH_LONG).show();
}
// Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
JSONArray jsonPosts;
try {
jsonPosts = mBlogData.getJSONArray("posts");
JSONObject jsonPost = jsonPosts.getJSONObject(position);
String blogUrl = jsonPost.getString("url");
Intent intent = new Intent(this, BlogWebViewActivity.class);
intent.setData(Uri.parse(blogUrl));
startActivity(intent);
} catch (JSONException e) {
logException(e);
}
}
private void logException(Exception e) {
Log.e(TAG, "Exception caught!", e);
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailable = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailable = true;
}
return isAvailable;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void handleBlogResponse() {
mProgressBar.setVisibility(View.INVISIBLE);
if(mBlogData==null) {
updateDisplayForError();
}
else {
try {
JSONArray jsonPosts = mBlogData.getJSONArray("posts");
ArrayList<HashMap<String, String>> blogPosts =
new ArrayList<HashMap<String, String>>();
for (int i = 0;i< jsonPosts.length();i++) {
JSONObject post = jsonPosts.getJSONObject(i);
String title = post.getString(KEY_TITLE);
title = Html.fromHtml(title).toString();
String author = post.getString(KEY_AUTHOR);
author = Html.fromHtml(author).toString();
HashMap<String, String> blogPost = new HashMap<String, String>();
blogPost.put(KEY_TITLE, title);
blogPost.put(KEY_AUTHOR, author);
blogPosts.add(blogPost);
}
String[] keys= { KEY_TITLE, KEY_AUTHOR };
int[] ids = {android.R.id.text1, android.R.id.text2};
SimpleAdapter adapter = new SimpleAdapter(this, blogPosts, android.R.layout.simple_list_item_2, keys, ids);
setListAdapter(adapter);
} catch (JSONException e) {
logException(e);
}
}
}
private void updateDisplayForError() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.error_title));
builder.setMessage(getString(R.string.error_message));
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
TextView emptyTextView = (TextView) getListView().getEmptyView();
emptyTextView.setText(getString(R.string.no_items));
}
private class GetBlogPostsTask extends AsyncTask<Object, Void, JSONObject> {
@Override
protected JSONObject doInBackground(Object... arg0) {
int responseCode = -1;
JSONObject jsonResponse = null;
try {
URL blogFeedUrl = new URL("http://www.evotechmachine.com/api/get_recent_posts/?include=title,url,status,id,date");
HttpURLConnection connection = (HttpURLConnection) blogFeedUrl.openConnection();
connection.connect();
responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK){
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 JSONObject(responseData);
} else {
Log.i(TAG, "unsuccessful HTTP Response Code: " +responseCode);
}
Log.i(TAG, "Code: " + responseCode);
} catch (MalformedURLException e) {
logException(e);}
catch (IOException e) {
logException(e);
}
catch (Exception e) {
logException(e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result) {
mBlogData = result;
handleBlogResponse();
}
}
}
這裏的logcat的:
07-31 20:49:08.209: E/(32544): <s3dReadConfigFile:75>: Can't open file for reading
07-31 20:49:08.209: E/(32544): <s3dReadConfigFile:75>: Can't open file for reading
07-31 20:49:09.280: E/MainListActivity(32544): Exception caught!
07-31 20:49:09.280: E/MainListActivity(32544): java.lang.NegativeArraySizeException: -1
07-31 20:49:09.280: E/MainListActivity(32544): at com.nibbdigital.blogreader.MainListActivity$GetBlogPostsTask.doInBackground(MainListActivity.java:168)
07-31 20:49:09.280: E/MainListActivity(32544): at com.nibbdigital.blogreader.MainListActivity$GetBlogPostsTask.doInBackground(MainListActivity.java:1)
07-31 20:49:09.280: E/MainListActivity(32544): at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-31 20:49:09.280: E/MainListActivity(32544): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
07-31 20:49:09.280: E/MainListActivity(32544): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
07-31 20:49:09.280: E/MainListActivity(32544): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-31 20:49:09.280: E/MainListActivity(32544): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
07-31 20:49:09.280: E/MainListActivity(32544): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
07-31 20:49:09.280: E/MainListActivity(32544): at java.lang.Thread.run(Thread.java:856)
它可以幫助發佈錯誤的堆棧跟蹤和工具/你用來解析JSON的代碼。 – Androiderson
我添加了活動文件以及日誌文件(僅顯示錯誤)。可以在活動文件代碼 – Nibb
下3/4找到提要URL。我指出活動文件中的第168行是這一行char [] charArray = new char [contentLength]; – Nibb