如何在android中检索更新的json

时间:2014-01-21 09:01:42

标签: php android json getjson

我有4个按钮,通过点击每个按钮,它将其ID发送到php并检查匹配ID,如果存在则意味着它从json中获取该内容并在主活动中显示该内容。对于我,我可以在点击每个时传递id按钮,但无法从json获取id匹配内容。

我的安卓代码在这里..

    public class MainActivity extends Activity {
    public GridView grid;

     public ArrayList arr = new ArrayList();
     public Map  home = new HashMap();
     public Long str_id; 
     String url = "http://10.0.2.2:80/android_connect/menu.php";                    


     @Override
 protected void onCreate(Bundle savedInstanceState) {

         home.put("id",new Integer(1));
         home.put("name",new String("home"));
         home.put("pos",new Integer(1));
         arr.add(home);
         home = new HashMap();

         home.put("id",new Integer(2));
         home.put("name",new String("About Us"));
         home.put("pos",new Integer(2));
         arr.add(home);
         home = new HashMap();

         home.put("id",new Integer(3));
         home.put("name",new String("Services"));
         home.put("pos",new Integer(3));
         arr.add(home);
         home = new HashMap();

         home.put("id",new Integer(4));
         home.put("name",new String("Products"));
         home.put("pos",new Integer(4));
         arr.add(home);

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      grid = (GridView) findViewById(R.id.gridView1);
      grid.setAdapter(new ButtonAdapter(this));  
      grid.setOnItemClickListener(new OnItemClickListener(){
         // private String ct_name;

      public void onItemClick(AdapterView<?> parent,View v, int position, long id)
    { 
         str_id = id;

      Toast.makeText(getBaseContext(), 
              "button" + (id) + " selected", 
              Toast.LENGTH_LONG).show();

      new CallLogin().execute(url);


      new LongOperation().execute(url);

     }

      }); 

    }

     public class ButtonAdapter extends BaseAdapter {
         private Context context;    
         public ButtonAdapter(Context c){
             context = c;
         }
         public int getCount() {
            //return filenames.length;
             return arr.size();
         }
         public Object getItem(int position) {

             Map p = (Map) arr.get(position);
             return Integer.parseInt(p.get("pos").toString());
             //return position;
         }     
         public long getItemId(int position) {
             //return position;
             Map p = (Map) arr.get(position);
             return Integer.parseInt(p.get("id").toString());
         }
         public View getView(int position, View convertView, ViewGroup parent){
               Button btn;  
                  if (convertView == null) {   
                   btn = new Button(context);  
                   btn.setLayoutParams(new GridView.LayoutParams(100, 100));  
                   btn.setPadding(8, 8, 8, 8);  
                   btn.setFocusable(false);
                   btn.setClickable(false);
                   }else {  
                   btn = (Button) convertView;  
                  }     

                  Map m = (Map) arr.get(position);

                 {

                  btn.setText(m.get("name").toString()+":"+position);    
                  btn.setTextColor(Color.WHITE);  
                  btn.setId(Integer.parseInt(m.get("id").toString()));

         }
                return btn;
         }
     }    

     /************onclick  button  passes its id to php ***********/
 class CallLogin extends AsyncTask<String, String, String>{

            //private int position;

            protected String doInBackground(String... params) {


                List<NameValuePair> parms = new ArrayList<NameValuePair>();
                parms.add(new BasicNameValuePair("pid",str_id.toString()));


                try{

                    URL httpUrl = new URL(url);
                    HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
                    wr.writeBytes(URLEncodedUtils.format(parms, "utf-8"));
                    wr.flush();
                    wr.close();
                int responseCode = connection.getResponseCode();

                }catch (IOException e) {
                    e.printStackTrace();
                }finally{

                }

                return null;
            }
        }

     /************ fetching datas from json ***********/
     private class LongOperation  extends AsyncTask<String, Void, Void> {

         // Required initialization

         private final HttpClient Client = new DefaultHttpClient();
         private String Content;
         private String Error = null;
         private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
         String data ="";

         TextView jsonParsed = (TextView) findViewById(R.id.jsonParsed);
         int sizeData = 0; 


         protected void onPreExecute() {

              Dialog.setMessage("Please wait..");
              Dialog.show();

               }

                 protected Void doInBackground(String... urls) {
                 /************ Make Post Call To Web Server ***********/
           BufferedReader reader=null;
                   // Send data
                 try
                 {
                     // Defined URL  where to send data
                    URL url = new URL(urls[0]);

                   // Send POST data request
                   URLConnection conn = url.openConnection();
                   conn.setDoOutput(true);
                   OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                   wr.write( data );
                   wr.flush();
                   // Get the server response
                   reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                   StringBuilder sb = new StringBuilder();
                   String line = null;
                        // Read Server Response
                     while((line = reader.readLine()) != null)
                         {
                                // Append server response in string
                                sb.append(line + "");
                        }

                     // Append Server Response To Content String
                    Content = sb.toString();
                 }
                 catch(Exception ex)
                 {
                     Error = ex.getMessage();
                 }
                 finally
                 {
                     try
                     {
                                reader.close();
                     }

                     catch(Exception ex) {}
                 }

                    return null;
       }

         protected void onPostExecute(Void unused) {

             Dialog.dismiss();
                   if (Error != null) {

                 jsonParsed.setText("Output : "+Error);

             } else {
                  // Show Response Json On Screen (activity)
                 jsonParsed.setText( Content );

              /****************** Start Parse Response JSON Data *************/

                String OutputData = "";
                 JSONObject jsonResponse;

                 try {

                      /****** Creates a new JSONObject with name/value mappings from the JSON string. ********/
                  jsonResponse = new JSONObject(Content);

                      /***** Returns the value mapped by name if it exists and is a JSONArray. ***/
                      /*******  Returns null otherwise.  *******/
                     JSONArray jsonMainNode = jsonResponse.optJSONArray("menu");

                      /*********** Process each JSON Node ************/

                  int lengthJsonArr = jsonMainNode.length(); 
                   for(int i=0; i < lengthJsonArr; i++)
                   {
                        /****** Get Object for each JSON node.***********/
                         JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
                         //getIntent().getData();
                          /******* Fetch node values **********/
                         String Pid      = jsonChildNode.optString("pid").toString();
                      String Content     = jsonChildNode.optString("name").toString();

                        OutputData += "pid : "+ Pid +" "+ "content : "+ Content +" ";

                 }

                  // Show Parsed Output on screen (activity)
                     jsonParsed.setText( OutputData );

                  } catch (JSONException e) {

                   e.printStackTrace();
                }

              }
         }
     }

    @Override
     public boolean onCreateOptionsMenu(Menu menu) {

     getMenuInflater().inflate(R.menu.main, menu);
     return true;
     }

}

