use of org.json.JSONArray in project jpHolo by teusink.
the class ContactAccessorSdk5 method populateContactArray.
/**
* Creates an array of contacts from the cursor you pass in
*
* @param limit max number of contacts for the array
* @param populate whether or not you should populate a certain value
* @param c the cursor
* @return a JSONArray of contacts
*/
private JSONArray populateContactArray(int limit, HashMap<String, Boolean> populate, Cursor c) {
String contactId = "";
String rawId = "";
String oldContactId = "";
boolean newContact = true;
String mimetype = "";
JSONArray contacts = new JSONArray();
JSONObject contact = new JSONObject();
JSONArray organizations = new JSONArray();
JSONArray addresses = new JSONArray();
JSONArray phones = new JSONArray();
JSONArray emails = new JSONArray();
JSONArray ims = new JSONArray();
JSONArray websites = new JSONArray();
JSONArray photos = new JSONArray();
// Column indices
int colContactId = c.getColumnIndex(ContactsContract.Data.CONTACT_ID);
int colRawContactId = c.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID);
int colMimetype = c.getColumnIndex(ContactsContract.Data.MIMETYPE);
int colDisplayName = c.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME);
int colNote = c.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
int colNickname = c.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
int colBirthday = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
int colEventType = c.getColumnIndex(ContactsContract.CommonDataKinds.Event.TYPE);
if (c.getCount() > 0) {
while (c.moveToNext() && (contacts.length() <= (limit - 1))) {
try {
contactId = c.getString(colContactId);
rawId = c.getString(colRawContactId);
// If we are in the first row set the oldContactId
if (c.getPosition() == 0) {
oldContactId = contactId;
}
// to the array of contacts and create new objects.
if (!oldContactId.equals(contactId)) {
// Populate the Contact object with it's arrays
// and push the contact into the contacts array
contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
// Clean up the objects
contact = new JSONObject();
organizations = new JSONArray();
addresses = new JSONArray();
phones = new JSONArray();
emails = new JSONArray();
ims = new JSONArray();
websites = new JSONArray();
photos = new JSONArray();
// Set newContact to true as we are starting to populate a new contact
newContact = true;
}
// These fields are available in every row in the result set returned.
if (newContact) {
newContact = false;
contact.put("id", contactId);
contact.put("rawId", rawId);
}
// Grab the mimetype of the current row as it will be used in a lot of comparisons
mimetype = c.getString(colMimetype);
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) && isRequired("name", populate)) {
contact.put("displayName", c.getString(colDisplayName));
}
if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE) && isRequired("name", populate)) {
contact.put("name", nameQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE) && isRequired("phoneNumbers", populate)) {
phones.put(phoneQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE) && isRequired("emails", populate)) {
emails.put(emailQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE) && isRequired("addresses", populate)) {
addresses.put(addressQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE) && isRequired("organizations", populate)) {
organizations.put(organizationQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE) && isRequired("ims", populate)) {
ims.put(imQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE) && isRequired("note", populate)) {
contact.put("note", c.getString(colNote));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE) && isRequired("nickname", populate)) {
contact.put("nickname", c.getString(colNickname));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE) && isRequired("urls", populate)) {
websites.put(websiteQuery(c));
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE)) {
if (isRequired("birthday", populate) && ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY == c.getInt(colEventType)) {
contact.put("birthday", c.getString(colBirthday));
}
} else if (mimetype.equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE) && isRequired("photos", populate)) {
photos.put(photoQuery(c, contactId));
}
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
}
// Set the old contact ID
oldContactId = contactId;
}
// Push the last contact into the contacts array
if (contacts.length() < limit) {
contacts.put(populateContact(contact, organizations, addresses, phones, emails, ims, websites, photos));
}
}
c.close();
return contacts;
}
use of org.json.JSONArray in project cordova-android-chromeview by thedracle.
the class ContactAccessorSdk5 method modifyContact.
/**
* Creates a new contact and stores it in the database
*
* @param id the raw contact id which is required for linking items to the contact
* @param contact the contact to be saved
* @param account the account to be saved under
*/
private String modifyContact(String id, JSONObject contact, String accountType, String accountName) {
// Get the RAW_CONTACT_ID which is needed to insert new values in an already existing contact.
// But not needed to update existing values.
int rawId = (new Integer(getJsonString(contact, "rawId"))).intValue();
// Create a list of attributes to add to the contact database
ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
//Add contact type
ops.add(ContentProviderOperation.newUpdate(ContactsContract.RawContacts.CONTENT_URI).withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, accountType).withValue(ContactsContract.RawContacts.ACCOUNT_NAME, accountName).build());
// Modify name
JSONObject name;
try {
String displayName = getJsonString(contact, "displayName");
name = contact.getJSONObject("name");
if (displayName != null || name != null) {
ContentProviderOperation.Builder builder = ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE });
if (displayName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, displayName);
}
String familyName = getJsonString(name, "familyName");
if (familyName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.FAMILY_NAME, familyName);
}
String middleName = getJsonString(name, "middleName");
if (middleName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.MIDDLE_NAME, middleName);
}
String givenName = getJsonString(name, "givenName");
if (givenName != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME, givenName);
}
String honorificPrefix = getJsonString(name, "honorificPrefix");
if (honorificPrefix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.PREFIX, honorificPrefix);
}
String honorificSuffix = getJsonString(name, "honorificSuffix");
if (honorificSuffix != null) {
builder.withValue(ContactsContract.CommonDataKinds.StructuredName.SUFFIX, honorificSuffix);
}
ops.add(builder.build());
}
} catch (JSONException e1) {
Log.d(LOG_TAG, "Could not get name");
}
// Modify phone numbers
JSONArray phones = null;
try {
phones = contact.getJSONArray("phoneNumbers");
if (phones != null) {
// Delete all the phones
if (phones.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a phone
{
for (int i = 0; i < phones.length(); i++) {
JSONObject phone = (JSONObject) phones.get(i);
String phoneId = getJsonString(phone, "id");
// This is a new phone so do a DB insert
if (phoneId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing phone so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Phone._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { phoneId, ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, getJsonString(phone, "value")).withValue(ContactsContract.CommonDataKinds.Phone.TYPE, getPhoneType(getJsonString(phone, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get phone numbers");
}
// Modify emails
JSONArray emails = null;
try {
emails = contact.getJSONArray("emails");
if (emails != null) {
// Delete all the emails
if (emails.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a email
{
for (int i = 0; i < emails.length(); i++) {
JSONObject email = (JSONObject) emails.get(i);
String emailId = getJsonString(email, "id");
// This is a new email so do a DB insert
if (emailId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing email so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Email._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { emailId, ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Email.DATA, getJsonString(email, "value")).withValue(ContactsContract.CommonDataKinds.Email.TYPE, getContactType(getJsonString(email, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify addresses
JSONArray addresses = null;
try {
addresses = contact.getJSONArray("addresses");
if (addresses != null) {
// Delete all the addresses
if (addresses.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a address
{
for (int i = 0; i < addresses.length(); i++) {
JSONObject address = (JSONObject) addresses.get(i);
String addressId = getJsonString(address, "id");
// This is a new address so do a DB insert
if (addressId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type")));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode"));
contentValues.put(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing address so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.StructuredPostal._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { addressId, ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.StructuredPostal.TYPE, getAddressType(getJsonString(address, "type"))).withValue(ContactsContract.CommonDataKinds.StructuredPostal.FORMATTED_ADDRESS, getJsonString(address, "formatted")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.STREET, getJsonString(address, "streetAddress")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.CITY, getJsonString(address, "locality")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.REGION, getJsonString(address, "region")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE, getJsonString(address, "postalCode")).withValue(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY, getJsonString(address, "country")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get addresses");
}
// Modify organizations
JSONArray organizations = null;
try {
organizations = contact.getJSONArray("organizations");
if (organizations != null) {
// Delete all the organizations
if (organizations.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a organization
{
for (int i = 0; i < organizations.length(); i++) {
JSONObject org = (JSONObject) organizations.get(i);
String orgId = getJsonString(org, "id");
// This is a new organization so do a DB insert
if (orgId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type")));
contentValues.put(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name"));
contentValues.put(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title"));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing organization so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Organization._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { orgId, ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Organization.TYPE, getOrgType(getJsonString(org, "type"))).withValue(ContactsContract.CommonDataKinds.Organization.DEPARTMENT, getJsonString(org, "department")).withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, getJsonString(org, "name")).withValue(ContactsContract.CommonDataKinds.Organization.TITLE, getJsonString(org, "title")).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get organizations");
}
// Modify IMs
JSONArray ims = null;
try {
ims = contact.getJSONArray("ims");
if (ims != null) {
// Delete all the ims
if (ims.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a im
{
for (int i = 0; i < ims.length(); i++) {
JSONObject im = (JSONObject) ims.get(i);
String imId = getJsonString(im, "id");
// This is a new IM so do a DB insert
if (imId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Im.TYPE, getImType(getJsonString(im, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing IM so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Im._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { imId, ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Im.DATA, getJsonString(im, "value")).withValue(ContactsContract.CommonDataKinds.Im.TYPE, getContactType(getJsonString(im, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get emails");
}
// Modify note
String note = getJsonString(contact, "note");
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Note.NOTE, note).build());
// Modify nickname
String nickname = getJsonString(contact, "nickname");
if (nickname != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Nickname.NAME, nickname).build());
}
// Modify urls
JSONArray websites = null;
try {
websites = contact.getJSONArray("urls");
if (websites != null) {
// Delete all the websites
if (websites.length() == 0) {
Log.d(LOG_TAG, "This means we should be deleting all the phone numbers.");
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a website
{
for (int i = 0; i < websites.length(); i++) {
JSONObject website = (JSONObject) websites.get(i);
String websiteId = getJsonString(website, "id");
// This is a new website so do a DB insert
if (websiteId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value"));
contentValues.put(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type")));
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing website so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Website._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { websiteId, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE }).withValue(ContactsContract.CommonDataKinds.Website.DATA, getJsonString(website, "value")).withValue(ContactsContract.CommonDataKinds.Website.TYPE, getContactType(getJsonString(website, "type"))).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get websites");
}
// Modify birthday
String birthday = getJsonString(contact, "birthday");
if (birthday != null) {
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=? AND " + ContactsContract.CommonDataKinds.Event.TYPE + "=?", new String[] { id, ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE, new String("" + ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY) }).withValue(ContactsContract.CommonDataKinds.Event.TYPE, ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY).withValue(ContactsContract.CommonDataKinds.Event.START_DATE, birthday).build());
}
// Modify photos
JSONArray photos = null;
try {
photos = contact.getJSONArray("photos");
if (photos != null) {
// Delete all the photos
if (photos.length() == 0) {
ops.add(ContentProviderOperation.newDelete(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.Data.RAW_CONTACT_ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { "" + rawId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).build());
} else // Modify or add a photo
{
for (int i = 0; i < photos.length(); i++) {
JSONObject photo = (JSONObject) photos.get(i);
String photoId = getJsonString(photo, "id");
byte[] bytes = getPhotoBytes(getJsonString(photo, "value"));
// This is a new photo so do a DB insert
if (photoId == null) {
ContentValues contentValues = new ContentValues();
contentValues.put(ContactsContract.Data.RAW_CONTACT_ID, rawId);
contentValues.put(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
contentValues.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
contentValues.put(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes);
ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI).withValues(contentValues).build());
} else // This is an existing photo so do a DB update
{
ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(ContactsContract.CommonDataKinds.Photo._ID + "=? AND " + ContactsContract.Data.MIMETYPE + "=?", new String[] { photoId, ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE }).withValue(ContactsContract.Data.IS_SUPER_PRIMARY, 1).withValue(ContactsContract.CommonDataKinds.Photo.PHOTO, bytes).build());
}
}
}
}
} catch (JSONException e) {
Log.d(LOG_TAG, "Could not get photos");
}
boolean retVal = true;
//Modify contact
try {
mApp.getActivity().getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
} catch (RemoteException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
} catch (OperationApplicationException e) {
Log.e(LOG_TAG, e.getMessage(), e);
Log.e(LOG_TAG, Log.getStackTraceString(e), e);
retVal = false;
}
// if the save was a success return the contact ID
if (retVal) {
return id;
} else {
return null;
}
}
use of org.json.JSONArray in project cordova-android-chromeview by thedracle.
the class CordovaChromeClient method onJsPrompt.
/**
* Tell the client to display a prompt dialog to the user.
* If the client returns true, WebView will assume that the client will
* handle the prompt dialog and call the appropriate JsPromptResult method.
*
* Since we are hacking prompts for our own purposes, we should not be using them for
* this purpose, perhaps we should hack console.log to do this instead!
*
* @param view
* @param url
* @param message
* @param defaultValue
* @param result
*/
@Override
public boolean onJsPrompt(ChromeView view, String url, String message, String defaultValue, JsPromptResult result) {
// Security check to make sure any requests are coming from the page initially
// loaded in webview and not another loaded in an iframe.
boolean reqOk = false;
if (url.startsWith("file://") || Config.isUrlWhiteListed(url)) {
reqOk = true;
}
// prompt(this.stringify(args), "gap:"+this.stringify([service, action, callbackId, true]));
if (reqOk && defaultValue != null && defaultValue.length() > 3 && defaultValue.substring(0, 4).equals("gap:")) {
JSONArray array;
try {
array = new JSONArray(defaultValue.substring(4));
String service = array.getString(0);
String action = array.getString(1);
String callbackId = array.getString(2);
String r = this.appView.exposedJsApi.exec(service, action, callbackId, message);
result.confirm(r == null ? "" : r);
} catch (JSONException e) {
e.printStackTrace();
return false;
}
} else // Sets the native->JS bridge mode.
if (reqOk && defaultValue != null && defaultValue.equals("gap_bridge_mode:")) {
this.appView.exposedJsApi.setNativeToJsBridgeMode(Integer.parseInt(message));
result.confirm("");
} else // Polling for JavaScript messages
if (reqOk && defaultValue != null && defaultValue.equals("gap_poll:")) {
String r = this.appView.exposedJsApi.retrieveJsMessages();
result.confirm(r == null ? "" : r);
} else // Do NO-OP so older code doesn't display dialog
if (defaultValue != null && defaultValue.equals("gap_init:")) {
result.confirm("OK");
} else // Show dialog
{
final JsPromptResult res = result;
AlertDialog.Builder dlg = new AlertDialog.Builder(this.cordova.getActivity());
dlg.setMessage(message);
final EditText input = new EditText(this.cordova.getActivity());
if (defaultValue != null) {
input.setText(defaultValue);
}
dlg.setView(input);
dlg.setCancelable(false);
dlg.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
String usertext = input.getText().toString();
res.confirm(usertext);
}
});
dlg.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
res.cancel();
}
});
dlg.create();
dlg.show();
}
return true;
}
use of org.json.JSONArray in project solo by b3log.
the class ArticleMgmtService method tag.
/**
* Tags the specified article with the specified tag titles.
*
* @param tagTitles the specified tag titles
* @param article the specified article
* @return an array of tags
* @throws RepositoryException repository exception
*/
private JSONArray tag(final String[] tagTitles, final JSONObject article) throws RepositoryException {
final JSONArray ret = new JSONArray();
for (int i = 0; i < tagTitles.length; i++) {
final String tagTitle = tagTitles[i].trim();
JSONObject tag = tagRepository.getByTitle(tagTitle);
String tagId;
if (null == tag) {
LOGGER.log(Level.TRACE, "Found a new tag[title={0}] in article[title={1}]", new Object[] { tagTitle, article.optString(Article.ARTICLE_TITLE) });
tag = new JSONObject();
tag.put(Tag.TAG_TITLE, tagTitle);
tag.put(Tag.TAG_REFERENCE_COUNT, 1);
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
// Publish article directly
tag.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, 1);
} else {
// Save as draft
tag.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, 0);
}
tagId = tagRepository.add(tag);
tag.put(Keys.OBJECT_ID, tagId);
} else {
tagId = tag.optString(Keys.OBJECT_ID);
LOGGER.log(Level.TRACE, "Found a existing tag[title={0}, id={1}] in article[title={2}]", new Object[] { tag.optString(Tag.TAG_TITLE), tag.optString(Keys.OBJECT_ID), article.optString(Article.ARTICLE_TITLE) });
final JSONObject tagTmp = new JSONObject();
tagTmp.put(Keys.OBJECT_ID, tagId);
tagTmp.put(Tag.TAG_TITLE, tagTitle);
final int refCnt = tag.optInt(Tag.TAG_REFERENCE_COUNT);
final int publishedRefCnt = tag.optInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);
tagTmp.put(Tag.TAG_REFERENCE_COUNT, refCnt + 1);
if (article.optBoolean(Article.ARTICLE_IS_PUBLISHED)) {
tagTmp.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt + 1);
} else {
tagTmp.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt);
}
tagRepository.update(tagId, tagTmp);
}
ret.put(tag);
}
return ret;
}
use of org.json.JSONArray in project solo by b3log.
the class ArticleMgmtService method processTagsForArticleUpdate.
/**
* Processes tags for article update.
*
* <ul>
* <li>Un-tags old article, decrements tag reference count</li>
* <li>Removes old article-tag relations</li>
* <li>Saves new article-tag relations with tag reference count</li>
* </ul>
*
* @param oldArticle the specified old article
* @param newArticle the specified new article
* @throws Exception exception
*/
private void processTagsForArticleUpdate(final JSONObject oldArticle, final JSONObject newArticle) throws Exception {
final String oldArticleId = oldArticle.getString(Keys.OBJECT_ID);
final List<JSONObject> oldTags = tagRepository.getByArticleId(oldArticleId);
final String tagsString = newArticle.getString(Article.ARTICLE_TAGS_REF);
String[] tagStrings = tagsString.split(",");
final List<JSONObject> newTags = new ArrayList<JSONObject>();
for (int i = 0; i < tagStrings.length; i++) {
final String tagTitle = tagStrings[i].trim();
JSONObject newTag = tagRepository.getByTitle(tagTitle);
if (null == newTag) {
newTag = new JSONObject();
newTag.put(Tag.TAG_TITLE, tagTitle);
}
newTags.add(newTag);
}
final List<JSONObject> tagsDropped = new ArrayList<JSONObject>();
final List<JSONObject> tagsNeedToAdd = new ArrayList<JSONObject>();
final List<JSONObject> tagsUnchanged = new ArrayList<JSONObject>();
for (final JSONObject newTag : newTags) {
final String newTagTitle = newTag.getString(Tag.TAG_TITLE);
if (!tagExists(newTagTitle, oldTags)) {
LOGGER.log(Level.DEBUG, "Tag need to add[title={0}]", newTagTitle);
tagsNeedToAdd.add(newTag);
} else {
tagsUnchanged.add(newTag);
}
}
for (final JSONObject oldTag : oldTags) {
final String oldTagTitle = oldTag.getString(Tag.TAG_TITLE);
if (!tagExists(oldTagTitle, newTags)) {
LOGGER.log(Level.DEBUG, "Tag dropped[title={0}]", oldTag);
tagsDropped.add(oldTag);
} else {
tagsUnchanged.remove(oldTag);
}
}
LOGGER.log(Level.DEBUG, "Tags unchanged[{0}]", tagsUnchanged);
for (final JSONObject tagUnchanged : tagsUnchanged) {
final String tagId = tagUnchanged.optString(Keys.OBJECT_ID);
if (null == tagId) {
// Unchanged tag always exist id
continue;
}
final int publishedRefCnt = tagUnchanged.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);
if (oldArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
if (!newArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
tagUnchanged.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt - 1);
tagRepository.update(tagId, tagUnchanged);
}
} else {
if (newArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
tagUnchanged.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt + 1);
tagRepository.update(tagId, tagUnchanged);
}
}
}
for (final JSONObject tagDropped : tagsDropped) {
final String tagId = tagDropped.getString(Keys.OBJECT_ID);
final int refCnt = tagDropped.getInt(Tag.TAG_REFERENCE_COUNT);
tagDropped.put(Tag.TAG_REFERENCE_COUNT, refCnt - 1);
final int publishedRefCnt = tagDropped.getInt(Tag.TAG_PUBLISHED_REFERENCE_COUNT);
if (oldArticle.getBoolean(Article.ARTICLE_IS_PUBLISHED)) {
tagDropped.put(Tag.TAG_PUBLISHED_REFERENCE_COUNT, publishedRefCnt - 1);
}
tagRepository.update(tagId, tagDropped);
}
final String[] tagIdsDropped = new String[tagsDropped.size()];
for (int i = 0; i < tagIdsDropped.length; i++) {
final JSONObject tag = tagsDropped.get(i);
final String id = tag.getString(Keys.OBJECT_ID);
tagIdsDropped[i] = id;
}
removeTagArticleRelations(oldArticleId, 0 == tagIdsDropped.length ? new String[] { "l0y0l" } : tagIdsDropped);
tagStrings = new String[tagsNeedToAdd.size()];
for (int i = 0; i < tagStrings.length; i++) {
final JSONObject tag = tagsNeedToAdd.get(i);
final String tagTitle = tag.getString(Tag.TAG_TITLE);
tagStrings[i] = tagTitle;
}
final JSONArray tags = tag(tagStrings, newArticle);
addTagArticleRelation(tags, newArticle);
}
Aggregations