Android的列表视图具有的JSONObject [英] android List View having jsonObject

查看:88
本文介绍了Android的列表视图具有的JSONObject的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的工作活动这要求服务器与放一个php文件中;这个PHP文件将返回我一个 JSONArray JSONObjects 作为要素。我得到这个 jArray &放大器;解压出来的内容,例如,所有的 jsonObjects 。每一个的JSONObject有像UNIQUEID,姓名,地址,联系方式等一个特定的用户数据......我向所有用户的列表。我需要当我点击列表项,它会显示我的关注用户的完整个人资料...&放大器;对于我把另一个这样的提取 jsonObjects 的JSONObject 有UNIQUEID姓名和放大器;相应的提取的JSONObject 作为它的值。

I am working on activity which request one php file on server & this php file will return me one JSONArray having JSONObjects as its elements. I get this jArray & extract out its contents e.g., all jsonObjects. each jsonObject have data of one specific user like uniqueId, name, address, contact details etc... I showed a list of all users. I need when I click on list item it will show me complete profile of the concern user...& for that i put these extracted jsonObjects in another JSONObject having uniqueId as name & the corresponding extracted jsonObject as its value.

我的列表:

当我点击这个名单,我得到了一个项目,它的 UNIQUEID 我需要的是,的JSONObject 为的JSONObject 作为它的值。

When i click on one item of this list I get its uniqueId what I need is, all keys of jsonObject having JsonObject as its values.

    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    ItemBean bean = (ItemBean) adapter.getItem(position);   
    Toast.makeText(this," FanId => " + bean.getUid() +" \n FanName => " + bean.getTitle(), 
                Toast.LENGTH_SHORT).show();
    Iterator<String> userKeys=extracted();//here i get-> Null PointerException!
        while(fKeys.hasNext()){
            System.out.println("Key:"+userKeys.next());
        }
  }

    //iterator that return me keys(e.g., all uids of users) 
    @SuppressWarnings("unchecked")
    private Iterator<String> extracted() {
        Iterator<String> keys = jFansData.keys();
        return keys;
    }


    12-10 20:45:55.833: ERROR/AndroidRuntime(907): Caused by:  java.lang.NullPointerException
    12-10 20:45:55.833: ERROR/AndroidRuntime(907): at com.technotalkative.listview5.MainActivity.extracted(MainActivity.java:87)
    12-10 20:45:55.833: ERROR/AndroidRuntime(907): at com.technotalkative.listview5.MainActivity.onCreate(MainActivity.java:51)
    12-10 20:45:55.833: ERROR/AndroidRuntime(907): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)

我没有得到我做什么错在这里,任何解决方案,请...

下面是完整的code我的类 - >

public class MainActivity extends Activity implements OnItemClickListener {

String url,fd;
ListView mFansListView;
JSONObject jFan_Data;//contain data of an indivisual fan
JSONObject jFansData;//contain data of an all fans
ListViewCustomAdapter adapter;
LayoutInflater lInflater;
private ArrayList<Object> fansList;
private ItemBean bean;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    prepareArrayLits();

    mFansListView = (ListView) findViewById(android.R.id.list);
    adapter = new ListViewCustomAdapter(this, fansList);
    mFansListView.setAdapter(adapter);//come null pointer exception when no fan data is returned! hendle it...

    mFansListView.setOnItemClickListener(this);
}

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    // TODO Auto-generated method stub
    ItemBean bean = (ItemBean) adapter.getItem(position);
    Toast.makeText(this," FanId => " + bean.getUid() +" \n UID => " + bean.getTitle(), Toast.LENGTH_SHORT).show(); 

    Iterator<String> fKeys=extracted();

    while(fKeys.hasNext()){
        System.out.println("Key:"+fKeys.next());
    }
}

//....................................................................

//iterator that return me keys(e.g., all uids of fans) through which i match clicked lists id
  @SuppressWarnings("unchecked")
private Iterator<String> extracted() {
            Iterator<String> keys = jFansData.keys();//I get NullPointerExcertion over here...???
    return keys;
}
//.............................................................................

/* *Method used to prepare the ArrayList,
 */