在我的4个按钮中,服务按钮只有chidelement,所以如果点击服务按钮,它的id将被传递并检查并获取那些子元素。这是我的问题,我无法检索相同的id内容。是我的PHP代码。

    <?php

    $con=mysql_connect("localhost","root","")or die("cannot connect"); 
    $db=mysql_select_db("and_dynamicview",$con) or die("cannot select");

    if(!isset($_REQUEST['pid']))
    {
        $sql = "select pid,name,refid,ord_field from menu where pid = 0 and stat != 'R'";
    }
    else
    {
        $sql = "select pid,name,refid,ord_field from menu where pid = ".$_REQUEST['pid']." and stat != 'R'";
    } 
        $fp = fopen("./log.txt","a");
        fwrite($fp,$sql."\n");
        fclose($fp);
    $result = mysql_query($sql);
    $json = array();
    $i = 0;
    if(mysql_num_rows($result))
    {
        $json['page_menu']['flag'] = 'M';
        while($row=mysql_fetch_assoc($result))
        {
            $json['menu'][$i]['pid']=ucwords($row['pid']);
            $json['menu'][$i]['name']=$row['name'];
            $json['menu'][$i]['refid']=$row['refid'];
            $json['menu'][$i++]['ord_field']=$row['ord_field'];
        }
    }
    else
    {

        $sql = "select * from page where pid=3";
        $result = mysql_query($sql);
        $json = array();

        if(mysql_num_rows($result))
        {
        while($row=mysql_fetch_assoc($result))
$json ['page_menu']['flag'] = 'P';
         {    $json['page'][]=$row;

         }
        }
    }

    mysql_close($con);
    echo json_encode($json); 
    ?>

我的json菜单是..

{"page_menu":{"flag":"M"},"menu":[{"pid":"0","name":"Home","refid":"1","ord_field":"1"},{"pid":"0","name":"About Us","refid":"2","ord_field":"2"},{"pid":"0","name":"Services","refid":"3","ord_field":"3"},{"pid":"0","name":"Products","refid":"4","ord_field":"4"}]} 

menu.php?pid = 3是

{"page_menu":{"flag":"M"},"menu":[{"pid":"3","name":"24X7","refid":"5","ord_field":"2"},{"pid":"3","name":"8X5","refid":"6","ord_field":"1"}]} 

1 个答案:

答案 0 :(得分:0)

我认为您应该采取以下措施:

    try {
        JSONObject jsonOBJ = new JSONObject(jsonString);
        JSONArray menuJSONArray = jsonOBJ.getJSONArray("menu");
        for (int i = 0; i < menuJSONArray.length(); i++) {
            JSONObject menuJSONObj = menuJSONArray.getJSONObject(i);
            //here you get the pid 
            int pId = menuJSONObj.getInt("pid");

        }

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

希望有所帮助