-2

i want to send all contacts with contact name and number in one row in one array in my android application like john => "+92312xxxxxxx" , Right now i'm using namevaluepairs to post two arrays but it's not working like : public class ContactList extends Activity {

public TextView outputText;
   String phoneNumber = null;
   String names = null;
   String[] keyValue;
   String[] kes;
   int Count;
   String s = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_contact_list);
    outputText = (TextView) findViewById(R.id.textView1);

     fetchContacts();
    //Http connection
     InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
        for (int i = 0; i < Count ; i++)
            {
            nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
            nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
            Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
            }
        try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
        } 
        catch(ClientProtocolException e)
        {
            Log.e("ClientProtocol","Log_tag");
            e.printStackTrace();
            System.out.println("Excep: "+e);
        }
        catch(IOException e)
        {
            Log.e("Log_tag","IOException"); 
            e.printStackTrace();
        }

        String result = "";
        try

        {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) 
            {
                sb.append(line + "\n");
            }
            reader.close();
            is.close();
            result=sb.toString();
            Log.i("Response", "result "+ result);
        }       
        catch(Exception e)
        {
        Log.e("log_tag", "Error converting result "+e.toString());
        }
        //result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
         try
        {
        JSONArray jArray = new JSONArray(result);
        for (int i = 0; i < jArray.length(); i++)
       {
            s= s +";"+ jArray.getString(i) + "\n";
       }
       } 
       catch (Exception e)
       {
       Log.e("Response", "error fetching indexes" + e);
       }
       String[] friends= s.split(";");
       StringBuffer output = new StringBuffer();
       for (int i = 0; i < friends.length; i++) 
       {
            Log.i("List","Your friends namee"+friends[i]);
            output.append("\n Your friend's number"+ friends[i]);
       }    
    }
    //Fetch Contacts
     public void fetchContacts() {

          //  String email = null;
            Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
            String _ID = ContactsContract.Contacts._ID;
            String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
            String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
            Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
            String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
            String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
           // Uri EmailCONTENT_URI =  ContactsContract.CommonDataKinds.Email.CONTENT_URI;
            //String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
         //   String DATA = ContactsContract.CommonDataKinds.Email.DATA;

            ContentResolver contentResolver = getContentResolver();
            Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null); 
            // Loop for every contact in the phone
            Count = cursor.getCount();
            if (cursor.getCount() > 0) {
                 keyValue= new String[Count];
                   kes= new String[Count];

                while (cursor.moveToNext()) {
                    String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
                    String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
                    int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));

                    if (hasPhoneNumber > 0) {

                     // Query and loop for every phone number of the contact
                        Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
                        while (phoneCursor.moveToNext()) 
                        {
                            int i=0;
                            String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
                            phoneNumber +=":"+ stu;
                            names +=":" + name;
                            Log.i("List",stu + name +"\n" );
                        }

                        phoneCursor.close();
                                          }             
                                         }

            }
            keyValue = phoneNumber.split(":");
            kes = names.split(":");
            Log.i("List","24th"+keyValue[23]);
            Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
        }

PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names i'm stuck with sending and receving part Here is php code

<?php
define('DB_HOST', 'localhost');
 define('DB_NAME', 'verification'); 
 define('DB_USER','root'); 
 define('DB_PASSWORD',''); 

 // 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
    die("Database connection failed: " . mysqli_error());
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    die("Database selection failed: " . mysqli_error());
}

$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){

 //or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{  echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];

$j++;
}
else
{
;
}}
}
echo (json_encode($friends));

?>

2 Answers 2

0

You'll get a URL now that would look like:

www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.

I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.

Sign up to request clarification or add additional context in comments.

Comments

0

Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.

4 Comments

i have used this code to send only phonenumbers , and it works
Send all of them as a JSON array as the value of one parameter, so you will get more control of the array
can you place any sample code to POST json arrays? @chatura dilan

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.