How to get the Contact Id and Group - android

how can i get the Contact ID and Contact group? i have used the following code which gives me the name and phone any all other info but not the id or the group
public void ExportContacts() {
vCard = new ArrayList<String>();
cursor = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
int ss = cursor.getCount();
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
cursor.moveToNext();
}
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor)
{
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
String _id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "_ID");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
} catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
i want to put the ID and the Group name in the vCard that i write in file. can any one help?

Depending on which ID you want, you can use this or this for the ID field.
Group name is potentially somewhat messier: this is the row for group title, which may be what you need, but you probably need to do the appropriate error checking in case there isn't a group defined.
EDIT: Group ID you can find here.

Related

Android - Contact photo from connection

When a contact has a connection, like Whatsapp or Skype, and that contact hasn't a photo, the Whatsapp or Skype photo appears.
How obtain the connection photo if the contact photo hasn't a photo?
public byte[] getPhoto(String contactId) {
Uri contactUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.valueOf(contactId));
Uri photoUri = Uri.withAppendedPath(contactUri, ContactsContract.Contacts.Photo.CONTENT_DIRECTORY);
try
{
Cursor c = getContentResolver().query(photoUri,
new String[] {ContactsContract.Contacts.Photo.PHOTO}, null, null, null);
try {
if (c.moveToFirst()) {
final byte[] image = c.getBlob(0);
final Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
c.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return new byte[0];
}
SOLVED
This method works correctly. The problem was in another part of the program. Sorry for the inconvenience and thank you to all.
First, note that a Whatsapp photo does not appear in your Contacts app, it only appears within the Whatsapp app, that's because it's a proprietary photo stored locally in the Whatsapp app and is not accessible to 3rd party apps.
I'm not sure about Skype, but if you do see a photo in the Contacts app, you should be able to access it via the API.
The code you've posted accessed the thumbnail-sized photo of the contact, it's possible that the contact has only a high-res photo and no thumbnail.
Try this code using ContactsContract.DisplayPhoto:
public InputStream openDisplayPhoto(long photoFileId) {
Uri displayPhotoUri = ContentUris.withAppendedId(DisplayPhoto.CONTENT_URI, photoKey);
try {
AssetFileDescriptor fd = getContentResolver().openAssetFileDescriptor(
displayPhotoUri, "r");
return fd.createInputStream();
} catch (IOException e) {
return null;
}
}
Also, this code will show you all photos stored for a contact, along with their RawContact ID source:
String[] projection = new String[] { CommonDataKinds.Photo.PHOTO_FILE_ID, CommonDataKinds.Photo.PHOTO, CommonDataKinds.Photo.RAW_CONTACT_ID };
String selection = Data.MIMETYPE + "='" + CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "' AND " + Data.CONTACT_ID + "=" + contactId;
Cursor c = resolver.query(Data.CONTENT_URI, projection, selection, null, null);
while (c != null && c.moveToNext()) {
Long photoId = c.getLong(0);
boolean hasPhoto = c.isNull(1);
Long rawContactId = c.getLong(2);
Log.d(TAG, "found photo: " + photoId + ", " + rawContactId + ", " + hasPhoto);
}

Android how to send multiple contacts are attached in single .vcf file and send to mail?

In my application, a number of contacts are attached to single .vcf file and that file sent to mail, try to this one all contacts data display in log cat, but unable to send all data attached to single .vcf file?
Anyone have an idea regarding this help me, please.
here is my code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
vCard = new ArrayList<String>();
Log.i("TAG one", "vfile" +vfile);
vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf";
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
}
private void getVcardString() {
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
Log.i("TAG two", "cursor" +cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
Log.i("Number of contacts", "cursorCount" +cursor.getCount());
for (int i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.i("TAG send contacts", "Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
}
StringBuffer s = new StringBuffer();
s.append( vCard.toString());
string = s.toString();
file = new File(string);
// Log.i("s", ""+s);
// Log.i("string", ""+string);
Log.i("file", ""+file);
} else {
Log.i("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", ""+lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
try {
AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
vCard.add(storage_path);
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void data() {
File filelocation = file;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
}
finally my issue is solved using like this
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
button = (Button) findViewById(R.id.send);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
data();
}
});
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
}
public static void getVcardString() {
String path = null;
String vfile = null;
vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
null, null, null);
phones.moveToFirst();
Log.i("Number of contacts", "cursorCount" +phones.getCount());
for(int i =0;i<phones.getCount();i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", " " +lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = mContext.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
filevcf = new File(path);
Log.i("file", "file" +filevcf);
}catch(Exception e1) {
e1.printStackTrace();
}
}
Log.i("TAG", "No Contacts in Your Phone");
}
protected void data() {
File filelocation = filevcf ;
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(Intent.EXTRA_EMAIL, "mail#gmail.com" );
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+filelocation.getAbsolutePath()));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
I successfully tested the following. Changes to your code are indicated with comments beginning with "CHANGE:". Don't forget to have android.permission.WRITE_EXTERNAL_STORAGE in your manifest.
public class MainActivity extends Activity {
private String vfile;
private Cursor cursor;
private ArrayList<String> vCard;
private String string;
private File file;
private String storage_path; //CHANGE: storage_path global
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vCard = new ArrayList<String>();
Log.i("TAG one", "vfile" + vfile);
vfile = "Contacts" + "_" + System.currentTimeMillis() + ".vcf";
/**
* This Function For Vcard And here i take one Array List in Which i
* store every Vcard String of Every Contact Here i take one Cursor and
* this cursor is not null and its count>0 than i repeat one loop up to
* cursor.getcount() means Up to number of phone contacts. And in Every
* Loop i can make vcard string and store in Array list which i declared
* as a Global. And in Every Loop i move cursor next and print log in
* logcat.
* */
getVcardString();
data(); //CHANGE: now calling data to send vCard intent
}
private void getVcardString() {
cursor = getContentResolver().
query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null, null, null, null);
Log.i("TAG two", "cursor" +cursor);
if (cursor != null && cursor.getCount() > 0) {
cursor.moveToFirst();
Log.i("Number of contacts", "cursorCount" +cursor.getCount());
for (int i = 0; i < cursor.getCount(); i++) {
get(cursor);
Log.i("TAG send contacts",
"Contact " + (i + 1) + "VcF String is" + vCard.get(i));
cursor.moveToNext();
}
// StringBuffer s = new StringBuffer(); CHANGE: not needed
// s.append( vCard.toString());
// string = s.toString();
// file = new File(string); //CHANGE: this is not what file should be
} else {
Log.i("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor) {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Log.i("lookupKey", ""+lookupKey);
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
try {
AssetFileDescriptor fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring); //CHANGE: added this, so log statement in above method doesn't generate error
// String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
//CHANGE: this is the path we need to get file for intent:
storage_path = getExternalFilesDir(null).toString() + File.separator + vfile;
Log.i("MainActivity", storage_path);
//CHANGE: this will create the file we need:
file = new File(getExternalFilesDir(null), vfile);
file.createNewFile(); //CHANGE
//CHANGE: this will create the stream we need:
FileOutputStream mFileOutputStream = new FileOutputStream(file, true);
mFileOutputStream.write(vcardstring.toString().getBytes());
mFileOutputStream.close(); //don't forget to close
// vCard.add(storage_path); //CHANGE: not needed
} catch (Exception e1) {
e1.printStackTrace();
}
}
private void data() {
// File filelocation = file; //CHANGE: not what we need
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("vnd.android.cursor.dir/email");
sharingIntent.setType("application/x-vcard");
//CHANGE: using correct path:
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(storage_path));
startActivity(Intent.createChooser(sharingIntent, "Send email"));
}
}

