获取网页内容(使用json数组)

时间:2013-08-26 11:59:43

标签: android http

我正在尝试获取我的网页内容(我在页面json数组中),我找不到办法来做到这一点,我在google中发现的evry代码不工作并使应用程序崩溃..

我需要帮助!

谢谢!

1 个答案:

答案 0 :(得分:1)

看看这里:

https://code.google.com/p/android-query/

这个库允许你(可以做很多事情)以一种非常简单的方式从特定的URL中获取json。我很清楚,我从来没有遇到任何问题。

我会告诉你一个例子:

Json在你的页面上

{
  "account":{
  "username":"nirbe"
  }
}

MyActivity.java

public class MyActivity extends Activity {

  private AQuery aQuery;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.my_activity);

    // First of all, create a new AQuery object
    aQuery = new AQuery(this);

    // Do your ajax call
    aQuery.ajax("http://www.nirberko.info/android/index.php", JSONObject.class, new AjaxCallback<JSONObject>() {

      @Override
      public void callback(String url, JSONObject json, AjaxStatus status) {
        if (json != null) {
          try {
            // Here you will receive your json object,
            // use it as you wish
            String username = json.getJSONObject("account").getString("username");
            // In case, you can directly update your view here
            aQuery.id(R.id.tv_name).text(username);
          } catch (JSONException e) {
            e.printStackTrace();
          }
        }
      }
    });
  }
}

my_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_name"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

</LinearLayout>