将联系人上传到服务器时出现空指针异常

时间:2016-09-15 04:55:50

标签: android android-contacts

在这里,我从移动设备上获取姓名,电子邮件,电话号码并尝试上传到服务器。如果联系人包含姓名,电子邮件和电话号码,则值将成功插入..但如果有任何字段是空的它正在抛出NULL指针异常。如何避免这一个..我的意思是如果联系人不包含电子邮件,它应该至少发送姓名和电话号码。

这是我的代码。

public class DisplayContact1 extends Activity {

    private static String TAG = WorkDetails1.class.getSimpleName();

    Button select;

    private String vault;
    List<AddressBookContact> list;

    public static final String kvault = "vault_no";
    public static final String kname = "name";
    public static final String kphone = "phone";
    public static final String kemail = "email";
    public static final String kcontacts = "contacts";

    public static final String SHARED_PREF_NAME = "myloginapp";

    public static final String UPLOAD_URL = "http://oursite.com/contacts_1.php";

    private static final int MY_PERMISSIONS_REQUEST_READ_CONTACTS = 1;

    Cursor cursor;
    LongSparseArray<AddressBookContact> array;
    long start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getActionBar().setDisplayShowTitleEnabled(false);
        setContentView(R.layout.display);

        SharedPreferences sharedPreferences = getSharedPreferences(ProfileLogin.SHARED_PREF_NAME, MODE_PRIVATE);

        vault = sharedPreferences.getString(ProfileLogin.EMAIL_SHARED_PREF,"Not Available");
        getAllContacts(this.getContentResolver());

    }

    public  void getAllContacts(ContentResolver cr) {

        int result = ContextCompat.checkSelfPermission(DisplayContact1.this, Manifest.permission.READ_CONTACTS);
        if (result == PackageManager.PERMISSION_GRANTED){

            //fetches contacts from the phone contact list and displays in ascending order
            list = new LinkedList<AddressBookContact>();
            array = new LongSparseArray<AddressBookContact>();
            start = System.currentTimeMillis();

            String[] projection = {
                    ContactsContract.Data.MIMETYPE,
                    ContactsContract.Data.CONTACT_ID,
                    ContactsContract.Contacts.DISPLAY_NAME,
                    ContactsContract.CommonDataKinds.Contactables.DATA,
                    ContactsContract.CommonDataKinds.Contactables.TYPE,
            };
            String selection = ContactsContract.Data.MIMETYPE + " in (?, ?)";
            String[] selectionArgs = {
                    ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE,
                    ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE,
            };
            String sortOrder = ContactsContract.Contacts.SORT_KEY_ALTERNATIVE;

            Uri uri = ContactsContract.Data.CONTENT_URI;
// we could also use Uri uri = ContactsContract.Data.CONTENT_URI;

            cursor = getContentResolver().query(uri, projection, selection, selectionArgs, sortOrder);
            contactsdisplay();

        } else {

            requestForLocationPermission();
        }
    }

    private void requestForLocationPermission()
    {

        if (ActivityCompat.shouldShowRequestPermissionRationale(DisplayContact1.this, Manifest.permission.READ_CONTACTS))
        {
        }
        else {

            ActivityCompat.requestPermissions(DisplayContact1.this, new String[]{Manifest.permission.READ_CONTACTS}, MY_PERMISSIONS_REQUEST_READ_CONTACTS);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults)
    {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_READ_CONTACTS:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED)
                {
                    getAllContacts(DisplayContact1.this.getContentResolver());
                    contactsdisplay();
                }
                break;
        }
    }

    public  void contactsdisplay() {

        //Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
        final int mimeTypeIdx = cursor.getColumnIndex(ContactsContract.Data.MIMETYPE);
        final int idIdx = cursor.getColumnIndex(ContactsContract.Data.CONTACT_ID);
        final int nameIdx = cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
        final int dataIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.DATA);
        final int typeIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Contactables.TYPE);

        while (cursor.moveToNext()) {
            long id = cursor.getLong(idIdx);
            AddressBookContact addressBookContact = array.get(id);
            if (addressBookContact == null) {
                addressBookContact = new AddressBookContact(id, cursor.getString(nameIdx), getResources());
                array.put(id, addressBookContact);
                list.add(addressBookContact);
            }
            int type = cursor.getInt(typeIdx);
            String data = cursor.getString(dataIdx);
            String mimeType = cursor.getString(mimeTypeIdx);
            if (mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)) {
                // mimeType == ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE
                addressBookContact.addEmail(type, data);
            } else {
                // mimeType == ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE
                addressBookContact.addPhone(type, data);
            }
        }
        long ms = System.currentTimeMillis() - start;
        cursor.close();