Android App high cpu-usage

I am programming a app that has to do a operation with high cpu usage on a longer time
the operation is startet like a service
but the android system kills the app because of the high cpu usage
so what can I do to reduce the cpu usage ?
and make the system not to stop my service ?
service :
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.os.IBinder;
import android.provider.ContactsContract;
public class backup_service extends Service {
int i;
int i2;
#Override
public void onCreate() {
try
{
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/dialog.db");
BufferedWriter out = new BufferedWriter(fstream);
out.write("on");
//Close the output stream
out.close();
backup();
}
catch (Exception x)
{
stopSelf();
}
}
#Override
public void onDestroy() {
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/dialog.db"));
stopSelf();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void backup()
{
util.deleteDir(new File("/data/data/contact.backup.alexander.fuchs/backup/"));
new File("/data/data/contact.backup.alexander.fuchs/backup/").mkdirs();
// get it
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
null, null, null, null);
if (cur.getCount() > 0) {
i = 0;
i2 = 0;
while (cur.moveToNext()) {
String id = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/id.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(id);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/name.txt");
out = new BufferedWriter(fstream);
out.write(name);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
if (Integer.parseInt(cur.getString(
cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
Cursor pCur = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = ?",
new String[]{id}, null);
while (pCur.moveToNext()) {
String number = pCur.getString(
pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/number.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(number);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
pCur.close();
Cursor emailCur = cr.query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{id}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(email);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/email_type.txt");
out = new BufferedWriter(fstream);
out.write(emailType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
emailCur.close();
String noteWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] noteWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, noteWhere, noteWhereParams, null);
if (noteCur.moveToFirst()) {
String note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/note.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(note);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
noteCur.close();
String addrWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] addrWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, null, null, null);
while(addrCur.moveToNext()) {
String poBox = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POBOX));
String street = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
String city = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.CITY));
String state = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.REGION));
String postalCode = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.POSTCODE));
String country = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.COUNTRY));
String type = addrCur.getString(
addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.TYPE));
// write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/pobox.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(poBox);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/street.txt");
out = new BufferedWriter(fstream);
out.write(street);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/city.txt");
out = new BufferedWriter(fstream);
out.write(city);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/state.txt");
out = new BufferedWriter(fstream);
out.write(state);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/postalcode.txt");
out = new BufferedWriter(fstream);
out.write(postalCode);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/country.txt");
out = new BufferedWriter(fstream);
out.write(country);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"addres_type.txt");
out = new BufferedWriter(fstream);
out.write(type);
//Close the output stream
out.close();
}
catch (Exception x)
{
}
}
addrCur.close();
String imWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] imWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Im.CONTENT_ITEM_TYPE};
Cursor imCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, imWhere, imWhereParams, null);
if (imCur.moveToFirst()) {
String imName = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.DATA));
String imType;
imType = imCur.getString(
imCur.getColumnIndex(ContactsContract.CommonDataKinds.Im.TYPE));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(imName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/im_type.txt");
out = new BufferedWriter(fstream);
out.write(imType);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
imCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,
ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,
null, orgWhere, orgWhereParams, null);
if (orgCur.moveToFirst()) {
String orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
String title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
String company = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.COMPANY));
String department = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DEPARTMENT));
//write
try
{
new File("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)).mkdirs();
FileWriter fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/orgName.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(orgName);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/title.txt");
out = new BufferedWriter(fstream);
out.write(title);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/company.txt");
out = new BufferedWriter(fstream);
out.write(company);
//Close the output stream
out.close();
fstream = new FileWriter("/data/data/contact.backup.alexander.fuchs/backup/"+String.valueOf(i)+"/department.txt");
out = new BufferedWriter(fstream);
out.write(department);
//Close the output stream
out.close();
}
catch(Exception x)
{
}
}
orgCur.close();
}
i++;
}
onDestroy();
}
}
}
You can try divide the operation into smaller pieces and place Thread.sleep() for a short time. If that's not enough try changing some code into loop like this:
Old code:
object.move(1000);
New code:
for (int i=0; i<100; i++) {
object.move(10);
Thread.sleep(10);
}
If the example move() operation takes more time if the given parameter is higher, the old code can cause your program non-responding. The new code will allow android to comunicate with your program during Thread.sleep(), so your app shoud not stop working.
#edit
As I can see in your code - you do have several while loops. Try placing Thread.sleep(10) inside them.
You're putting this code directly in a Service which runs on the main thread. You need to instead put it in a background thread. Consider using an IntentService instead or start a worker thread from your service.

