Related
I am trying to fetch SMS's which start with TM-,ID-, AX-, AD- but I am getting sms's only which having number.
I am not able to receive any sms which will have text in address.
Here is my code :
Uri uriSms = Uri.parse("content://sms/inbox");
String[] projection = new String[]{"_id", "address", "date", "body", "person", "type"};
m_SMSCursor =context.getContentResolver().query(uriSms, projection, null,null,null);
if(m_SMSCursor.moveToFirst())
{
// Read each row from cursor and store it into the database
do {
// Extract fields from cursor
final String number = m_SMSCursor.getString(1);
final long date = m_SMSCursor.getLong(2);
final String body = m_SMSCursor.getString(3);
final String person = m_SMSCursor.getString(4);
final int type = m_SMSCursor.getInt(5);
try {
// Insert call log into database
long l;
new Thread(new Runnable() {
#Override
public void run() {
// create object for CallLogAdapter
SMSDataAdapter objSmsDataAdapter = new SMSDataAdapter(
context);
// open the database
objSmsDataAdapter = objSmsDataAdapter.Open();
try {
boolean isVMPresent = number.startsWith("VM-");
boolean isLMPresent = number.startsWith("LM-");
boolean isTMPresent = number.startsWith("TM-");
boolean isVKPresent = number.startsWith("VK-");
boolean isIXPresent = number.startsWith("IX-");
boolean isADPresent = number.startsWith("AD-");
boolean isAXPresent = number.startsWith("AX-");
boolean isBWPresent = number.startsWith("BW-");
boolean isIDPresent = number.startsWith("ID-");
boolean isIMPresent = number.startsWith("IM-");
Log.i(TAG, "Number1 : " + number + " body1 : " + body + " peron : " + person + " type : " + type);
if (isVMPresent || isLMPresent || isTMPresent || isVKPresent || isIXPresent || isADPresent || isAXPresent || isBWPresent || isIDPresent || isIMPresent) {
long lNumberOfEntry = objSmsDataAdapter.Insert(number, body, date, DATA_NOT_ANALYZED);
}
} catch (SQLException e1) {
} finally {
// Close the database
objSmsDataAdapter.Close();
}
}
}).start();
} catch (SQLException e) {
return FAILURE;
}
} while (m_SMSCursor.moveToNext());
}
But I am able to fetch all sms except which having text in address. I am able fetch sms's which having number in address.
Please give me hint or reference.
Use this method to get all data in a list first and then access the number by smsList.getNumber()
List<SMSData> smsList = new ArrayList<SMSData>();
Uri uri = Uri.parse("content://sms/inbox");
Cursor c= getContentResolver().query(uri, null, null ,null,null);
startManagingCursor(c);
// Read the sms data and store it in the list
if(c.moveToFirst()) {
for(int i=0; i < c.getCount(); i++) {
SMSData sms = new SMSData();
sms.setBody(c.getString(c.getColumnIndexOrThrow("body")).toString());
sms.setNumber(c.getString(c.getColumnIndexOrThrow("address")).toString());
smsList.add(sms);
c.moveToNext();
}
}
c.close();
SMSData:
public class SMSData {
// Number from witch the sms was send
private String number;
// SMS text body
private String body;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
Here i am fetching the name,email,phone number from the mobile and trying to upload to server..Here if the contacts contains name,email and phone number the values will be inserted successfully..but if any of the field is empty it is throwing NULL pointer exception.How to avoid this one..i mean if the contact does not contain email it should atleast send name and phone number.
here is my code.
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();
}
}
here is the 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);
}
}
if email field is empty, i am getting null pointer exception at this line..
contact.put(kemail, addressBookContact.email.toString());..so i have added if loop to check the null condition..but then also i am getting exception.
Here
if (addressBookContact.email.toString() != null)
you try to get String from 'email' variable that is null.
Correct comparing is:
if (addressBookContact.email != null)
Add two conditions as below your string might not be null but can be
empty ""
if(addressBookContact.email.toString() != null && !addressBookContact.email.toString().equalsIgnoreCase(""))
contact.put(kemail, addressBookContact.email.toString());
Use TextUtils.
if(!TextUtils.isEmpty(addressBookContact.email.toString())){
contact.put(kemail, addressBookContact.email.toString());
}
And if kemail is compulsory field then in else condition just pass "" empty value.
I have this function which is called when there is any change in Contacts in Phone, Now the problem here is that this code works fine on HTC Desire 620 (KitKat) but crashes on Moto G (Lollipop) and other devices.
Error : java.lang.IllegalStateException: Illegal State: object is no longer valid to operate on. Was it deleted?
Also: It works fine with Moto G2 if contacts are less like < 500 but if more it crashes!
Logcat details:
E/AndroidRuntime: Process: com.advisualinc.echo:SwitchService, PID: 16972
E/AndroidRuntime: java.lang.IllegalStateException: Illegal State: Object is no longer valid to operate on. Was it deleted by another thread?
E/AndroidRuntime: at io.realm.internal.UncheckedRow.nativeGetString(Native Method)
E/AndroidRuntime: at java.lang.Thread.run(Thread.java:818)
My service class:
public class ContactsSyncService extends Service {
public static int count = 0;
int k = 0;
Realm realmFresh;
public static boolean contactUpdated = false;
ContentObserver mObserver;
public Context contextService = ContactsSyncService.this;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mObserver = new ContentObserver(new Handler()) {
#Override
public void onChange(boolean selfChange) {
super.onChange(selfChange);
k++;
// Toast.makeText(ApplicationController.getInstance(), "Starting Change: " , Toast.LENGTH_SHORT).show();
if (!contactUpdated) {
contactUpdated = true;
Logger.debug("Contact Update to start -->");
// Toast.makeText(ApplicationController.getInstance(), "Changing: " , Toast.LENGTH_SHORT).show();
FetchLocalContacts.refreshingContactsDB(contextService);
// Toast.makeText(ApplicationController.getInstance(), "Changed: " , Toast.LENGTH_SHORT).show();
}
}
};
getContentResolver().registerContentObserver(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, true, mObserver);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
getContentResolver().unregisterContentObserver(mObserver);
}
}
The Function called by Service is refreshingContactsDB():
public static void parseContactstoContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
Realm realmFetchFirstTime = Realm.getInstance(ApplicationController.getInstance());
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION,null,null, null);
String duplicateName = "";
String duplicatePhone = "";
if( phones.getCount() >0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if(phoneNo!=null&&!phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if(name.equalsIgnoreCase(duplicateName)&&phoneNo.equalsIgnoreCase(duplicatePhone))
{
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
realmFetchFirstTime.beginTransaction();
R_LocalContactDB rContacts = realmFetchFirstTime.createObject(R_LocalContactDB.class);
rContacts.setName(name);
rContacts.setPhone(formattedPhoneNumber);
realmFetchFirstTime.commitTransaction();
Logger.debug("Formatted Contacts --> Name: "
+ name
+ " -- Phone No: "
+ formattedPhoneNumber);
}
}
}
phones.close();
}
realmFetchFirstTime.close();
// getNumbersFromDBAndUpdate();
}
});
background.start();
}
public static void getNumbersFromDBAndUpdate()
{
Realm realmServer = Realm.getInstance(ApplicationController.getInstance());
RealmResults<R_LocalContactDB> query = realmServer.where(R_LocalContactDB.class).findAll();
Logger.debug("Contact Update updating to server -->");
for (int i = 0; i < query.size(); i++)
{
phoneNumberJsonArray.put(query.get(i).getPhone());
}
try
{
uploadContactJsonBody.put("phone_numbers", phoneNumberJsonArray);
Logger.debug("LocalContacts RequestJson ---> "
+ uploadContactJsonBody.toString());
AppPreferenceManager.getInstance().setContactPref(1);
UploadLocalContactsToServerAsynTask test = new UploadLocalContactsToServerAsynTask(
uploadContactJsonBody.toString(),
new LocalContactsSyncCallBack()
{
#Override
public void didFinishProfileSync(boolean bool,
String result) {
Logger.debug("Is ContactUpdated FetchContacts --> "
+ bool);
setMatchedStatusToFalse();
AppPreferenceManager.getInstance().setContactUpdate(bool);
Intent roomIntent = new Intent();
roomIntent
.setAction("com.advisualinc.echo.fetch.local_contacts");
ApplicationController.getInstance().sendBroadcast(roomIntent);
}
});
test.execute();
}
catch (JSONException e)
{
e.printStackTrace();
}
realmServer.close();
}
public static void refreshingContactsDB()
{
Thread background = new Thread(new Runnable()
{
public void run()
{
realmFresh = Realm.getInstance(ApplicationController.getInstance());
createCountryDetailsArrayModel();
R_LocalContactDB rCont;
TelephonyManager tm = (TelephonyManager) ApplicationController.getInstance()
.getSystemService(Context.TELEPHONY_SERVICE);
String simCountryISO = tm.getSimCountryIso();
for (int i = 0; i < countryDetailsList.size(); i++)
{
if (simCountryISO.equalsIgnoreCase(countryDetailsList.get(i)
.getCode()))
{
dialCodePrefix = countryDetailsList.get(i).getDial_code();
}
}
AppPreferenceManager.getInstance().setContactUpdate(false);
Logger.debug("Contact Update Refreshing Contact Started -->");
ContentResolver cr = ApplicationController.getInstance()
.getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PROJECTION, null, null, null);
String duplicateName = "";
String duplicatePhone = "";
if (phones.getCount() > 0)
{
final int nameIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
final int numberIndex = phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
while (phones.moveToNext())
{
String name = phones.getString(nameIndex);
String phoneNo = phones.getString(numberIndex);
if (phoneNo != null && !phoneNo.isEmpty())
{
phoneNo = phoneNo.replace(" ", "");
phoneNo = phoneNo.replace("(", "");
phoneNo = phoneNo.replace(")", "");
phoneNo = phoneNo.replace("-", "");
phoneNo = phoneNo.replace("\u00a0", "");
phoneNo = phoneNo.replace("\u202c", "");
phoneNo = phoneNo.replace("\u2011", "");
phoneNo = phoneNo.replace("\u202a", "");
phoneNo = phoneNo.replace("*", "");
phoneNo = phoneNo.replace("#", "");
if (phoneNo.length() >= 5)
{
if (name.equalsIgnoreCase(duplicateName) && phoneNo.equalsIgnoreCase(duplicatePhone)) {
continue;
}
duplicateName = name;
duplicatePhone = phoneNo;
String formattedPhoneNumber;
formattedPhoneNumber = parseNumber(phoneNo);
R_LocalContactDB realmResults = realmFresh.where(R_LocalContactDB.class).equalTo("phone", formattedPhoneNumber).findFirst();
Logger.debug("Size: " + realmResults);
R_LocalContactDB rContacts = new R_LocalContactDB(null, null, false, 0);
if (realmResults == null)
{
i++;
realmFresh.beginTransaction();
rCont = realmFresh.copyToRealm(rContacts);
rCont.setName(name);
rCont.setPhone(formattedPhoneNumber);
rCont.setStatus(0);
rCont.setMatchedWithRecent(true);
// Logger.debug("New Size: " + query.size());
realmFresh.commitTransaction();
}
else if( realmResults.isValid())
{
realmFresh.beginTransaction();
if (!name.equalsIgnoreCase(realmResults.getName()))
{
realmResults.setName(name);
}
realmResults.setMatchedWithRecent(true);
// Logger.debug("New Size Else Condition: " + query.size());
realmFresh.commitTransaction();
}
}
}
}
ContactsSyncService.contactUpdated = false;
}
realmFresh.close();
deleteExtraContacts();
getNumbersFromDBAndUpdate();
}
});
background.start();
}
I want to retrieve multiple numbers from one contacts which is already saved to phone.
So how to read numbers of one contact programmatically in android?
I have created my own custom class for doing this , it may help you :
package com.android.addressbook.result;
import java.util.HashMap;
import android.graphics.Bitmap;
public class Contact {
String id = "";
String displayName = "";
String dateOfBirth = "";
String dateOfAnniversary = "";
String nickName = "";
String note = "";
Bitmap image = null;
HashMap<Integer, String> emails;
HashMap<Integer, String> phones;
HashMap<Integer, Address> addresses;
HashMap<Integer, Organization> organizations;
HashMap<Integer, String> im;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getDateOfBirth() {
return dateOfBirth;
}
public void setDateOfBirth(String dateOfBirth) {
this.dateOfBirth = dateOfBirth;
}
public String getDateOfAnniversary() {
return dateOfAnniversary;
}
public void setDateOfAnniversary(String dateOfAnniversary) {
this.dateOfAnniversary = dateOfAnniversary;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Bitmap getImage() {
return image;
}
public void setImage(Bitmap image) {
this.image = image;
}
public HashMap<Integer, String> getEmails() {
return emails;
}
public void setEmails(HashMap<Integer, String> emails) {
this.emails = emails;
}
public HashMap<Integer, String> getPhones() {
return phones;
}
public void setPhones(HashMap<Integer, String> phones) {
this.phones = phones;
}
public HashMap<Integer, Address> getAddresses() {
return addresses;
}
public void setAddresses(HashMap<Integer, Address> addresses) {
this.addresses = addresses;
}
public HashMap<Integer, Organization> getOrganizations() {
return organizations;
}
public void setOrganizations(HashMap<Integer, Organization> organizations) {
this.organizations = organizations;
}
public HashMap<Integer, String> getIm() {
return im;
}
public void setIm(HashMap<Integer, String> im) {
this.im = im;
}
/******************************************************************************************/
static class Address {
private String postBox = "";
private String street = "";
private String city = "";
private String state = "";
private String postalCode = "";
private String country = "";
private String neighborhood = "";
public String getPostBox() {
return postBox;
}
public void setPostBox(String postBox) {
this.postBox = postBox;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPostalCode() {
return postalCode;
}
public void setPostalCode(String postalCode) {
this.postalCode = postalCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getNeighborhood() {
return neighborhood;
}
public void setNeighborhood(String neighborhood) {
this.neighborhood = neighborhood;
}
#Override
public String toString() {
return "Address [postBox=" + postBox + "\n street=" + street
+ "\n city=" + city + "\n state=" + state + "\n postalCode="
+ postalCode + "\n country=" + country + "\n neighborhood="
+ neighborhood + "]";
}
}
/**********************************/
static class Organization {
private String company = "";
private String jobTitle = "";
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getJobTitle() {
return jobTitle;
}
public void setJobTitle(String jobTitle) {
this.jobTitle = jobTitle;
}
#Override
public String toString() {
return "Organization [company=" + company + "\n jobTitle="
+ jobTitle + "]";
}
}
/**********************************/
public static class Email_TYPE {
// Email Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
public static final int MOBILE = 4;
}
/**********************************/
public static class PHONE_TYPE {
// / Phone Type
public static final int HOME = 1;
public static final int MOBILE = 2;
public static final int WORK = 3;
public static final int FAX_WORK = 4;
public static final int FAX_HOME = 5;
public static final int PAGER = 6;
public static final int OTHER = 7;
}
/**********************************/
public static class ADDRESS_TYPE {
// / Address Type
public static final int HOME = 1;
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class ORGANIZATION_TYPE {
// / Organization Type
public static final int WORK = 2;
public static final int OTHER = 3;
}
/**********************************/
public static class IM_TYPE {
public static final int CUSTOM = -1;
public static final int AIM = 0;
public static final int MSN = 1;
public static final int YAHOO = 2;
public static final int SKYPE = 3;
public static final int QQ = 4;
public static final int GOOGLE_TALK = 5;
public static final int ICQ = 6;
public static final int JABBER = 7;
public static final int NETMEETING = 8;
}
#Override
public String toString() {
return "Contact [id=" + id + "\n displayName=" + displayName
+ "\n dateOfBirth=" + dateOfBirth + "\n dateOfAnniversary="
+ dateOfAnniversary + "\n nickName=" + nickName + "\n note="
+ note + "\n image=" + image + "\n emails=" + emails
+ "\n phones=" + phones + "\n addresses=" + addresses
+ "\n organizations=" + organizations + "\n im=" + im + "]";
}
}
PhoneContact.java
package com.android.addressbook.result;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import com.android.addressbook.result.Contact.Address;
import com.android.addressbook.result.Contact.Organization;
public class PhoneContact {
ContentResolver cr;
List<Contact> contactList;
Context context;
public PhoneContact(Context context) {
this.context = context;
cr = context.getContentResolver();
contactList = new ArrayList<Contact>();
readContacts();
}
public void readContacts() {
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
null, null, null);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Contact contact = new Contact();
// Get contact id (id)
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
contact.setId(id);
// Get contact name (displayName)
String displayName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
contact.setDisplayName(displayName);
// Get BirthDay (dateOfBirth)
Uri URI_DOB = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOB = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_BIRTHDAY;
String[] SELECTION_ARRAY_DOB = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOB = cr.query(URI_DOB, null, SELECTION_DOB,SELECTION_ARRAY_DOB, null);
int indexDob = currDOB.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOB.moveToNext()) {
String dobStr = currDOB.getString(indexDob);
contact.setDateOfBirth(dobStr);
}
currDOB.close();
// Get Anniversary (dateOfAnniversary)
Uri URI_DOA = ContactsContract.Data.CONTENT_URI;
String SELECTION_DOA = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ? AND "
+ ContactsContract.CommonDataKinds.Event.TYPE
+ "="
+ ContactsContract.CommonDataKinds.Event.TYPE_ANNIVERSARY;
String[] SELECTION_ARRAY_DOA = new String[] {
id,
ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE };
Cursor currDOA = cr.query(URI_DOA, null, SELECTION_DOA,SELECTION_ARRAY_DOA, null);
int indexDoa = currDOA.getColumnIndex(ContactsContract.CommonDataKinds.Event.START_DATE);
if (currDOA.moveToNext()) {
String doaStr = currDOA.getString(indexDoa);
contact.setDateOfAnniversary(doaStr);
}
currDOA.close();
// Get Nick Nmae(nickName)
Uri URI_NICK_NAME = ContactsContract.Data.CONTENT_URI;
String SELECTION_NICK_NAME = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NICK_NAME = new String[] {
id,
ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE };
Cursor currNickName = cr.query(URI_NICK_NAME, null,
SELECTION_NICK_NAME, SELECTION_ARRAY_NICK_NAME,
null);
int indexNickName = currNickName.getColumnIndex(ContactsContract.CommonDataKinds.Nickname.NAME);
if (currNickName.moveToNext()) {
String nickNameStr = currNickName
.getString(indexNickName);
contact.setNickName(nickNameStr);
}
currNickName.close();
// GetNote(note)
Uri URI_NOTE = ContactsContract.Data.CONTENT_URI;
String SELECTION_NOTE = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_NOTE = new String[] {
id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE };
Cursor currNote = cr.query(URI_NOTE, null, SELECTION_NOTE,SELECTION_ARRAY_NOTE, null);
int indexNote = currNote.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE);
if (currNote.moveToNext()) {
String noteStr = currNote.getString(indexNote);
contact.setNote(noteStr);
}
currNote.close();
// Get User Image (image)
Uri URI_PHOTO = ContactsContract.Data.CONTENT_URI;
String SELECTION_PHOTO = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_PHOTO = new String[] {
id,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE };
Cursor currPhoto = cr.query(URI_PHOTO, null,SELECTION_PHOTO, SELECTION_ARRAY_PHOTO, null);
int indexPhoto = currPhoto.getColumnIndex(ContactsContract.CommonDataKinds.Photo.PHOTO);
while (currPhoto.moveToNext()) {
byte[] photoByte = currPhoto.getBlob(indexPhoto);
if (photoByte != null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
// Getting Caching directory
File cacheDirectory = context.getCacheDir();
// Temporary file to store the contact image
// File tmpFile = new File(cacheDirectory.getPath()
// + "/image_"+id+".png");
File tmpFile = new File(cacheDirectory.getPath()+ "/image_.png");
// The FileOutputStream to the temporary file
try {
FileOutputStream fOutStream = new FileOutputStream(tmpFile);
// Writing the bitmap to the temporary file as png file
bitmap.compress(Bitmap.CompressFormat.PNG, 100,fOutStream);
// Flush the FileOutputStream
fOutStream.flush();
// Close the FileOutputStream
fOutStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// String photoPath = tmpFile.getPath();
contact.setImage(bitmap);
}
}
currPhoto.close();
// Get Email and Type.... (<HashMap<Integer, String> emails)
Uri URI_EMAIL = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
String SELECTION_EMAIL = ContactsContract.CommonDataKinds.Email.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_EMAIL = new String[] { id };
Cursor emailCur = cr.query(URI_EMAIL, null,SELECTION_EMAIL, SELECTION_ARRAY_EMAIL, null);
int indexEmail = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
int indexEmailType = emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE);
if (emailCur.getCount() > 0) {
HashMap<Integer, String> emailMap = new HashMap<Integer, String>();
while (emailCur.moveToNext()) {
// This would allow you get several email addresses,
// if the email addresses were stored in an array
String emailStr = emailCur.getString(indexEmail);
String emailTypeStr = emailCur.getString(indexEmailType);
emailMap.put(Integer.parseInt(emailTypeStr),emailStr);
}
contact.setEmails(emailMap);
}
emailCur.close();
// Get Phone Number....(HashMap<Integer, String>phones)
Uri URI_PHONE = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String SELECTION_PHONE = ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?";
String[] SELECTION_ARRAY_PHONE = new String[] { id };
Cursor currPhone = cr.query(URI_PHONE, null,SELECTION_PHONE, SELECTION_ARRAY_PHONE, null);
int indexPhoneNo = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int indexPhoneType = currPhone.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE);
if (currPhone.getCount() > 0) {
HashMap<Integer, String> phoneMap = new HashMap<Integer, String>();
while (currPhone.moveToNext()) {
String phoneNoStr = currPhone.getString(indexPhoneNo);
String phoneTypeStr = currPhone.getString(indexPhoneType);
phoneMap.put(Integer.parseInt(phoneTypeStr),phoneNoStr);
}
contact.setPhones(phoneMap);
}
currPhone.close();
// Get Postal Address....(HashMap<Integer, Address> addresses)
Uri URI_ADDRESS = ContactsContract.Data.CONTENT_URI;
String SELECTION_ADDRESS = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ADDRESS = new String[] {
id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE };
Cursor currAddr = cr.query(URI_ADDRESS, null,SELECTION_ADDRESS, SELECTION_ARRAY_ADDRESS, null);
int indexAddType = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE);
int indexStreet = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET);
int indexPOBox = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX);
int indexNeighbor = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.NEIGHBORHOOD);
int indexCity = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY);
int indexRegion = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION);
int indexPostCode = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE);
int indexCountry = currAddr
.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY);
if (currAddr.getCount() > 0) {
HashMap<Integer, Address> addressMap = new HashMap<Integer, Contact.Address>();
while (currAddr.moveToNext()) {
Contact.Address address = new Contact.Address();
String typeStr = currAddr.getString(indexAddType);
address.setStreet(currAddr.getString(indexStreet));
address.setNeighborhood(currAddr.getString(indexNeighbor));
address.setPostalCode(currAddr.getString(indexPostCode));
address.setPostBox(currAddr.getString(indexPOBox));
address.setCity(currAddr.getString(indexCity));
address.setState(currAddr.getString(indexRegion));
address.setCountry(currAddr.getString(indexCountry));
addressMap.put(Integer.parseInt(typeStr), address);
}
contact.setAddresses(addressMap);
}
currAddr.close();
// Get Organization (HashMap<Integer, Organization> organizations)
Uri URI_ORGNIZATION = ContactsContract.Data.CONTENT_URI;
String SELECTION_ORGNIZATION = ContactsContract.Data.CONTACT_ID
+ " = ? AND "
+ ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_ORGNIZATION = new String[] {
id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE };
Cursor currOrg = cr.query(URI_ORGNIZATION, null,
SELECTION_ORGNIZATION, SELECTION_ARRAY_ORGNIZATION,
null);
int indexOrgType = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TYPE);
int indexOrgName = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA);
int indexOrgTitle = currOrg
.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE);
if (currOrg.getCount() > 0) {
HashMap<Integer, Organization> orgMap = new HashMap<Integer, Contact.Organization>();
while (currOrg.moveToNext()) {
Contact.Organization organization = new Organization();
String orgTypeStr = currOrg.getString(indexOrgType);
organization.setCompany(currOrg.getString(indexOrgName));
organization.setJobTitle(currOrg.getString(indexOrgTitle));
orgMap.put(Integer.parseInt(orgTypeStr),organization);
}
contact.setOrganizations(orgMap);
}
currOrg.close();
// Get Instant Messenger..... (HashMap<Integer, String> im)
Uri URI_IM = ContactsContract.Data.CONTENT_URI;
String SELECTION_IM = ContactsContract.Data.CONTACT_ID
+ " = ? AND " + ContactsContract.Data.MIMETYPE
+ " = ?";
String[] SELECTION_ARRAY_IM = new String[] {
id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE };
Cursor currIM = cr.query(URI_IM, null, SELECTION_IM,SELECTION_ARRAY_IM, null);
int indexName = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA);
int indexType = currIM
.getColumnIndex(ContactsContract.CommonDataKinds.Im.PROTOCOL);
if (currIM.getCount() > 0) {
HashMap<Integer, String> imMap = new HashMap<Integer, String>();
while (currIM.moveToNext()) {
String imNameStr = currIM.getString(indexName);
String imTypeStr = currIM.getString(indexType);
imMap.put(Integer.parseInt(imTypeStr), imNameStr);
}
contact.setIm(imMap);
}
currIM.close();
/*****************************************/
contactList.add(contact);
}
}
}
cur.close();
}
public List<Contact> getAllContacts() {
return contactList;
}
}
and finally use this in your activity :
PhoneContact pCon = new PhoneContact(context);
List<Contact> conList = pCon.getAllContacts();
HashMap<Integer, String> phones = conList.get(0).getPhones();
String home = phones.get(Contact.PHONE_TYPE.HOME);
here is the tutorial. i think it may help you. check once
Working With Android Contacts
Hope this Snippet can help you out
String id , name;
ContentResolver cr = getContentResolver();
String sortOrder = ContactsContract.Contacts.DISPLAY_NAME + " COLLATE LOCALIZED ASC";
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, sortOrder);
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
name = cur.getString( cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
Log.i(tag, "Id is "+ id+"\t Name is"+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);
// this second loop will retrieve all the contact numbers for a paricular contact id
while (pCur.moveToNext()) {
// Do something with phones
int phNumber = pCur.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.NUMBER);
String phn = pCur.getString(phNumber);
Log.i("phn number", phn);
}
pCur.close();
}
}
}
I need to work with SQLite in Android.
So, do I have to download any SQLite Administration (like MySql) or it is already in device memory?
All you need is already installed. To inspect the database during development you can use the sqlite3 tool. It is installed in the emulator.
You Don't need to download anything.its already there.
You don't have to do anything besides using the built-in tools in the Android SDK. For more information please have a look at the sqlite documentation
Basically you can use Java code to create databases, insert records into them, modify them etc.
If you want a graphical way to work on the databases, simply use Eclipse's DDMS View to navigate into your app's databases folder. From there, download the database on your computer and open it with one of the many sqlite applications available.
------------------------------------------------------------------------
Sqlite
----------------------------------------------------------------------
// instance varieable
Button btn_insert,btn_update,btn_show,btn_delete,btn_search;
EditText edit_no,edit_name,edit_mark;
Cursor c;
Context context=this;
SQLiteDatabase db;
StringBuffer sb;
init
edit_no= (EditText) findViewById(R.id.edit_no);
edit_name= (EditText) findViewById(R.id.edit_name);
edit_mark= (EditText) findViewById(R.id.edit_mark);
btn_insert= (Button) findViewById(R.id.btn_insert);
btn_update= (Button) findViewById(R.id.btn_update);
btn_show= (Button) findViewById(R.id.btn_show);
btn_delete= (Button) findViewById(R.id.btn_delete);
btn_search= (Button) findViewById(R.id.btn_search);
db=openOrCreateDatabase("topstech",context.MODE_PRIVATE,null);
db.execSQL("create table if not exists register(no varchar2(20),name varchar2(20),mark varchar2(20))");
btn_insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (edit_no.getText().toString().trim().length() == 0) {
edit_no.setError("Enter Your No");
return;
} else if (edit_name.getText().toString().trim().length() == 0) {
edit_name.setError("Enter Your Name");
return;
} else if (edit_mark.getText().toString().trim().length() == 0) {
edit_mark.setError("Enter Your Mark");
return;
} else {
db.execSQL("insert into register values('" + edit_no.getText().toString() + "','" + edit_name.getText().toString() + "','" + edit_mark.getText().toString() + "')");
Toast.makeText(context, "Record Successfully Inserted...", Toast.LENGTH_SHORT).show();
Clear();
}
}
});
btn_show.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
c=db.rawQuery("select * from register",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
sb.append(c.getString(c.getColumnIndex("no"))+"\t");
sb.append(c.getString(c.getColumnIndex("name"))+"\t");
sb.append(c.getString(c.getColumnIndex("mark"))+"\n");
}while (c.moveToNext());
Toast.makeText(MainActivity.this, ""+sb, Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(MainActivity.this, "Empty Record...", Toast.LENGTH_SHORT).show();
}
}
});
btn_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
db.execSQL("delete from register where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Deleted...", Toast.LENGTH_SHORT).show();
Clear();
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_search.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
edit_name.setText(c.getString(c.getColumnIndex("name")));
edit_mark.setText(c.getString(c.getColumnIndex("mark")));
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
btn_update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
if (edit_no.getText().toString().trim().length() == 0)
{
edit_no.setError("Enter Your No");
return;
}
else
{
c=db.rawQuery("select * from register where no='"+edit_no.getText().toString()+"'",null);
sb=new StringBuffer();
if(c.moveToFirst())
{
do
{
if (edit_name.getText().toString().trim().length() == 0)
{
edit_name.setError("Enter Your Name");
return;
}
else if (edit_mark.getText().toString().trim().length() == 0)
{
edit_mark.setError("Enter Your Mark");
return;
}
else
{
//Syntex:-
// db.execSQL("update tablename set col_name='" +edit_name+"' where no='" + no+ "'");
db.execSQL("update register set name='"+edit_name.getText().toString()+"',mark='"+edit_mark.getText().toString()+"' where no='"+edit_no.getText().toString()+"'");
Toast.makeText(MainActivity.this, "1 Record Is Updated...", Toast.LENGTH_SHORT).show();
Clear();
}
}while (c.moveToNext());
}
else
{
Toast.makeText(MainActivity.this, "Record Not Found...", Toast.LENGTH_SHORT).show();
Clear();
}
}
}
});
}
-----------------------------------------
Upload Image ANd Fetch Device Contact JSON ARRAY
------------------------------------------
Upload Image Using Retrofit
#Multipart
#POST("addDocument")
Call<AddDocumentsResponse> doAddDocuments(#Header("Authorization") String token, #Part List<MultipartBody.Part> files, #PartMap Map<String, RequestBody> map);
private void uploadDocuments() {
if (Utility.checkInternetConnection(InsurenceActivity.this)) {
ArrayList<MultipartBody.Part> multipart = new ArrayList<>();
Map<String, RequestBody> map = new HashMap<>();
map.put("document_type", RequestBody.create(MediaType.parse("text/plain"), "insurance"));
map.put("expiry_date", RequestBody.create(MediaType.parse("text/plain"), str_select_date));
map.put("photo_id_type", RequestBody.create(MediaType.parse("text/plain"), ""));
multipart.add(Utility.prepareFilePart(InsurenceActivity.this, "document_file", picturePath));
messageUtil.showProgressDialog(InsurenceActivity.this);
Call<AddDocumentsResponse> registerResponseCall = ApiClient.getApiInterface().doAddDocuments(fastSave.getString(Constant.ACCESS_TOKEN), multipart, map);
Log.d("request","---- Request -----"+map.toString());
registerResponseCall.enqueue(new Callback<AddDocumentsResponse>() {
#Override
public void onResponse(Call<AddDocumentsResponse> call, Response<AddDocumentsResponse> response) {
if (response.code() == 200) {
if (response.body().getStatus().equalsIgnoreCase("fail"))
{
messageUtil.hideProgressDialog();
messageUtil.showErrorToast(response.body().getMessage());
return;
}
if (response.body().getStatus().equalsIgnoreCase("success"))
{
Log.d("response","---- Respons -----"+new Gson().toJson(response));
messageUtil.hideProgressDialog();
messageUtil.showSuccessToast(response.body().getMessage());
str_select_date = str_select_date;
picturePath = null;
Log.d("TAG", "success:............... " + new Gson().toJson(response));
finish();
}
}
}
#Override
public void onFailure(Call<AddDocumentsResponse> call, Throwable t) {
messageUtil.hideProgressDialog();
messageUtil.showErrorToast("Something went wrong");
}
});
} else {
Toast.makeText(this, R.string.no_internet_connection, Toast.LENGTH_SHORT).show();
}
}
public static MultipartBody.Part prepareFilePart(Context context, String partName, String filePath) {
if(filePath!=null) {
File file = new File(filePath);
Log.d("TAG", "prepareFilePart: " + filePath);
// RequestBody requestBody = RequestBody.create(MediaType.parse(getContentResolver().getType(Uri.fromFile(file))), file);
// Libaray Required
RequestBody requestBody = RequestBody.create(MediaType.parse("image/*"), file);
// Multipart Camera and Gallery
// RequestBody requestBody = RequestBody.create(MediaType.parse(context.getContentResolver().getType(FileProvider.getUriForFile(context, "com.", file))), file);
return MultipartBody.Part.createFormData(partName, file.getName(), requestBody);
}
else {
return MultipartBody.Part.createFormData(partName,"");
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
CropImage.ActivityResult result = CropImage.getActivityResult(data);
if (resultCode == RESULT_OK) {
Uri resultUri = result.getUri();
ll_profile_file.setVisibility(View.GONE);
img_photo_file.setVisibility(VISIBLE);
img_photo_file.setImageURI(resultUri);
picturePath = resultUri.getPath();
} else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
}
}
}
Fetch Device Contact Fast
ArrayList<Contact> listContacts;
listContacts = new ContactFetcher(this).fetchAll();
public class ContactPhone {
public String number;
public String type;
public ContactPhone(String number, String type) {
this.number = number;
this.type = type;
}
}
public class ContactFetcher {
private final Context context;
public ContactFetcher(Context c) {
this.context = c;
}
public ArrayList<Contact> fetchAll() {
String[] projectionFields = new String[]{
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
};
ArrayList<Contact> listContacts = new ArrayList<>();
CursorLoader cursorLoader = new CursorLoader(context,
ContactsContract.Contacts.CONTENT_URI,
projectionFields, // the columns to retrieve
null, // the selection criteria (none)
null, // the selection args (none)
null // the sort order (default)
);
Cursor c = cursorLoader.loadInBackground();
final Map<String, Contact> contactsMap = new HashMap<>(c.getCount());
if (c.moveToFirst()) {
int idIndex = c.getColumnIndex(ContactsContract.Contacts._ID);
int nameIndex = c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
do {
String contactId = c.getString(idIndex);
String contactDisplayName = c.getString(nameIndex);
Contact contact = new Contact(contactId, contactDisplayName);
contactsMap.put(contactId, contact);
listContacts.add(contact);
} while (c.moveToNext());
}
c.close();
matchContactNumbers(contactsMap);
matchContactEmails(contactsMap);
return listContacts;
}
public void matchContactNumbers(Map<String, Contact> contactsMap) {
// Get numbers
final String[] numberProjection = new String[]{
Phone.NUMBER,
Phone.TYPE,
Phone.CONTACT_ID,
};
Cursor phone = new CursorLoader(context,
Phone.CONTENT_URI,
numberProjection,
null,
null,
null).loadInBackground();
if (phone.moveToFirst()) {
final int contactNumberColumnIndex = phone.getColumnIndex(Phone.NUMBER);
final int contactTypeColumnIndex = phone.getColumnIndex(Phone.TYPE);
final int contactIdColumnIndex = phone.getColumnIndex(Phone.CONTACT_ID);
while (!phone.isAfterLast()) {
final String number = phone.getString(contactNumberColumnIndex);
final String contactId = phone.getString(contactIdColumnIndex);
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
final int type = phone.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
CharSequence phoneType = Phone.getTypeLabel(context.getResources(), type, customLabel);
contact.addNumber(number, phoneType.toString());
phone.moveToNext();
}
}
phone.close();
}
public void matchContactEmails(Map<String, Contact> contactsMap) {
// Get email
final String[] emailProjection = new String[]{
Email.DATA,
Email.TYPE,
Email.CONTACT_ID,
};
Cursor email = new CursorLoader(context,
Email.CONTENT_URI,
emailProjection,
null,
null,
null).loadInBackground();
if (email.moveToFirst()) {
final int contactEmailColumnIndex = email.getColumnIndex(Email.DATA);
final int contactTypeColumnIndex = email.getColumnIndex(Email.TYPE);
final int contactIdColumnsIndex = email.getColumnIndex(Email.CONTACT_ID);
while (!email.isAfterLast()) {
final String address = email.getString(contactEmailColumnIndex);
final String contactId = email.getString(contactIdColumnsIndex);
final int type = email.getInt(contactTypeColumnIndex);
String customLabel = "Custom";
Contact contact = contactsMap.get(contactId);
if (contact == null) {
continue;
}
CharSequence emailType = Email.getTypeLabel(context.getResources(), type, customLabel);
contact.addEmail(address, emailType.toString());
email.moveToNext();
}
}
email.close();
}
public class ContactEmail {
public String address;
public String type;
public ContactEmail(String address, String type) {
this.address = address;
this.type = type;
}
}
public class Contact {
public String id;
public String name;
public ArrayList<ContactEmail> emails;
public ArrayList<ContactPhone> numbers;
public Contact(String id, String name) {
this.id = id;
this.name = name;
this.emails = new ArrayList<ContactEmail>();
this.numbers = new ArrayList<ContactPhone>();
}
#Override
public String toString() {
String result = name;
if (numbers.size() > 0) {
ContactPhone number = numbers.get(0);
result += " (" + number.number + " - " + number.type + ")";
}
if (emails.size() > 0) {
ContactEmail email = emails.get(0);
result += " [" + email.address + " - " + email.type + "]";
}
return result;
}
public void addEmail(String address, String type) {
emails.add(new ContactEmail(address, type));
}
public void addNumber(String number, String type) {
numbers.add(new ContactPhone(number, type));
}
JSON ARRAY
Model model = new Model();
ArrayList<Model> contacts_arraylist=new ArrayList<>();
for (int i = 0; i < 50; i++)
{
model.setName("sanjay"+i);
model.setEmails("sanjay#gmail.com"+i);
model.setNumbers("89689527"+i);
contacts_arraylist.add(model);
}
JSONArray personarray=new JSONArray();
for (int j = 0; j < contacts_arraylist.size(); j++)
{
JSONObject person1 = new JSONObject();
try {
if(contacts_arraylist.get(j).getName()!=null)
{
person1.put("name", contacts_arraylist.get(j).getName());
}
else {
person1.put("name","");
}
if(contacts_arraylist.get(j).getEmails().length()>0)
{
person1.put("email", contacts_arraylist.get(j).getEmails());
}
else {
person1.put("email", "");
}
if(contacts_arraylist.get(j).getNumbers().length()>0)
{
person1.put("mobile_number", contacts_arraylist.get(j).getNumbers());
}
else {
person1.put("mobile_number", "");
}
personarray.put(person1);
} catch (JSONException e)
{
e.printStackTrace();
}
}
txt_array.setText(personarray.toString());
System.out.println("jsonString:---- " + personarray.toString());
}