0

i am creating an android application in which i want to access database from mysql for user name, phone no and email address. and i want to compare phone no from android phone contact list and the phone no getting from mysql database. for that purpose i use 2 arraylist 1st for phone contact and 2nd for mysql phone no. my main problem is when i compare both the arraylist then i shows no result. i attach here the code please someone help me to solve this problem.

public class PhoneNoActivity extends Activity{
    JSONArray jArray,jArray1;
    JSONObject jobj;
    String result = null,phone=null;
    InputStream is = null;
    StringBuilder sb=null;
    double lat=0;
    double lon=0;
    String user=null;
    ArrayList<NameValuePair> nameValuePairs;

    ListView lv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        String phno=null;
        ArrayList<String> cntPhone=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) {
                    Cursor pCur = cr.query(
                    ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?", new String[]{id}, null);
                    while (pCur.moveToNext()) {
                        String phoneNo = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                        if(phoneNo.length()>10) {
                            phno=phoneNo.subSequence(phoneNo.length()-10, phoneNo.length()).toString();
                            // Log.e(name, phno);
                        }
                        cntPhone.add(phoneNo);
                    } 
                    pCur.close();
                }
            }
        }

        ArrayList<String> cntOnline=new ArrayList<String>();
        try {
            nameValuePairs = new ArrayList<NameValuePair>();

            /*String phone=null;
            for(int k=0;k<=cntPhone.size();k++) {
                Log.e("k",k+"");
                phone=cntPhone.get(k);
                nameValuePairs.add(new BasicNameValuePair("phone", phone));
            */
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://10.0.2.2/ah_login_api/select.php");
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line="0";
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            result=sb.toString();

            Log.e("result=", result);
            jArray = new JSONArray(result);
            JSONObject json_data=null;
            for(int i=0;i<jArray.length();i++){
                json_data = jArray.getJSONObject(i);
                user=json_data.getString("user");
                phone=json_data.getString("phone");
                lat=json_data.getDouble("email");

                cntOnline.add(phone);
            }
            for(String s:cntOnline) {
                for(String s1:cntPhone ) {
                    if(s.equals(s1)) {
                        Log.e("match found", phone);
                    }
                }
            }
            /*
                for(int l=0;l<cntOnline.size();l++) {
                    Log.e("loop start", ""+l);
                    for(int k=0;k<cntPhone.size();k++) {
                        if(cntPhone.get(k).trim().equals(cntOnline.get(l).trim())) {
                            Log.e("match found", phone);
                        }
                    }      
                }*/
        //}
        } catch(Exception ex) {
            Log.e("Exception  in ",ex.toString());
        }
    }
}

and this is my php code from which i access details

<?php
    mysql_connect("localhost","root","");
    mysql_select_db("MyContact");
    $sql=mysql_query("select * from newuser");
    while($row=mysql_fetch_assoc($sql))
        $output[]=$row;
    print(json_encode($output));
    mysql_close(); 
?>
3
  • how are you getting past the NetworkOnMainThreadException? Commented May 30, 2013 at 17:01
  • with this: if (android.os.Build.VERSION.SDK_INT > 9) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); } Commented May 30, 2013 at 17:47
  • 1. Post an example of the JSON you get returned. 2. Remove all unnecessary code, like uncommented code. 3. Only show the part of the code, that you want us to look at. 4. Use a few printstatements, to see what is actually really returned from the ContentResolver and what is actually returned from the JSON Array. If String.equals doesn't return anything, nothing matches = something is wrong with the data you're trying to compare and it's not like you expect it to be. Commented May 30, 2013 at 20:28

1 Answer 1

2

/* Retrieves phone numbers from Phone Contact List */

public ArrayList<String> getNumber() {
    String phoneNumber;
    ArrayList<String> contact_number = new ArrayList<String>();
    ContentResolver cr = getApplicationContext().getContentResolver();
    Cursor phones = cr.query(
            ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
            null, null);
    while (phones.moveToNext()) {
        phoneNumber = phones
                .getString(phones
                        .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

        System.out.println(".................." + phoneNumber);
        contact_number.add(phoneNumber);
    }
    phones.close();
    return contact_number;
}

/* Gets the Numbers from MySQL database using object "Contact" and Compares it with the method "getNumber()" which retrieves phone numbers from Phone Contact List */

@SuppressWarnings("unused")
private Contact convertContact(JSONObject obj) throws JSONException {
    Contact contact = new Contact();
    String name = obj.getString("user_name");
    String mobile_no = obj.getString("mobile_no");

    boolean isMatched = false;
    contact_number = getNumber();
    for (int i = 0; i < contact_number.size(); i++) {
        if (mobile_no.equals(contact_number.get(i))) {
            isMatched = true;
            contact.setName(name);
            contact.setMobileNo(mobile_no);

        }
    }
    return isMatched ? contact : null;

}

/* If the number from database matches with the phone contact list add and generate in listview */

private class AsyncTasak extends
        AsyncTask<String, Void, ArrayList<Contact>> {

    @Override
    protected void onPostExecute(ArrayList<Contact> result) {
        super.onPostExecute(result);
        arrayadapter.setItemList(result);
        arrayadapter.notifyDataSetChanged();

    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected ArrayList<Contact> doInBackground(String... params) {
        ArrayList<Contact> result = new ArrayList<Contact>();

        try {
            URL u = new URL(params[0]);

            HttpURLConnection conn = (HttpURLConnection) u.openConnection();
            conn.setRequestMethod("GET");

            conn.connect();
            InputStream is = conn.getInputStream();

            byte[] b = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            while (is.read(b) != -1)
                baos.write(b);

            String JSONResp = new String(baos.toByteArray());

            JSONArray arr = new JSONArray(JSONResp);
            for (int i = 0; i < arr.length(); i++) {
                Contact temp = convertContact(arr.getJSONObject(i));
                if (temp != null) {
                    result.add(temp);
                }
            }

            return result;
        } catch (Throwable t) {
            t.printStackTrace();
        }
        return null;
    }
Sign up to request clarification or add additional context in comments.

1 Comment

@Ramesh_D: I don't know but if it is, it's lacking a lot of explanation about what it's doing and why. Some context and information would enhance it a lot.

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.