// done!!! show the results...
        int i = 1;
        for (AddressBookContact addressBookContact : list) {
            Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
        }
        final String cOn = "<b><font color='#ff9900'>";
        final String cOff = "</font></b>";
        Spanned l1 = Html.fromHtml("got " + cOn + array.size() + cOff + " contacts<br/>");
        Spanned l2 = Html.fromHtml("query took " + cOn + ms / 1000f + cOff + " s (" + cOn + ms + cOff + " ms)");

        Log.d(TAG, "\n\n╔══════ query execution stats ═══════" );
        Log.d(TAG, "║    " + l1);
        Log.d(TAG, "║    " + l2);
        Log.d(TAG, "╚════════════════════════════════════" );
        SpannableStringBuilder msg = new SpannableStringBuilder().append(l1).append(l2);

        ListView lv= (ListView) findViewById(R.id.lv);
        lv.setAdapter(new ArrayAdapter<AddressBookContact>(this, android.R.layout.simple_list_item_1, list));
        lv.setItemsCanFocus(false);
        lv.setTextFilterEnabled(true);

        select = (Button) findViewById(R.id.button1);
        select.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v){
                uploadImage();
            }

        });
    }

    public void uploadImage(){

        SharedPreferences sharedPreferences = getSharedPreferences(DisplayContact.SHARED_PREF_NAME, MODE_PRIVATE);

        final String vault_no = vault;

        class UploadImage extends AsyncTask<Void,Void,String> {
            ProgressDialog loading;
            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                loading = ProgressDialog.show(DisplayContact1.this,"Please wait...","uploading",false,false);
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                loading.dismiss();
                if(s.equalsIgnoreCase("Successfully Saved")){
                    //Intent intent = new Intent(CollegeDetails.this,Work.class);
                    Toast.makeText(DisplayContact1.this, s, Toast.LENGTH_SHORT).show();
                    // startActivity(intent);
                }else{
                    Toast.makeText(DisplayContact1.this,s,Toast.LENGTH_SHORT).show();

                }
            }

            @Override
            protected String doInBackground(Void... params) {
                RequestHandler rh = new RequestHandler();
                //RegisterUserClass rh = new RegisterUserClass();
                HashMap<String,String> param = new HashMap<String,String>();

                JSONArray contacts = new JSONArray();
                int i = 1;
                for (AddressBookContact addressBookContact : list) {
                    try {
                        Log.d(TAG, "AddressBookContact #" + i++ + ": " + addressBookContact.toString(true));
                        JSONObject contact = new JSONObject();

                        contact.put(kname, addressBookContact.name.toString());
                        contact.put(kvault, vault_no);
                        contact.put(kphone, addressBookContact.phone.toString());

                        if(addressBookContact.email.toString()!=null)
                           contact.put(kemail, addressBookContact.email.toString());

                        contacts.put(contact);
                    }
                    catch (JSONException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    param.put(kcontacts, contacts.toString());
                    System.out.println("param value.." + i++ +":"+ contacts.toString());
                }
                return rh.sendPostRequest(UPLOAD_URL, param);

            }
        }
        UploadImage u = new UploadImage();
        u.execute();
    }
}

这里是 AddressBookContact.class

public class AddressBookContact {

    private long id;
    private Resources res;
    String name;
    LongSparseArray<String> email;
    LongSparseArray<String> phone;

    AddressBookContact(long id, String name, Resources res) {
        this.id = id;
        this.name = name;
        this.res = res;
    }

    @Override
    public String toString() {
        return toString(false);
    }

    public String toString(boolean rich) {
        SpannableStringBuilder builder = new SpannableStringBuilder();
        if (rich) {
            builder.append("id: ").append(Long.toString(id))

                    .append(", name: ").append(name);
        } else {
            builder.append("name: ").append(name);
        }

        if (phone != null) {
            builder.append("\nphone: ");
            for (int i = 0; i < phone.size(); i++) {
                int type = (int) phone.keyAt(i);

                builder.append(phone.valueAt(i));
                if (i + 1 < phone.size()) {
                    builder.append(", ");
                }
            }
        }

        if (email != null) {
            builder.append("\nemail: ");
            for (int i = 0; i < email.size(); i++) {
                int type = (int) email.keyAt(i);

                builder.append(email.valueAt(i));
                if (i + 1 < email.size()) {
                    builder.append(", ");
                }
            }
        }
        return builder.toString();
    }

    public void addEmail(int type, String address) {
        if (email == null) {
            email = new LongSparseArray<String>();
        }
        email.put(type, address);
    }

    public void addPhone(int type, String number) {
        if (phone == null) {
            phone = new LongSparseArray<String>();
        }
        phone.put(type, number);
    }
}

如果电子邮件字段为空,我在此行收到空指针异常。 contact.put(kemail, addressBookContact.email.toString()); ..所以我添加了if循环来检查空状态..但是我也得到了异常。

3 个答案:

答案 0 :(得分:1)

  

添加两个条件,如下所示,您的字符串可能不是null,但可以   空""

 if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
     contact.put(kemail, addressBookContact.email.toString());

答案 1 :(得分:1)

使用TextUtils

if(!TextUtils.isEmpty(addressBookContact.email.toString())){
    contact.put(kemail, addressBookContact.email.toString()); 
}

如果kemail是必填字段,那么在else条件下只需传递""空值。

答案 2 :(得分:1)

下面

if (addressBookContact.email.toString() != null)

您尝试从'email'变量获取String,该变量为null。 正确的比较是:

if (addressBookContact.email != null)