gpt4 book ai didi

php - Android使用GSON在listview中显示记录

转载 作者:行者123 更新时间:2023-11-29 13:15:25 25 4
gpt4 key购买 nike

目前我正在研究Google的GSON。我关注了this教程。它正在发挥作用。我现在想做的是在 ListView 中显示记录。所以我没有使用自定义 ListView 。

这是我迄今为止尝试过的:

private void handlePostsList(final List<Post> posts) {
this.posts = posts;

runOnUiThread(new Runnable() {
@Override
public void run() {
for(Post post : PostsActivity.this.posts) {
//Toast.makeText(PostsActivity.this, post.verse_title, Toast.LENGTH_SHORT).show();
Log.d(TAG, "" + post.verse_title);

//posts.addAll(post.verse_title);

adapter = new ArrayAdapter<Post>(PostsActivity.this,
android.R.layout.simple_list_item_1, posts);

lv.setAdapter(adapter);

}

}
});
}

private void failedLoadingPosts() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Toast.makeText(PostsActivity.this, "Failed to load Posts. Have a look at LogCat.",
Toast.LENGTH_SHORT).show();
}
});
}


private class PostFetcher extends AsyncTask<Void, Void, String> {
private static final String TAG = "PostFetcher";
public static final String SERVER_URL = "http://mlssabio.x10.mx/test/webservice-gson/test.php";
//"http://kylewbanks.com/rest/posts";

@Override
protected String doInBackground(Void... params) {
try {
//Create an HTTP client
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(SERVER_URL);

//Perform the request and check the status code
HttpResponse response = client.execute(post);
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();

try {
//Read the server response and attempt to parse it as JSON
Reader reader = new InputStreamReader(content);

GsonBuilder gsonBuilder = new GsonBuilder();
//gsonBuilder.setDateFormat("M/d/yy hh:mm a");
gson = gsonBuilder.create();
List<Post> posts = new ArrayList<Post>();
posts = Arrays.asList(gson.fromJson(reader, Post[].class));


content.close();

handlePostsList(posts);
} catch (Exception ex) {
Log.e(TAG, "Failed to parse JSON due to: " + ex);
failedLoadingPosts();
}
} else {
Log.e(TAG, "Server responded with status code: " + statusLine.getStatusCode());
failedLoadingPosts();
}
} catch(Exception ex) {
Log.e(TAG, "Failed to send HTTP POST request due to: " + ex);
failedLoadingPosts();
}
return null;
}

}

帖子类:

public class Post {

@SerializedName("id")
public long ID;
@SerializedName("verse_title")
public String verse_title;
public String verse_content;
public String lang;

public List tags;

public Post() {

}

}

但它显示的是com.r.....而不是标题。你能告诉我我哪里做错了吗?谢谢。

最佳答案

在您的 Post 类中实现 toString 并返回标题。

也没有必要

 adapter = new ArrayAdapter<Post>(PostsActivity.this, 
android.R.layout.simple_list_item_1, posts);
lv.setAdapter(adapter);

在 for 循环中

关于php - Android使用GSON在listview中显示记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21522147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com