How to store .vcf file in separate folder in internal SDCard - android

I am using following code to store vcf file that i am generating from code
I am able to generate vcf file
but it appears under root directory in SDcard
I want to store it under seperate folder
How do i meet to requirements? Plz help
Thanks you.
private void getVcardString() throws IOException {
final String vfile = "BackupCont" + currDate + ".vcf";
vCard = new ArrayList<String>();
cursor = getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
Cursor c = dbhandle.getContactsByIsChecked();
ArrayList<String> arrchk=new ArrayList<String>();
for(int cc=0;cc<c.getCount();cc++)
{
arrchk.add(c.getString(c.getColumnIndex("con_name")));
}
if (cursor != null && cursor.getCount() > 0) {
int i;
String new_path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/Folder_name";
// String path = "c:/";
File dir = new File(new_path);
if (!dir.exists())
dir.mkdirs();
String storage_path = Environment.getExternalStorageDirectory()+"/Folder_name"+vfile;
Toast.makeText(getApplicationContext(), storage_path,Toast.LENGTH_LONG).show();
FileOutputStream mFileOutputStream = new FileOutputStream(storage_path, false);
cursor.moveToFirst();
for (i = 0; i < cursor.getCount(); i++)
{
if(arrchk.contains(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))))
{
get(cursor);
cursor.moveToNext();
mFileOutputStream.write(vCard.get(i).toString().getBytes());
}
}
mFileOutputStream.close();
cursor.close();
Toast.makeText(getApplicationContext(), "Created...",Toast.LENGTH_LONG).show();
Uri uri=Uri.fromFile(new File(storage_path,""+vfile));
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("application/x-vcard");
sharingIntent.putExtra(android.content.Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
else
{
Log.d("TAG", "No Contacts in Your Phone");
}
}

String outputDirectory = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "subFolderName";
outputDirectory.mkdirs();
File outputFile = new File(outputDirectory, filename);
FileOutputStream fos = new FileOutputStream(outputFile);
You should also check Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) to ensure that the external storage is in fact available.

Related

How to programmatically set some images as invisible from the Gallery?

I need to make images invisible from my gallery and i see other answers on stackoverflow but did not work for me .
this how i done that programmatically .
public void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode,data);
if(resultCode== Activity.RESULT_OK){
if(requestCode==REQUEST_CAMERA){
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
Log.e(TAG, "image: "+ imageTemplateStr );
//CommonMethod.SaveImage(bmp);
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
}else if(requestCode==SELECT_FILE){
Uri selectedImageUri = data.getData();
if (null != selectedImageUri) {
// Get the path from the Uri
String path = getPathFromURI(selectedImageUri);
File file = new File(path);
Bitmap bmp = CommonMethod.compressImage(file, getContext());
Log.e(TAG, "onActivityResult --: "+ String.format("Size : %s", getReadableFileSize(file.length())));
mCustomerImage = CommonMethod.bitmapToByteArray(bmp);
imageTemplateStr = Base64.encodeToString(mCustomerImage, Base64.DEFAULT);
//CommonMethod.SaveImage(bmp);
Log.e(TAG, "image: "+ imageTemplateStr );
imageCustomer.setImageBitmap(bmp);
CommonMethod.SaveImage(bmp);
}
}
SaveImage Method :
public static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/safco_private_pics");
if (!myDir.exists()) {
myDir.mkdirs();
}
File newFile = new File(root,".nomedia");
try {
FileWriter writer = new FileWriter(newFile);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ())
file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
getPathFromURI method
public String getPathFromURI(Uri contentUri) {
String res = null;
String[] proj = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(contentUri, proj, null, null, null);
if (cursor.moveToFirst()) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
res = cursor.getString(column_index);
}
cursor.close();
return res;
}
Now by that code images from gallery are not shown but images from Camera are visible in gallery and also .nomedia file not created.
Images are stored in my folder that i created and also in DCIM/Camera folder . I do not know why
What is wrong can anybody help me . ?
If you want to save the image for temporarily then you can use following code
File outputDir = context.getCacheDir(); // context should be the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
Instead of
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/safco_private_pics");
For more details about cache dir read this: https://stackoverflow.com/a/6528104/7708305
But, If you want your file to be hidden and persisted on the permanent storage regardless of usage you can use following code.
File file = new File(root + "/.hidden_folder");
The dot(.) before the file/folder name makes it hidden.
let your image in hidden folder
//replace
File myDir = new File(root + "/safco_private_pics");
//with
File myDir = new File(root + "/.safco_private_pics");
put dot(.)before directory name it will create hidden directory and put your image in that directory

