目标
我的Welcomescreen
活动是欢迎屏幕,当用户点击按钮时,它会获取Google News
并将JSON返回到DisplayMessageActivity,我想在这里显示JSON,就像精美的新闻Feed样式......
取得
到目前为止,我实现了获取JSON并使用Intent将响应移动到NewsFeed活动。现在该做什么。?
尝试:
我跟着Hooking Custom Layout to ListView,我在这里..他们的下一次会议是不同的,所以我没有跟进..
DisplayMessageActivity.java
public class DisplayMessageActivity extends ActionBarActivity {
private ListView newsListView;
//private String[] stringArray;
private ArrayAdapter newsItemArrayAdapter;
private static final String DEBUG_TAG = "HTTP";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
//newsItemArrayAdapter = new ArrayAdapter(DisplayMessageActivity.this, android.R.layout.simple_list_item_1, stringArray);
newsItemArrayAdapter = new NewsAdapter(DisplayMessageActivity.this, new String[10]);
newsListView = (ListView) findViewById(R.id.listViewId);
newsListView.setAdapter(newsItemArrayAdapter);
// Get the message from the intent
//Intent intent = getIntent();
//String message = intent.getStringExtra(WelcomescreenActivity.EXTRA_MESSAGE);
//Log.d(DEBUG_TAG, "The response is: " + message);
//setContentView(R.layout.activity_display_message);
}
NewsAdapter.java
public class NewsAdapter extends ArrayAdapter{
private LayoutInflater inflater;
public NewsAdapter(Activity activity, String[] items){
super(activity, R.layout.news_feed, items);
inflater = activity.getWindow().getLayoutInflater();
}
@Override
public View getView(int position, View convertView, ViewGroup parent){
return inflater.inflate(R.layout.news_feed, parent, false);
}
}
news_feed.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView android:id="@+id/title"
android:text="@string/news_title"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="19sp" />
</LinearLayout>
更新
搜索后我发现了这个How to parse JSON in Android答案......尝试了,它抛出..
org.json.JSONException: Unterminated string at character 500 of {"responseData": {"results":[{"G
任何想法?
答案 0 :(得分:0)
有关于此的数百个教程,但你应该尝试Gson。 您只需要创建一个包含要从Json解析的属性的类。所以用这样的课:
public class Data {
private String name;
private int age;
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
}
Json喜欢这样:
{
"name": "whatever",
"age": 21
}
你可以这样做:
public void setData(String jsonAsString) {
final Gson gson = new GsonBuilder().create();
final Data data = gson.fromJson(jsonAsString, Data.class);
//And of course access your data like this
String name = data.getName();
}
当然,您不必在课堂上拥有所有json变量。在这种情况下,仅使用变量name
它就可以工作。
但当然,最好的帮助就是学会如何自己找到答案......