2014-01-21 44 views
0

我有4个按钮,通过点击每个按钮它发送它的ID到PHP和检查匹配ID,如果存在意味着它从JSON获取内容并显示在主activity.For我我点击每个按钮时可以传递id,但无法从json中获取id匹配的内容。如何检索更新的JSON在Android

我的Android的代码是在这里..

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将被通过,检查并取入该子elements.Here我的问题是,我无法检索相同的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"}]} 
+0

你的意思是说,在PHP中没有收到yopu从android应用程序传递给PHP的ID? – Vaibs

+0

你可以请你的JSON响应。 –

+0

id我通过但检索相应的id内容不正确.ie菜单?pid = 3 json是这样的.. {“flag”:“M”,“menu”:[{“pid”:“3”,“命名 “:” 24X7" , “REFID”: “5”, “ord_field”: “2”},{ “PID”: “3”, “名称”: “8X5”, “REFID”: “6”,” ord_field“:”1“}]}。 – ammu

回答

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

希望有帮助

+0

获取pid值的内容,但在我的情况下,我可以将pid发送到php及其工作,但是在获取数据时,jpn自动设置为零,所以我没有得到预期的结果.pid 0值只显示。 – ammu

+0

请发布您的android代码。 –

+0

我已经发布了代码 – ammu