get all .vcf file in a single folder

i am making .vcf file off all contacts stored in contacts list and save it in sdcard as well but all .vcf file are storing sepratly in my SDCARD , iwant to make a folder in side Sdcard and save all the .vcf file inside it...and finally get the path of folder and able to mail it in email id..so how to make a folder to save all .vcf file inside it if there are thousands of contacts in contact list of my device.
my code for making .vcf and save it in sdcard are below. pls modified on the same or provide some new idea...
private void getVcardString() {
int j=0;
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(cursor!=null&&cursor.getCount()>0)
{
cursor.moveToFirst();
for(int i =0;i<cursor.getCount();i++)
{
get(cursor);
Log.d("TAG", "Contact "+(i+1)+"VcF String is"+vCard.get(i));
publishProgress(Integer.toString(j));
j++;
cursor.moveToNext();
}
csv_status = true;
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
}
public void get(Cursor cursor)
{
vfile = "Contacts" + "_" + System.currentTimeMillis()+".vcf";
//String vfile = "Contacts"+".vcf";
//cursor.moveToFirst();
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = CsvSender.this.getContentResolver().openAssetFileDescriptor(uri, "r");
FileInputStream fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String vcardstring= new String(buf);
vCard.add(vcardstring);
String storage_path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
mFileOutputStream.write(vcardstring.toString().getBytes());
}catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}

