android列表视图有jsonObject

时间:2011-12-10 16:58:58

标签: android json listview

我正致力于在服务器和服务器上请求一个php文件的活动。这个php文件将返回一个JSONArray作为其元素的JSONObjects。我得到了jArray&提取出其内容,例如全部jsonObjects。每个jsonObject都有一个特定用户的数据,如uniqueId,名称,地址,联系方式等......我展示了所有用户的列表。当我点击列表项时,我需要它会显示关注用户的完整个人资料...&为此,我将这些提取的jsonObjects放在另一个JSONObject中,其中uniqueId为name&相应的提取jsonObject作为其值。

我的清单:

this

当我点击此列表中的一个项目时,我得到了uniqueId我需要的内容,jsonObject的所有键都有JsonObject作为其值。

    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)

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

以下是我的班级的完整代码 - &gt;

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

如上所述,当我点击列表项时,我需要显示用户的完整个人资料...那么,我该怎么做才能解决这个问题! ???

2 个答案:

答案 0 :(得分:0)

简单:jFansData为空。它应该在哪里初始化?

答案 1 :(得分:0)

好的,所以我发现我错了。因为我从php&amp;获得了一个JSONArray的JSONArray每个JSONObject都是一个用户的完整数据,因此代表创建一个新的JSONOBject(将用户的UniqueId作为键,并将其作为索引i的JSONObject作为其值),我只需在“onClick”和“onClick”中拍摄JSONArrray。经历了它的元素(即JSONObjects)&amp;将当前JSONObject的UniqueId元素与我单击列表项时获得的uid相匹配。如果它匹配,那么我把这个jObject&amp;如果没有,则使用其值,然后转到其他。

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

}

坦克向所有回应我的宝贵评论&amp;建议! :)