使用 volley 库为 json 对象传递 php 文件

passing php file for json object using volley library

你好,我正在使用 volley 库从 mysql database.But 中获取数据,无法解析 json object.This 是我的主要活动代码

public class MainActivity extends Activity {
    private static final String TAG = MainActivity.class.getSimpleName();
    private ListView listView;
    private FeedListAdapter listAdapter;
    private List<FeedItem> feedItems;
    private String URL_FEED = "http://someurl/feed.json";

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

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
        getActionBar().setIcon(
                new ColorDrawable(getResources().getColor(android.R.color.transparent)));

        // We first check for cached request
         Cache cache = AppController.getInstance().getRequestQueue().getCache();
         Entry entry = cache.get(URL_FEED);



         if (entry != null) {
         //fetch the data from cache
          try {
              String data = new String(entry.data, "UTF-8");
           try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
              e.printStackTrace();
            }
         } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
         }

          } else {
         //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
         * */
    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("name"));

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

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }





    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

在上面的代码中,url传递的是一个json对象,json对象的结构就像

{
    "feed": [
        {
            "id": 1,
            "name": "National Geographic Channel",
            "image": "http://api.androidhive.info/feed/img/cosmos.jpg",
            "status": "\"Science is a beautiful and emotional human endeavor,\" says Brannon Braga, executive producer and director. \"And Cosmos is all about making science an experience.\"",
            "profilePic": "http://api.androidhive.info/feed/img/nat.jpg",
            "timeStamp": "1403375851930",
            "url": null
        },
        {
            "id": 2,
            "name": "TIME",
            "image": "http://api.androidhive.info/feed/img/time_best.jpg",
            "status": "30 years of Cirque du Soleil's best photos",
            "profilePic": "http://api.androidhive.info/feed/img/time.png",
            "timeStamp": "1403375851930",
            "url": "http://ti.me/1qW8MLB"
        }
]
}

但我想传递一个 php 文件而不是我正在使用的 URL_FEED variable.The php 文件中使用的 json 对象是

<?php
define('HOST','mysql.******.in');
define('USER','someuser');
define('PASS','*****');
define('DB','somedb');

$con = mysqli_connect(HOST,USER,PASS,DB);

$sql = "select * from timeline";

$res = mysqli_query($con,$sql);

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('id'=>intval($row[0]),
'name'=>$row[1],
'image'=>$row[2],
'status'=>$row[3],
'profilePic'=>$row[4],
'timestamp'=>$row[5],
'url'=>$row[6]
));
}

header('Content-type: application/json');
echo json_encode(array("feed"=>$result),JSON_PRETTY_PRINT);

mysqli_close($con);

?>

我的 php 文件的输出是

{
    "feed": [
        {
            "id": 1,
            "name": "helpme",
            "image": "http:\/\/api.androidhive.info\/feed\/img\/cosmos.jpg",
            "status": "Hello everyone",
            "profilePic": "http:\/\/api.androidhive.info\/feed\/img\/nat.jpg",
            "timestamp": "2015-08-21 19:11:15",
            "url": "http:\/\/ti.me\/1qW8MLB"
        }
    ]
}

这里的url格式被打乱了,会不会影响解析文件的时候。 即使我使用的 php 文件的输出是一个 json 对象但传递它的 link 不是 working.i 意味着在使用的列表视图中没有任何显示。 任何人都可以帮助我知道我使用的 php 文件是否正确如果不正确怎么可能 rectified.And 我们可以在 URL_FEED 变量中使用 php 文件而不是json 对象。 提前谢谢你。

您只需使用JSON_UNESCAPED_SLASHES

将回显行更改为:

echo json_encode(array("feed"=>$result), JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);