public void prepareArrayLits()
{
    url="http://192.168.200.111/ManU/location1_and.php";
    HttpClient client = new DefaultHttpClient();
    HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000);

    HttpResponse response;
    JSONObject json = new JSONObject();
 try {
    HttpPost post=new HttpPost(url);
     /**! Currently all these parameters are hard coded... 
      * In future i have to use services of LocationManager to get my current location!
      */
     json.put("radius", 1000);
     json.put("lat", 12.9716060);
     json.put("lang", 77.5903760);
     json.put("myid", "h9ow0");

        post.setHeader("json", json.toString());
        StringEntity se=new StringEntity(json.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        post.setEntity(se);

        response=client.execute(post);

       /* Checking response */
        // Get the data in the entity
        InputStream in=response.getEntity().getContent(); 

        //convert it to string... 
         fd=convertStreamToString(in);

        Log.i("Read from Server", fd);

      //Checking that fd is array containing data of all users or have no data...
        String no_data="No Data"; 

          if(no_data==fd){
              Log.i("NoRecords", "No Users Near you... Try over long distance!");
              }else {    

               JSONArray jArray = new JSONArray(fd);//contain array returned by "php" having data of all users

                   try{
                    fansList = new ArrayList<Object>();
                      for(int i=0;i<jArray.length();i++){
                        //will return the data of each row fetched from JSONArray returned by location1.php
                          String data_of_each_user=jArray.get(i).toString();

                        Log.i("Data Of User at index "+i+" is", data_of_each_user);

                         //I put the object at index "i" into JSONObject & retrieve data from name-value pair
                          jFan_Data=jArray.getJSONObject(i);//data of User at index i in array

                        AddObjectToList(jFan_Data.getString("uniqid").toString(),R.drawable.ic_add, jFan_Data.getString("name"), jFan_Data.getString("distance"));

                     try{
                            /** this JSONObject hold data of all users taking UniqueId of user as key & 
                             * JSONObject at index i in the array returned by the php as the value!!! */      
                               jFansData.put(jFan_Data.get("uniqid").toString(), jFan_Data);//why i getting NullPointerException Over Here...???
                          } catch (Exception e) {
                             // TODO: handle exception
                             e.printStackTrace(); 
                         }

                       }
                     } catch (Exception e) {
                         // TODO: handle exception
                         e.printStackTrace(); 
                     }
                }   
     } catch (Exception e) {
       // TODO: handle exception
       e.printStackTrace(); 
    }

}

//..............................................................................
// Add one item into the Array List
public void AddObjectToList(String uid,int image, String title, String desc)
{
    bean = new ItemBean();
    bean.setUid(uid);
    bean.setDescription(desc);
    bean.setImage(image);
    bean.setTitle(title);
    fansList.add(bean);
}

// -------------------------------------------------------------------------
//convert respons into human readable formate
private static String convertStreamToString(InputStream is) {

    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
 }
}

正如我上面提到的,我需要向用户展示的完整个人资料当我点击列表项......所以,我做什么来解决这个问题! ???

as i mentioned above, I need to show the complete profile of the user when i click on list item... So, What i do to solve this problem!!! ???

推荐答案

好了,所以我想通了,凡我错了。因为我从PHP和放大器JSONObjects之一JSONArray;每个JSONObject的是一个用户的完整的数据,因此对于有代表创造一种新的JSONObject(用户的关键和放大器具有唯一ID; JSONObject的索引i作为它的价值),我只是PIC的JSONArrray中的onClick&放大器;通过它的元素(即JSONObjects)及不见了;当前的JSONObject的UniqueID元素匹配,我得到当我点击列表项目的UID。如果匹配的话,我借此jObject和放大器;使用它的值,如果没有的话去其他。

Ok so I figured it out that where i am wrong. as i get one JSONArray of JSONObjects from php & each JSONObject is the complete data of one user so there for behalf of creating one new JSONOBject(having UniqueId of user as key & JSONObject at index i as its Value), i simply pic the JSONArrray in "onClick" & gone through its elements(i.e., JSONObjects) & match the UniqueId element of current JSONObject with the uid which i get when i click on list item. If it match then i take this jObject & use its values if not then go for other.

 public void onItemClick(AdapterView<?> arg0, View arg1, int position, long id) {
    // TODO Auto-generated method stub
    ItemBean bean = (ItemBean) adapter.getItem(position);
    Toast.makeText(this," FanId => " + bean.getUid() +" \n UID => " + bean.getTitle(), Toast.LENGTH_SHORT).show(); 


    /**from here-> I am going to start one activity that show the complete profile of a 
     * particular user... According to the unique id received from clicking on ListItem!    
     */
    for(int i=0;i<jArray.length();i++){
        try {
            JSONObject jFan_Data=jArray.getJSONObject(i);
            String uid=jFan_Data.getString("uniqid");

            if(uid.equals(bean.getUid())){
            //New Intent that start new Activity that show Profile of user
                String nm = jFan_Data.get("name").toString();// +"\n";
                String add = jFan_Data.get("address").toString();
                String city = jFan_Data.get("city").toString();
                String state = jFan_Data.get("state").toString();
                String zip = jFan_Data.get("postcode").toString();
                String uniqid = jFan_Data.get("uniqid").toString();
                String lat = jFan_Data.get("lat").toString();
                String lng = jFan_Data.get("lang").toString();
                String phone = jFan_Data.get("phone").toString();
                String mob = jFan_Data.get("mobile").toString();
                String email = jFan_Data.get("email").toString();
                String dis = jFan_Data.get("distance").toString();

                String[] jFanData={nm,add,city,state,zip,phone,mob,email,dis,uniqid,lat,lng};

                Intent in= new Intent(getParent(), FanProfile.class);
                TabGroupActivity prnt = (TabGroupActivity) getParent();
                Bundle fBundle= new Bundle();
                fBundle.putStringArray("jFanData", jFanData);
                in.putExtras(fBundle);
                prnt.startChildActivity("FanProfile", in);
                //startActivity(in);

            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

}

坦克所有的回应我提出的宝贵意见和放大器;建议! :)

Tanks to all that respond me for their valuable comments & suggestions! :)

这篇关于Android的列表视图具有的JSONObject的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