How to import the contacts from vcf file stored in sdcard programically in android

I stored the vcf file in Sdcard but now i have to import that vcf file in contacts programicaly
i have created the vcf file by following code
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
phones.moveToFirst();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones
.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
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);
String path = Environment.getExternalStorageDirectory()
.toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path,true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
by this contact.vcf is created in sdcard
-now i have to import this vcf file in contacts programicaly
and by using following code i have restore the vcf file
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, "text/x-vcard");
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
-but not syncing the contacts by using this code

how to save all contact from vcf file directly to phonememory in android device

I am made an android application which get contacts from vcf file and save to android device and the code is:
String tmptype = mime.getMimeTypeFromExtension("vcf");
final File file = new File(Environment.getExternalStorageDirectory().toString() + "/contacts.vcf");
Intent i = new Intent();
i.setDataAndType(Uri.fromFile(file), "text/x-vcard");
startActivity(i);
It saves all contacts into device
but problem is it wants userinterface to choose where to save.But I want directly save to PhoneMemory or Phonebook.I don't want any other option while inserting Contacts.I have search on web could not find any answer please help to find out this
public class VCardActivity extends Activity {
Cursor cursor;
ArrayList<String> vCard;
String vfile;
static Context mContext;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = VCardActivity.this;
getVCF();
}
public static void getVCF() {
final String vfile = "Contacts.vcf";
Cursor phones = mContext.getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
phones.moveToFirst();
for (int i = 0; i < phones.getCount(); i++) {
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
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);
String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path, true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
Add on Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Credit to: https://stackoverflow.com/a/12048639/2378691

Prevent adding duplicate contacts in a vcf file

I have copied the code from the below link to export contacts to a vcf file.it works fine but the problem is Every contact that has more than one phone number (a mobile and work number) are saved twice. And both of the numbers are in each duplicate contact, so they are getting duplicated. please help
Export the Contacts as VCF file
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null, null, null);
phones.moveToFirst();
for(int i =0;i<phones.getCount();i++)
{
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try
{
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
//private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
sdCard =new File(Environment.getExternalStorageDirectory() + "//yourdir//");
directory = new File (sdCard.getAbsolutePath());
directory.mkdirs();
file = new File(directory, vfile);
// String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(file,true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
//Log.d("Vcard", VCard);
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}}
Toast.makeText(this, "contacts copied to " + vfile,
Toast.LENGTH_SHORT).show();

export contacts from listview of my application

i want to copy just the checked contacts to sd card as a vcf file
Is there any way to copy the checked contacts from a list view to s d card ? i have made an app in which i can export contacts from the contacts menu but i want to export contacts from a list view and which are checked contacts.please kindly help. i have to submit a project.
itemsSelected = "Selected items: \n";
for (int i = 0; i < lstContacts.getCount(); i++) {
view = lstContacts.getChildAt(i);
check= (CheckBox)view.findViewById(R.id.cb2);
if (check.isChecked()) {
itemsSelected += lstContacts.getItemAtPosition(i) + "\n";
}
}
Finally i got the answer to this question.
in this,lv is the contactlist from listview. just copy this code and you can check the contacts which you want to copy to the sd card.
long [] ids = lv.getCheckedItemIds();
for(long id : ids) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[] { id + "" }, null);
phones.moveToFirst();
for(int i =0;i<phones.getCount();i++)
{
String lookupKey = phones.getString(phones.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try
{
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
fis = fd.createInputStream();
byte[] buf = new byte[(int) fd.getDeclaredLength()];
fis.read(buf);
String VCard = new String(buf);
//private File mPath = new File(Environment.getExternalStorageDirectory() + "//yourdir//");
sdCard =new File(Environment.getExternalStorageDirectory() + "//yourdir//");
directory = new File (sdCard.getAbsolutePath());
directory.mkdirs();
file = new File(directory, vfile);
// String path = Environment.getExternalStorageDirectory().toString() + File.separator + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(file,true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
//Log.d("Vcard", VCard);
}
catch (Exception e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}}
Toast.makeText(this, "contacts copied to " + vfile,
Toast.LENGTH_SHORT).show();

Categories

Resources