【问题标题】:Android JSON ListView importAndroid JSON ListView 导入
【发布时间】:2014-12-29 14:02:30
【问题描述】:

我在这里慢慢变得疯狂。

我有 NewsActivity,它从网站获取信息并将其放入列表视图,但它不起作用。

public class NewsActivity extends ListActivity {

  private ProgressDialog pDialog;

  // URL to get contacts JSON
  private static String NEWS_URL = "http://www.bandofbrothersgaming.nl/android/news.php";

  // JSON Node names
  private static final String TAG_POSTID = "sid";
  private static final String TAG_POSTSUBJECT = "title";
  private static final String TAG_POSTTEXT = "hometext";

  // contacts JSONArray
  JSONArray post_id = null;

  // Hashmap for ListView
  ArrayList < HashMap < String, String >> NewsList;

  @
  Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_news);

    NewsList = new ArrayList < HashMap < String, String >> ();

    ListView lv = getListView();

    // Listview on item click listener
    lv.setOnItemClickListener(new OnItemClickListener() {

      @
      Override
      public void onItemClick(AdapterView <? > parent, View view,
        int position, long id) {
        // getting values from selected ListItem
        String name = ((TextView) view.findViewById(R.id.post_id))
          .getText().toString();
        String cost = ((TextView) view.findViewById(R.id.post_subject))
          .getText().toString();
        String description = ((TextView) view.findViewById(R.id.post_text))
          .getText().toString();

        // Starting single contact activity
        /*  Intent in = new Intent(getApplicationContext(),
                  SingleContactActivity.class);
          in.putExtra(TAG_NAME, name);
          in.putExtra(TAG_EMAIL, cost);
          in.putExtra(TAG_PHONE_MOBILE, description);
          startActivity(in);*/

      }
    });

    // Calling async task to get json
    new GetContacts().execute();
  }

  /**
   * Async task class to get json by making HTTP call
   * */
  private class GetContacts extends AsyncTask < Void, Void, Void > {

    @
    Override
    protected void onPreExecute() {
      super.onPreExecute();
      // Showing progress dialog
      pDialog = new ProgressDialog(NewsActivity.this);
      pDialog.setMessage("Please wait...");
      pDialog.setCancelable(false);
      pDialog.show();

    }

    @
    Override
    protected Void doInBackground(Void...arg0) {
      // Creating service handler class instance
      ServiceHandler sh = new ServiceHandler();

      // Making a request to url and getting response
      String jsonStr = sh.makeServiceCall(NEWS_URL, ServiceHandler.GET);

      Log.d("Response: ", "> " + jsonStr);

      if (jsonStr != null) {
        try {
          JSONObject jsonObj = new JSONObject(jsonStr);

          // Getting JSON Array node
          post_id = jsonObj.getJSONArray(TAG_POSTID);

          // looping through All Posts
          for (int i = 0; i < post_id.length(); i++) {
            JSONObject c = post_id.getJSONObject(i);

            String postid = c.getString(TAG_POSTID);
            String postsubject = c.getString(TAG_POSTSUBJECT);
            String posttext = c.getString(TAG_POSTTEXT);


            // tmp hashmap for single contact
            HashMap < String, String > contact = new HashMap < String, String > ();

            // adding each child node to HashMap key => value
            contact.put(TAG_POSTID, postid);
            contact.put(TAG_POSTSUBJECT, postsubject);
            contact.put(TAG_POSTTEXT, posttext);

            // adding contact to contact list
            NewsList.add(contact);
          }
        } catch (JSONException e) {
          e.printStackTrace();
        }
      } else {
        Log.e("ServiceHandler", "Couldn't get any data from the url");
      }

      return null;
    }

    @
    Override
    protected void onPostExecute(Void result) {
      super.onPostExecute(result);
      // Dismiss the progress dialog
      if (pDialog.isShowing())
        pDialog.dismiss();
      /**
       * Updating parsed JSON data into ListView
       * */
      ListAdapter adapter = new SimpleAdapter(
        NewsActivity.this, NewsList,
        R.layout.list_item, new String[] {
          TAG_POSTID, TAG_POSTSUBJECT,
          TAG_POSTTEXT
        }, new int[] {
          R.id.post_id,
            R.id.post_subject, R.id.post_text
        });

      setListAdapter(adapter);
    }

  }

}

当我运行它时,LogCat 会显示以下内容:

12-29 13:56:39.698: W/System.err(1685): org.json.JSONException: Value [{"hometext":"Welcome to Nuke-Evolution.<br \/><br \/>\r\n\r\nYou must now setup an admin account.  You can do this by <a href=\"admin.php\">clicking here<\/a>.<br \/><br \/><br \/><br \/>\r\n\r\n<b>NOTE:<\/b> You can remove this by going into the News Administration or by clicking the delete button below.\r\n","sid":"1","time":"2005-07-02 10:38:28","title":"Welcome To Nuke-Evolution"},{"hometext":"<p>\n\ttest android<\/p>\n<p>\n\tandroid test<\/p>","sid":"2","time":"2014-12-28 23:21:25","title":"android test"}] of type org.json.JSONArray cannot be converted to JSONObject

有人知道我做错了什么吗?

【问题讨论】:

    标签: android json import arrays jsonobject


    【解决方案1】:

    您正在尝试将jsonStr 转换为JSONObject,但实际上是JSONArray,查看LogCat。所以首先将其转换为JSONArray,然后对其进行迭代并获取您要查找的数据。

    【讨论】:

      【解决方案2】:

      你可以使用

      JSONArray post_id = new JSONArray(jsonStr); 而不是

      JSONObject jsonObj = new JSONObject(jsonStr);
      // Getting JSON Array node
      post_id = jsonObj.getJSONArray(TAG_POSTID);
      

      因为你得到的 jsonStr 是一个 JSONArray

      【讨论】:

        【解决方案3】:

        这是您的 php 文件的响应,请检查您的代码 PHP。

        【讨论】:

          【解决方案4】:

          试试这个

              JSONArray jsonArr = new JSONArray(jsonStr);
          
                  for(int i = 0; i < jsonArr.length(); i++){
                    JSONObject item = jsonArr.getJSONObject(i);
                  String postid = item.getString(TAG_POSTID);
                              String postsubject = item.getString(TAG_POSTSUBJECT);
                              String posttext = item.getString(TAG_POSTTEXT);
          
          
                              // tmp hashmap for single contact
                              HashMap < String, String > contact = new HashMap < String, String > ();
          
                              // adding each child node to HashMap key => value
                              contact.put(TAG_POSTID, postid);
                              contact.put(TAG_POSTSUBJECT, postsubject);
                              contact.put(TAG_POSTTEXT, posttext);
          
                              // adding contact to contact list
                              NewsList.add(contact);
                 }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-08-10
            • 1970-01-01
            • 2014-03-03
            • 1970-01-01
            • 1970-01-01
            • 2015-10-30
            相关资源
            最近更新 更多