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

时间:2015-08-21 19:23:01

标签: php mysql json android-volley

你好我正在使用volley库从mysql数据库中获取数据。但是无法解析json对象。这是我主要活动的代码

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变量中使用的json对象。我正在使用的php文件是

<?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文件的outpuut是一个json对象,但传递其链接不工作.i意味着在使用的listview中没有显示任何内容。 谁能帮助我知道我使用的php文件是否正确如果不能如何纠正。我们可以在URL_FEED变量而不是json对象中使用php文件。 提前谢谢。

1 个答案:

答案 0 :(得分:0)

您所要做的就是使用JSON_UNESCAPED_SLASHES

将回声线更改为:

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