繁体   English   中英

使用JSON通过PHP将数据绑定到Android

[英]Binding data through PHP to Android using JSON

我正在开发使用PHP和mysql作为外部数据库的android应用程序。 现在,在我的活动页面中,整个JSON数据都存在,但没有绑定到listview中。 我尝试了很多,也在Google上搜索。

我的activity.java如下:

private void getdatalatlog(double latitude, double longitude) {
    String link = "http://192.168.0.104/PHP/webservice/comments.php?latitude='"+latitude+"'&longitude='"+longitude+"'";
    aq.progress(R.id.progressBar1).ajax(link, JSONObject.class, this,"jsonCallback");
}

public void jsonCallback(String link, JSONObject json, AjaxStatus status) throws JSONException {                
    mCommentList = new ArrayList<HashMap<String, String>>();
    JSONParser jParser = new JSONParser();
    json = jParser.getJSONFromUrl(link);        
    mComments = json.getJSONArray(TAG_POSTS);
    for (int i = 0; i < mComments.length(); i++) {
            JSONObject c = mComments.getJSONObject(i);
            String title = c.getString(TAG_TITLE);
            String content = c.getString(TAG_MESSAGE);
            String username = c.getString(TAG_USERNAME);            
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(TAG_TITLE, title);
            map.put(TAG_MESSAGE, content);
            map.put(TAG_USERNAME, username);
            mCommentList.add(map);              
        }
    ListAdapter adapter = new SimpleAdapter(this, mCommentList,
            R.layout.single_post, new String[] { TAG_TITLE,TAG_USERNAME ,TAG_MESSAGE
                    }, new int[] { R.id.shop_name,R.id.address,R.id.distance
                     });

    setListAdapter(adapter);        
    ListView lv = getListView();    
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

        }
    });
}

我的getdatalatlong()方法在onCreate()方法中调用。 jsonCallback()方法的json object ,我获得了数据库的所有数据。

检查是否从服务器获取JSON对象。

如果您有能力,请执行此操作。 将该JSON结果存储在字符串中(通常我将其称为JSONString)。

例如 :

{
    "username":"Vignesh";
    "title" : "Check My Site";
    "content" : "vickytechy.hol.es"
}

然后使用它通过索引获取值

JSONObject jsonObject = new JSONObject(JSONString);//JSONString is the JSON result;
Name = jsonObject.optString("username");//Name = Vignesh
Title = jsonObject.optString("title");//Title = Check My Site
Content = jsonObject.optString("content");//Content = vickytechy.hol.es

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM