JSON feed无法使用android

时间:2014-09-12 14:37:13

标签: php android json rss android-volley

我在这个网址上有这个网址(Feeds A),这个网址在这里(Feeds B

当我在android网址中插入 Feed B 时,它可以正常工作100%

但是当我在Android应用网址中插入 Feed A 时,它没有得到任何内容

这是我的代码

public class MainActivity extends Activity  {
    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;

    //Feeds URL - Your Website URL where you uploaded the admin panel
    private String URL_FEED = "http://apps.encly.com/?feed=all_posts";
    // Session Manager Class
    SessionManagement session;
    Button btnLoadMore;

    ProgressDialog pDialog; 
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";

    // Flag for current page
    int current_page = 1;


    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);


        //Getting feeds from the website into listview 
        listView = (ListView) findViewById(R.id.list);
        feedItems = new ArrayList<FeedItem>();
        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);


            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                                parseJsonFeed(response);
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);


    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    @SuppressWarnings("deprecation")
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("fullName"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj.getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }

    }


    ///Menus functions
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();

        switch (itemId) {
        case R.id.action_logout:
            session.logoutUser();
            break;
        case R.id.myProfile:
            Intent intent2 = new Intent(this, ProfileActivity.class);
            startActivity(intent2);
            break;
        case R.id.addPhoto:
            Intent intent1 = new Intent(this, UploadPhoto.class);
            startActivity(intent1);
            break;
        }

        // TODO Auto-generated method stub
        return super.onOptionsItemSelected(item);
    }


}

i.stack.imgur.com/VtKhy.png

Feed无法显示任何内容的图片

i.stack.imgur.com/PT1Iz.png

Feed B图像正确显示所有项目

我的Logcat

    09-12 15:21:10.730: D/Volley(2426): [1] 1.onResponse: MainActivity
09-12 15:21:10.730: W/System.err(2426): org.json.JSONException: Value at 1 is null.
09-12 15:21:10.734: W/System.err(2426):     at org.json.JSONArray.get(JSONArray.java:259)
09-12 15:21:10.734: W/System.err(2426):     at com.twaa9l.photosee.MainActivity.parseJsonFeed(MainActivity.java:151)
09-12 15:21:10.734: W/System.err(2426):     at com.twaa9l.photosee.MainActivity.access$7(MainActivity.java:146)
09-12 15:21:10.734: W/System.err(2426):     at com.twaa9l.photosee.MainActivity$1.onResponse(MainActivity.java:121)
09-12 15:21:10.734: W/System.err(2426):     at com.twaa9l.photosee.MainActivity$1.onResponse(MainActivity.java:1)
09-12 15:21:10.734: W/System.err(2426):     at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
09-12 15:21:10.734: W/System.err(2426):     at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
09-12 15:21:10.734: W/System.err(2426):     at android.os.Handler.handleCallback(Handler.java:615)
09-12 15:21:10.734: W/System.err(2426):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-12 15:21:10.734: W/System.err(2426):     at android.os.Looper.loop(Looper.java:137)
09-12 15:21:10.734: W/System.err(2426):     at android.app.ActivityThread.main(ActivityThread.java:4745)
09-12 15:21:10.734: W/System.err(2426):     at java.lang.reflect.Method.invokeNative(Native Method)
09-12 15:21:10.734: W/System.err(2426):     at java.lang.reflect.Method.invoke(Method.java:511)
09-12 15:21:10.734: W/System.err(2426):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-12 15:21:10.734: W/System.err(2426):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-12 15:21:10.734: W/System.err(2426):     at dalvik.system.NativeStart.main(Native Method)

我正在使用wordpress来获取Feed A的Feed,就像这里的php代码一样

     <?php
error_reporting(E_ALL);
 ini_set('display_errors', 1);
  $temp = $wp_query; 
  $wp_query = null; 
  $wp_query = new WP_Query();
  $wp_query->query('showposts=3&post_type=usersposts'.'&paged='.$paged); 

  echo '{ "feed": [';
  $i = 1;
  while ($wp_query->have_posts()) : $wp_query->the_post(); 
  $featured_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
   $author_id=$post->post_author;
   $ProfilePicture = get_user_meta($author_id, '_cmb_profilePic');
   $gmt_timestamp = get_the_time( 'U', $post->ID ); 
   $username = get_the_author_meta( 'user_login', $author_id );
   $firstName = get_the_author_meta( 'first_name', $author_id );
   $lastName = get_the_author_meta( 'last_name', $author_id );
  ?>

        {
            "id": <?php echo $i++; ?>,
            "name": "<?php echo $firstName." ".$lastName." - ".$username; ?>",
            "image": "<?php echo $featured_image; ?>",
            "status": "<?php echo the_title(); ?>",
            "profilePic": "<?php echo $ProfilePicture[0]; ?>",
            "timeStamp": "1403375851930",
            "url": null
        },
  <?php

  endwhile;  
  echo ']}';

  $wp_query = null; 
  $wp_query = $temp;  // Reset

  function get_avatar_url($get_avatar){
    preg_match("/src='(.*?)'/i", $get_avatar, $matches);
    return $matches[1];
  }
?>

4 个答案:

答案 0 :(得分:1)

http://apps.encly.com/?feed=all_posts似乎没有返回JSON对象。因此,您的parseJSONFeed可能无法按照您希望的方式工作。

您需要定义一个返回JSON对象的URL(一个具有文件扩展名.JSON的对象)URL_FEED = "yourURLhere.json"是JSON对象,JSONObjectRequest可以在Response.Listener()中找到JSON对象。

the documentation中,它表示JsonObjectRequest参数&#34; listener - Listener接收JSON响应&#34;。但是当您使用http://apps.encly.com/?feed=all_posts时,它不是JSON对象。它可能看起来像JSON对象,但它不是JSON对象类型。就像.doc类型的文本文件在Word中如何像.txt文件一样,但它不是一回事。 .doc嵌入了不同的格式,您根本看不到。

答案 1 :(得分:0)

您的Json格式不正确。你的JSON末尾还有一个额外的逗号

答案 2 :(得分:0)

如上所述,你的php产生无效的JSON。您只需在项目之间添加,,而不是在最后。像下面这样的东西应该解决它:

echo '{ "feed": [';
$i = 1;

while ($wp_query->have_posts()) : $wp_query->the_post();
  if( $i > 1 ) 
     echo ','; 
  $featured_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
   $author_id=$post->post_author;
   $ProfilePicture = get_user_meta($author_id, '_cmb_profilePic');
   $gmt_timestamp = get_the_time( 'U', $post->ID ); 
   $username = get_the_author_meta( 'user_login', $author_id );
   $firstName = get_the_author_meta( 'first_name', $author_id );
   $lastName = get_the_author_meta( 'last_name', $author_id );
  ?>

        {
            "id": <?php echo $i++; ?>,
            "name": "<?php echo $firstName." ".$lastName." - ".$username; ?>",
            "image": "<?php echo $featured_image; ?>",
            "status": "<?php echo the_title(); ?>",
            "profilePic": "<?php echo $ProfilePicture[0]; ?>",
            "timeStamp": "1403375851930",
            "url": null
        }
  <?php

endwhile;  
echo ']}';

请注意,我从末尾删除了逗号,只有在它不是第一项时才将其插入。

答案 3 :(得分:0)

问题是@erad said volly库没有识别JSON数据,因为它看起来像JSON数据,但它不是

所以我将这行代码添加到页面

header('Content-Type: application/json');

现在它工作正常。