2016-12-09 8 views
2

私の電話から連絡先を取得しようとしていますが、データをPHPサービスに投稿してデータベースに保存したいと考えています。検索した後、私は名前と値のペアを持つ配列を作成し、スニペットJSONArrayをPHPに投稿する

 public void getContacts() throws IOException, JSONException { 

     List<String> phnnumbers = new ArrayList<String>(); 
     List<String> names = new ArrayList<String>(); 

     ContentResolver cr = getContentResolver(); 
     Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, 
       null, null, null, null); 

     if (cur.getCount() > 0) { 
      while (cur.moveToNext()) { 
       String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); 
       String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
       if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
        System.out.println("name : " + name + ", ID : " + id); 
        names.add(name); 
        // get the phone number 
        Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", 
          new String[]{id}, null); 
        while (pCur.moveToNext()) { 
         String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
         System.out.println("phone" + phone); 
         phnnumbers.add(phone); 
        } 

       } 
      } 
Log.d("NAMES",name.toString()); 
      // registerContacts(this,URL,names,phnnumbers); 
     } 
    } 

は、出力は、私はデータベースに格納することができるようにどのように私はこれをフォーマットします。この

[name[]="Chacha Kori, phone[]="+123456987", name[]="Gabuli Somi", [phone[]="+123456789",name[]="Geto Somi", phone[]="+123456789", 

のようなものです。私のPHP側

function SynchContacts() { 

      $phone = $this->input->post('phone'); 
      $name = $this->input->post('name');  


      for ($i = 0; $i < count($phone); $i++) { 
       $data = array(
        'name' => $name[$i], 
        'phone' => $phone[$i] 
       ); 
       $this->saveData('phonebook', $data); 
      } 
     } 

ご意見はありますか? PHP側の

答えて

4

私の提案は、ロリポップバージョンより上のNameValuePairはと行くのでより良い廃止されているので、のNameValuePairを行っていないです配列リスト。

public void getContacts() { 

    List<String> phnnumbers = new ArrayList<String>(); 
    List<String> names = new ArrayList<String>(); 

    ContentResolver cr = getContentResolver(); 
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, 
     null, null, null, null); 

    if (cur.getCount() > 0) { 
     while (cur.moveToNext()) { 
      String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID)); 
      String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
      if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) { 
       System.out.println("name : " + name + ", ID : " + id); 
       names.add(name); 
       // get the phone number 
       Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", 
        new String[]{id}, null); 
       while (pCur.moveToNext()) { 
        String phone = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); 
        System.out.println("phone" + phone); 
        phnnumbers.add(phone); 
       } 
       pCur.close(); 
      } 
     } 
    } 
} 

そしてあなたのJSON

private static JSONObject post(String sUrl, String body) { 
    Log.d("post", sUrl); 
    Log.d("post-body", sanitizeJSONBody(body)); 
    HttpURLConnection connection = null; 

    String authentication = "example" + ":" + "exam123ple"; 
    String encodedAuthentication = Base64 
     .encodeToString(authentication.getBytes(), Base64.NO_WRAP); 

    try { 
     URL url = new URL(sUrl); 
     connection = (HttpURLConnection) url.openConnection(); 
     connection.setDoOutput(true); 
     connection.setDoInput(true); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", "application/json"); 
     connection.setRequestProperty("Accept", "application/json"); 
     connection.setRequestProperty("Authorization", 
      "Basic " + encodedAuthentication); 
     connection.setRequestProperty("Accept-Charset", "utf-8,*"); 
     OutputStreamWriter streamWriter = new OutputStreamWriter(
      connection.getOutputStream()); 

     streamWriter.write(body); 
     streamWriter.flush(); 
     StringBuilder stringBuilder = new StringBuilder(); 
     if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { 
      InputStreamReader streamReader = new InputStreamReader(
       connection.getInputStream()); 
      BufferedReader bufferedReader = new BufferedReader(
       streamReader); 
      String response = null; 
      while ((response = bufferedReader.readLine()) != null) { 
       stringBuilder.append(response + "\n"); 
      } 
      bufferedReader.close(); 

      Log.d("Post-Response", 
      sanitizeJSONBody(stringBuilder.toString())); 
      return new JSONObject(stringBuilder.toString()); 
     } else { 
      Log.d("Post-Error", connection.getResponseMessage()); 
      return null; 
     } 
    } catch (Exception exception) { 
     Log.e("Post-Exception", exception.toString()); 
     return null; 
    } finally { 
     if (connection != null) { 
      connection.disconnect(); 
     } 
    } 
} 

、以下のように見えるしなければならない部分を呼び出し、連絡先データは、以下の方法で送信する必要があります:

public static JSONObject registerTask(Context ctx, String sUrl, List<String> names, List<String> phoneNums) throws JSONException, IOException { 
    JSONObject request = new JSONObject(); 

    request.putOpt("names", names); 
    request.putOpt("phoneNums", phoneNums); 

    sUrl = sUrl + "yourapiname"; 
    return post(sUrl, request.toString()); 
} 

private static String sanitizeJSONBody(String body) { 
    if (body.contains("password")) { 
     body = body.replaceAll("\"password\":\"[^\"]+\"", 
       "\"password\":******"); 
    } 
    if (body.contains("newPassword")) { 
     body = body.replaceAll("\"newPassword\":\"[^\"]+\"", 
       "\"newPassword\":******"); 
    } 

    return body; 
} 

そして、あなたのPHPコードを見ていきますlike、

$inputJSON = file_get_contents('php://input'); 
$input = json_decode($inputJSON, TRUE); 
$nameArray = array($input['names']); 
$phoneNumArray = array($input['phoneNums']); 
for($i=0;i<count($nameArray);$i++){ 
    $data = array(
     'name' => $nameArray[$i], 
     'phone' => $phoneNumArray[$i], 
    ); 
    $this->saveData('phonebook', $data); 
} 
+0

@BクマールdこのメソッドはsanitizeJSONBody();を実行します。 – Alphy

+0

私はsanitizeJSONBody()のメソッドの実装を追加しました;実際にはこのメソッドはLog.vにリクエストとレスポンスを表示するために使用されます(セキュリティ上の理由からパスワードフィールドがあれば***を置き換えます)。 – Bethan

+0

@B Kumar、これまでのところ良くなっていますが、ボディの出力を見ることができますが、{"phone": "[+ 123、+ 456、789、 +456、789] "}、理由は何でしょうか? – Alphy

2

次のJSONを必要とする:あなたは(申し訳ありませんが、それを支援することはできません)あなたに、このようなJSONを提供するために、GsonBuilderを管理する場合

[ 
    { 
     "name": "Chacha Kori", 
     "phone": "+123456987" 
    }, 
    { 
     "name": "Gabuli Somi", 
     "phone": "+123456987" 
    }, 
    { 
     "name": "Geto Somi", 
     "phone": "+123456987" 
    } 
] 

、あなたのPHPサービスに投稿することができます。

その後、PHPで:また

// Get the json variable which contains our JSON string 
$json = $this->input->post('json'); 

// Decode JSON into PHP Array 
$contacts = json_decode($json, true); 

// Iterate through the collection of phone/names 
foreach ($contacts as $row) { 
    $data = array(
     'name' => $row['name'], 
     'phone' => $row['phone'], 
    ); 

    $this->saveData('phonebook', $data); 
} 

参照:http://php.net/manual/en/function.json-decode.php

関連する問題