Get attachment from unread MMS messages

I would like to get attachment from unread MMS messages, but the codes I have doesn't allow me to do so. How do I go about doing that?
Codes modified from here:
private void checkMMSMessages(){
// Create string arrays to store the queries later on
String[] columns = null;
String[] values = null;
// Calls the ContentResolver to query for columns with URI "content:mms"
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, null, null, null);
if(curPdu.moveToNext()){
//String read = curRead.getString(curRead.getColumnIndex("read"));
// Gets ID of message
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
// Gets thread ID of message
String thread_id = curPdu.getString(curPdu.getColumnIndex("thread_id"));
// Gets subject of message (if any)
String subject = curPdu.getString(curPdu.getColumnIndex("sub"));
// Gets date of message
String date = curPdu.getString(curPdu.getColumnIndex("date"));
String selectionAddr = new String ("msg_id = '" + id + "'");
Uri uriAddr = Uri.parse ("content://mms/" + id + "/addr");
Cursor curAddr = getContentResolver().query(uriAddr, null, null, null, null);
if(curAddr.moveToNext()){
String contact_id = curAddr.getString (curAddr.getColumnIndex ("contact_id"));
String address = curAddr.getString (curAddr.getColumnIndex ("address"));
String selectionPart = new String ("mid = '" + id + "'");
Cursor curPart = getContentResolver ().query(Uri.parse ("content://mms/part"), null, null, null, null);
//Cursor curPart = context.getContentResolver ().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
String contact_idd = curPart.getString(0);
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
//Toast.makeText(getApplicationContext(), "Retrieved MMS attachment", Toast.LENGTH_LONG);
}
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
Figured out myself, the codes are as follows:
private void checkMMSMessages() {
String[] columns = null;
String[] values = null;
String read = "read = 0";
Cursor curPdu = getContentResolver().query(Uri.parse("content://mms"), null, read, null, null);
if(curPdu.moveToNext()){
String id = curPdu.getString(curPdu.getColumnIndex("_id"));
Cursor curPart = getContentResolver().query(Uri.parse ("content://mms/" + id + "/part"), null, null, null, null);
while(curPart.moveToNext())
{
columns = curPart.getColumnNames();
if(values == null)
values = new String[columns.length];
for(int i=0; i< curPart.getColumnCount(); i++){
values[i] = curPart.getString(i);
}
if(values[3].equals("image/jpeg") || values[3].equals("image/bmp") ||
values[3].equals("image/gif") || values[3].equals("image/jpg") ||
values[3].equals("image/png"))
{
GetMmsAttachment(values[0],values[12]);
}
}
}
}
private void GetMmsAttachment(String _id, String _data)
{
Uri partURI = Uri.parse("content://mms/part/" + _id );
String filePath = "/sdcard/photo.jpg";
InputStream is = null;
OutputStream picFile = null;
Bitmap bitmap = null;
try {
is = getContentResolver().openInputStream(partURI);
bitmap = BitmapFactory.decodeStream(is);
picFile = new FileOutputStream(filePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 50, picFile);
picFile.flush();
picFile.close();
}
catch (Exception e)
{
e.printStackTrace();
//throw new MmsException(e);
}
}
I think he asked how to retrieve the attachment from the server, as it is written UNREAD mms... If you have the column ct_l how to get the data from that internet address?

Categories

Resources