-1
你好,我是用凌空庫從一個MySQL database.But無法解析JSON object.This獲取數據是我的主要ativity的代碼使用凌空庫通過PHP文件的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 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對象,但傳遞它的鏈接不工作。我的意思是在所使用的列表視圖中沒有任何顯示。 任何人都可以請幫助我知道如果我使用的PHP文件是正確的,如果不是如何可以糾正。我們可以在URL_FEED變量而不是json對象中使用php文件。 預先感謝您。
Roggeri坎波斯非常感謝你認爲解決了URL問題。 – dev
但即使在這之後,我通過的URL文件作爲URL_FEED不顯示任何內容。 – dev
對不起,延誤了。你解決了你的問題嗎? –