2014-01-21 43 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