2016-12-09 2 views
2

Ich versuche, Kontakte von meinem Telefon zu bekommen, aber ich möchte die Daten zu einem PHP-Dienst veröffentlichen, um in der Datenbank zu speichern. Nach dem Abrufen, i erstellen, ist ein Array mit Name-Wert-Paaren, die SchnipselJSONArray zu PHP schreiben

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

Der Ausgang so etwas wie dieses

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

Wie formatiere ich das so, dass ich es in der Datenbank speichern können. Meine PHP-Seite

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

Irgendwelche Vorschläge?

Antwort

4

Mein Vorschlag ist nicht mit dem Namevaluepair gehen Sie über der Lutscher-Version, da der Namevaluepair veraltet ist so besser mit dem Thema Anordnungsliste.

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

und Ihre Json Teil Aufruf sollte wie unten, muss

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

Und die Kontaktdaten sehen werden, mit dem unten stehenden Verfahren senden:

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

Und Ihre PHP-Code aussehen wird wie,

$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 Kumar, Danke, ein d was macht diese Methode sanitizeJSONBody(); – Alphy

+0

Ich habe die Methodenimplementierung von sanitizeJSONBody(); hinzugefügt, diese Methode wird verwendet, um die Anfrage und die Antwort in der Log.v anzuzeigen (ersetzen Sie die ***, wenn diese aus Sicherheitsgründen irgendwelche Passwortfelder haben). – Bethan

+0

@B Kumar, So weit so gut, ich kann die Körperausgabe sehen, aber sie scheint abgeschnitten zu sein wie {"phone": "[+ 123, +456, 789, statt {" phone ":" [+ 123, +456, 789] "}, was könnte der Grund sein? – Alphy

2

Auf der PHP-Seite müssen Sie die folgende JSON:

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

Wenn Sie verwalten GsonBuilder Sie solche JSON zur Verfügung zu stellen (sorry, kann damit nicht helfen), können Sie es zu Ihrem PHP-Service veröffentlichen können.

Dann in 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); 
} 

Siehe auch: http://php.net/manual/en/function.json-decode.php