Youssef Al Subaihi
Youssef Al Subaihi

Reputation: 136

JSON feed not working correctly with android

I have this feed on this URL here ( Feeds A ) and this feeds here ( Feeds B )

when I insert Feeds B in android URL it works fine 100%

but when I insert Feeds A in android app URL it's not getting anything

here is my Code

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);
    }
    
    
}

https://i.sstatic.net/VtKhy.png

Feed A image not showing anything

https://i.sstatic.net/PT1Iz.png

Feed B image Showing all items correctly

my 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)

im using wordpress to get feeds for Feed A as this php code here

     <?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];
  }
?>

Upvotes: -1

Views: 254

Answers (4)

erad
erad

Reputation: 1786

http://apps.encly.com/?feed=all_posts does not appear to return a JSON object. Therefore your parseJSONFeed will probably not be working the way you want it to.

You need to define a URL that returns a JSON object (one that has file extension .JSON) URL_FEED = "yourURLhere.json" is JSON object that is acceptable for JsonObjectRequest to find a JSON object in Response.Listener().

In the documentation, it indicates that the JsonObjectRequest parameter "listener - Listener to receive the JSON response". But when you use http://apps.encly.com/?feed=all_posts, it is not a JSON Object. It may LOOK like a JSON object, but it is not of type JSON object. Much like how a text file of type .doc LOOKS like a .txt file in Word, but it is NOT the same thing. .doc has different formatting embeded in it that you simply do not see.

Upvotes: 1

Youssef Al Subaihi
Youssef Al Subaihi

Reputation: 136

the problem was as @erad said the volly library didn't recognize the JSON data because it was look like JSON data but it's not

so i added this line of code to the page

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

and now it's working fine.

Upvotes: 0

323go
323go

Reputation: 14274

As I stated above, your php produces invalid JSON. You need to add the , only between items, not at the end. Something like the following should fix it:

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 ']}';

Note that I removed the comma from the end and only insert it at the beginning if it's not the first item.

Upvotes: 0

hoomi
hoomi

Reputation: 1912

Your Json is not well formatted. You have one extra comma at the end of your JSON

Upvotes: 0

Related Questions