2017-02-28 55 views
1

我通過JSONarray檢索一些聯繫人的一些電話和電子郵件,爲這些元素中的每一個創建一個新的EditText(使用電話或電子郵件)。如果EditText內容更改,如何更新JSONobject?

我想知道如何更新我的JSONobject,如果用戶更改電話號碼或電子郵件,之後我想將此JSON對象添加到JSON數組發佈到我的服務。

這就是我把元素的EditText的代碼:我嘗試一些代碼以「setOnFocusChangeListener」,但它並沒有:-(

在此先感謝工作

try { 
       multiplesArray = new JSONArray(multiples); 
       //multiplesUpdatedArray = new JSONArray(); 
       System.out.println(multiplesArray.toString(2)); 

       for (int i=0; i<multiplesArray.length(); i++) { 
        JSONObject contact = new JSONObject(); 
        String type = multiplesArray.getJSONObject(i).getString("tipo"); 
        String data = multiplesArray.getJSONObject(i).getString("texto"); 
        String id = multiplesArray.getJSONObject(i).getString("id"); 

        if (type.equals("phone")) { 
         final EditText etPhoneItem = new EditText(this); 
         etPhoneItem.setText(data); 
         viewPhonesContainer.addView(etPhoneItem); 

        } else if (type.equals("email")) { 
         final EditText etEmailItem = new EditText(this); 
         etEmailItem.setText(data); 
         viewEmailContainer.addView(etEmailItem); 

        } 

        contact.put("tipo", type); 
        contact.put("id", id); 
        contact.put("texto", data); 
        contact.put("cat", ""); 
        contact.put("cat_id", ""); 

        /*multiplesUpdatedArray.put("tipo"); 
        multiplesUpdatedArray.put(type); 
        multiplesUpdatedArray.put("id"); 
        multiplesUpdatedArray.put(id); 
        multiplesUpdatedArray.put("texto"); 
        multiplesUpdatedArray.put(data);*/ 
       } 

      } catch (JSONException e) { 
       e.printStackTrace(); 
      } 

回答

1

使用addTextChangeListener

editText.addTextChangedListener(new TextWatcher() { 
      @Override 
      public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

      } 

      @Override 
      public void onTextChanged(CharSequence pCode, int start, int before, int count) { 
       // change your JSONObject 
       jsobObject.put("key", "value"); 
      } 

      @Override 
      public void afterTextChanged(Editable s) { 

      } 
     }); 
1

你可以做到這一點。

etPhoneItem.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 

     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 

     } 

     @Override 
     public void afterTextChanged(Editable s) { 
      if (s.length() != 0) { 
       try { 
        contact.put("number", s.toString()); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    }); 
1

只需在用戶更改文本時使用textView.addTextChangedListener(yourTextWatcherListener)即可獲取文本。但爲什麼更新json中的文本,因爲使用TextWatcher,你將最終更新你輸入的每個字符的json。頻繁更新json是非常昂貴和非常糟糕的做法。當您按下發布按鈕時,不要使用textwatch監聽器來創建json。

如果您非常清楚您要頻繁更新它,請根據json結構創建pojo類。更新類的變量並不昂貴。編輯完成後,使用Jackson將pojo類轉換爲json。

JSON to POJO

相關問題