我只是擺弄並試圖解析來自示例url的JSON數據到我的app.After解析後我想顯示列表上的項目。我使用自定義adapter.List是顯示空的沒有數據inside.But調試顯示我從url成功獲取數據。問題在哪裏? (調試):添加此代碼(然後將其刪除),以查看哈希表對象是否被正確添加到ArrayList中。將HashMap對象添加到List中沒有問題。CustomAdapter不在列表中顯示arraylist項目
for (HashMap<String, String> map : blogPosts)
for (Map.Entry<String, String> mapEntry : map.entrySet())
{
String key = mapEntry.getKey();
String value = mapEntry.getValue();
Log.v(TAG,"Debugging2" +key);
Log.v(TAG,"Debugging2" +value);
}
這裏是main_activity:
package blogreader.com.example.android.blogreader;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
public class MainListActivity extends ListActivity {
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(isNetworkAvaliable()){
mProgressBar.setVisibility(View.VISIBLE);
GetBlogPostsTask getBlogPostsTask = new GetBlogPostsTask();
getBlogPostsTask.execute();//calls Asynchronus class's doInbackGround
}else{
Toast.makeText(this, "Network Unavailable!", Toast.LENGTH_LONG).show();
}
//Toast.makeText(this, getString(R.string.no_items), Toast.LENGTH_LONG).show();
}
private boolean isNetworkAvaliable() {
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.menu_main_list, menu);
return true;
}
private void handleBlogResponse()
{
mProgressBar.setVisibility(View.INVISIBLE);
if (mBlogData == null)
{
// TODO: handle errors
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();//check escape characters
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);//addding hashmap object to arraylist
}
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) {
Log.e(TAG, "Exception Caught", 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 dialogue=builder.create();
dialogue.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://blog.teamtreehouse.com/api/get_recent_summary/?count=" + NUMBER_OF_POSTS);
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 nextCharacter; // read() returns an int, we cast it to char later
String responseData = "";
while(true){ // Infinite loop, can only be stopped by a "break" statement
nextCharacter = reader.read(); // read() without parameters returns one character
if(nextCharacter == -1) // A return value of -1 means that we reached the end
break;
responseData += (char) nextCharacter; // The += operator appends the character to the end of the string
}
jsonResponse = new JSONObject(responseData);
String status = jsonResponse.getString("status");
Log.v(TAG, status);
JSONArray jsonPosts = jsonResponse.getJSONArray("posts");
for (int i = 0; i < jsonPosts.length(); i++)
{//just for debugging
JSONObject jsonPost = jsonPosts.getJSONObject(i);
String title = jsonPost.getString("title");
Log.v(TAG, "Post " + i + ": " + title);
}
}
else {
Log.i(TAG, "Unsuccessful HTTP Response Code: " + responseCode);
}
}
catch (MalformedURLException e) {
Log.e(TAG, "URLException caught: "+e, e);
}
catch (IOException e) {
Log.e(TAG, "IOException caught: "+e, e);
}
catch (Exception e) {
Log.e(TAG, "Exception caught: "+e, e);
}
return jsonResponse;
}
@Override
protected void onPostExecute(JSONObject result){
mBlogData=result;//This class is a bridge between AsyncTask class and Main
handleBlogResponse();
}
}
}
這裏是logcat的:
09-22 21:09:09.910 11081-11081/blogreader.com.example.android.blogreader I/art﹕ Late-enabling -Xcheck:jni
09-22 21:09:09.954 11081-11091/blogreader.com.example.android.blogreader E/art﹕ Failed sending reply to debugger: Broken pipe
09-22 21:09:09.955 11081-11091/blogreader.com.example.android.blogreader I/art﹕ Debugger is no longer active
09-22 21:09:10.067 11081-11110/blogreader.com.example.android.blogreader D/OpenGLRenderer﹕ Use EGL_SWAP_BEHAVIOR_PRESERVED: true
09-22 21:09:10.106 11081-11081/blogreader.com.example.android.blogreader D/Atlas﹕ Validating map...
09-22 21:09:10.209 11081-11110/blogreader.com.example.android.blogreader I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.016_msm8226_LA.BF.1.1.1_RB1__release_AU()
OpenGL ES Shader Compiler Version: E031.25.03.00
Build Date: 02/11/15 Wed
Local Branch:
Remote Branch: quic/LA.BF.1.1.1_rb1.10
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_LA.BF.1.1.1_RB1.05.00.02.042.016 + 62ca4eb + acd831d + 9f8b442 + e027a02 + cba30ba + 53c303a + a649d79 + 23e16f8 + 5e97da7 + cbd2a44 + 33d072a + 7aacf06 + 72b33e7 + 28f6f60 + b4c13d8 + NOTHING
09-22 21:09:10.216 11081-11110/blogreader.com.example.android.blogreader I/OpenGLRenderer﹕ Initialized EGL, version 1.4
09-22 21:09:10.302 11081-11110/blogreader.com.example.android.blogreader D/OpenGLRenderer﹕ Enabling debug mode 0
09-22 21:09:15.607 11081-11096/blogreader.com.example.android.blogreader W/art﹕ Suspending all threads took: 5.419ms
09-22 21:09:16.618 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ ok
09-22 21:09:16.618 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 0: Asset Workflow for Game Art: 3D Modeling
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 1: New Course Roundup: JavaFX, WooCommerce, Java Loops and The CSS calc() Function
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 2: Mastering Meetups for Maximum Merriment
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 3: The 10 Most Influential Figures in Web Design
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 4: Jeanne Learned Swift and Used Her Free Time to Create and Launch a Unique iPhone App
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 5: New Course Roundup: Foundations for Apps, Drupal, 3D Art with Maya LT, Future Insights Live and More
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 6: Keeping Up With Java
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 7: Ricky is a High School Senior With a Successful Freelance Web Design and Development Business
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 8: Your First Job May Not Be Your Dream Job
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 9: Ultimate Guide to User Feedback Part 2: 10 Ways to Get User Feedback
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 10: Creating Customized Shelf Buttons and Hotkeys in Maya LT
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 11: The Scrum Sniff Test
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 12: 15-Year-Old Harry Learned to Code, Gained Industry Experience and is Well on His Way to a Future in Tech
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 13: How to Use Image Effects in Unity
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 14: New Course Roundup: Functional Python, Tkinter, Ruby, WordPress and More
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 15: What Every Junior iOS Developer Needs to Know
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 16: Go Back to School With Treehouse
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 17: How to be a Resourceful Indie Game Developer
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 18: New Course Roundup: How to Make a Video Game and Express Basics
09-22 21:09:16.619 11081-11108/blogreader.com.example.android.blogreader V/MainListActivity﹕ Post 19: Learn Game Development at Treehouse!
你在使用模擬器嗎? – Aakash
您的SimpleAdapter類在哪裏 –
@Aakash我正在使用我的物理設備。模擬器太慢了。我嘗試使用GenyMotion,但我更喜歡我的設備。 – user3847870