How to remove duplicate contacts in vcf file - android

Hi guys i have this code which i use to get contacts from the phone and store them in vcf format,the code works properly for contacts that have only one number but i keep getting duplicates for contacts with multiple numbers i.e contacts that have home number,work number e.t.c...any help will be appreciated.....this is my code below
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
public class Show_contacts 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.activity_main);
mContext = Show_contacts.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);
mFileOutputStream.close();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

We have to check lookupKey. It works for me.
Cursor cursor;
ArrayList<String> vCard;
Context mContext;
ArrayList<String> saveLkKey;
String vcfFile;
String currentTime;
String rootStorage;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.save_contact_fragment, container,
false);
mContext = getActivity();
rootStorage = Environment.getExternalStorageDirectory() + "/";
Time today = new Time(Time.getCurrentTimezone());
today.setToNow();
currentTime = today.monthDay + "" + (today.month + 1) + "" + today.year
+ "-" + today.format("%k%M%S") + "";
vcfFile = "myContacts" + currentTime + ".vcf";
Button btnSaveVcf = (Button) view.findViewById(R.id.btnSave1);
btnSaveVcf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getVCF(vcfFile);
}
});
return view;
}
public void getVCF(String vfile) {
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));
lookupKey = lookupKey.trim();
if (saveLkKey == null) {
saveLkKey = new ArrayList<String>();
saveLkKey.add(lookupKey);
} else {
if (isDuplicate(lookupKey)) {
phones.moveToNext();
continue;
} else {
saveLkKey.add(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);
String path = rootStorage + vfile;
FileOutputStream mFileOutputStream = new FileOutputStream(path,
true);
mFileOutputStream.write(VCard.toString().getBytes());
phones.moveToNext();
Log.d("Vcard", VCard);
mFileOutputStream.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
}
public boolean isDuplicate(String lkKey) {
for (String s : saveLkKey) {
if (s.equals(lkKey)) {
return true;
}
}
return false;
}

Related

java.lang.NullPointerException: at com.example.util.DBHelper.<init> [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I have a fragment called PopularFragment.java in that i am fetching images from server and then displaying them into recyclerview. Usually it works great but sometimes the app crashes with a NullPointerException.
PopularFragment:
package com.apphics.minimalwallpapers;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.adapter.AdapterImage;
import com.example.item.ItemPhotos;
import com.example.util.Constant;
import com.example.util.DBHelper;
import com.example.util.EndlessRecyclerViewScrollListener;
import com.example.util.JsonUtils;
import com.pnikosis.materialishprogress.ProgressWheel;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
public class PopularFragment extends Fragment {
DBHelper dbHelper;
GridLayoutManager lLayout;
RecyclerView recyclerView;
AdapterImage adapterImage;
ArrayList<ItemPhotos> arrayOfLatestImage;
SwipeRefreshLayout mSwipeRefreshLayout;
ProgressWheel pbar;
TextView txt_no;
int spaceInPixels = 10;
Boolean isOver = false;
public PopularFragment newInstance() {
PopularFragment fragment = new PopularFragment();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_latest, container, false);
pbar=(ProgressWheel) rootView.findViewById(R.id.progressBar1);
mSwipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.activity_main_swipe_refresh_layout);
mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
dbHelper = new DBHelper(getActivity().getApplicationContext());
arrayOfLatestImage=new ArrayList<ItemPhotos>();
lLayout = new GridLayoutManager(getActivity(), 2);
lLayout.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
#Override
public int getSpanSize(int position) {
return adapterImage.isHeader(position) ? lLayout.getSpanCount() : 1;
}
});
recyclerView = (RecyclerView)rootView.findViewById(R.id.recyclerView_latest);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(lLayout);
recyclerView.addOnScrollListener(new EndlessRecyclerViewScrollListener(lLayout) {
#Override
public void onLoadMore(int p, int totalItemsCount) {
arrayOfLatestImage.add(null);
adapterImage.notifyItemInserted(arrayOfLatestImage.size() - 1);
arrayOfLatestImage.remove(arrayOfLatestImage.size() - 1);
adapterImage.notifyItemRemoved(arrayOfLatestImage.size());
if(!isOver) {
// list_url.clear();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
}
}, 2000);
} else {
adapterImage.hideHeader();
//Toast.makeText(getActivity(), "No more data", Toast.LENGTH_SHORT).show();
}
}
});
mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
refreshContent();
}
});
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask(getActivity().getApplicationContext()).execute(Constant.POPULAR_URL);
} else {
arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
if(arrayOfLatestImage.size()==0) {
Toast.makeText(getActivity(), "Please connect to internet to load Images ", Toast.LENGTH_SHORT).show();
pbar.setVisibility(View.GONE);
} else {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
pbar.setVisibility(View.GONE);
}
}
return rootView;
}
private class MyTask extends AsyncTask<String, Void, String> {
private final WeakReference<Context> contextReference;
public MyTask(Context context) {
this.contextReference = new WeakReference<Context>(context);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
Context context = this.contextReference.get();
if(context != null) {
if (arrayOfLatestImage.size() == 0) {
pbar.setVisibility(View.VISIBLE);
}
}
}
#Override
protected String doInBackground(String... params) {
return JsonUtils.getJSONString(params[0]);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Context context = this.contextReference.get();
if(context != null) {
if (arrayOfLatestImage.size() == 0) {
pbar.setVisibility(View.INVISIBLE);
}
if (null == result || result.length() == 0) {
Toast.makeText(getActivity(), "Something Went Wrong! Please check your internet and reload", Toast.LENGTH_SHORT).show();
} else {
try {
JSONObject mainJson = new JSONObject(result);
JSONArray jsonArray = mainJson.getJSONArray(Constant.TAG_ROOT);
if (jsonArray.length() <= arrayOfLatestImage.size() + 40) {
isOver = true;
}
int a = arrayOfLatestImage.size();
int b;
b = 40;
JSONObject objJson = null;
for (int i = a; i < a + b; i++) {
objJson = jsonArray.getJSONObject(i);
String id = objJson.getString(Constant.TAG_WALL_ID);
String cid = objJson.getString(Constant.TAG_CAT_ID);
String img = objJson.getString(Constant.TAG_WALL_IMAGE);
String img_thumb = objJson.getString(Constant.TAG_WALL_IMAGE_THUMB);
String cat_name = objJson.getString(Constant.TAG_CAT_NAME);
String views = objJson.getString(Constant.TAG_WALL_VIEWS);
ItemPhotos objItem = new ItemPhotos(id, cid, img, img_thumb, cat_name, views);
dbHelper.addtoFavorite(objItem, "popular");
arrayOfLatestImage.add(objItem);
}
} catch (JSONException e) {
e.printStackTrace();
isOver = true;
}
setAdapterToListview();
}
}
}
}
public void setAdapterToListview() {
if(arrayOfLatestImage.size()<41) {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
} else {
adapterImage.notifyDataSetChanged();
}
//setExmptTextView();
}
/*private void setExmptTextView() {
if(adapterImage.getItemCount()==0) {
txt_no.setVisibility(View.VISIBLE);
} else{
txt_no.setVisibility(View.INVISIBLE);
}
}*/
public void showToast(String msg) {
Toast.makeText(getActivity(), msg, Toast.LENGTH_LONG).show();
}
#Override
public void onResume() {
//if(adapterImage!=null && adapterImage.getItemCount() > 0) {
// adapterImage.notifyDataSetChanged();
//setExmptTextView();
// }
super.onResume();
}
private void refreshContent() {
// TODO implement a refresh
recyclerView.getRecycledViewPool().clear();
adapterImage.notifyDataSetChanged();
arrayOfLatestImage.clear();
try{
if (JsonUtils.isNetworkAvailable(getActivity())) {
new MyTask(getActivity()).execute(Constant.POPULAR_URL);
} else {
arrayOfLatestImage = dbHelper.getAllDataPopular("popular");
if(arrayOfLatestImage.size()==0) {
Toast.makeText(getActivity(), "First Time Load Application from Internet ", Toast.LENGTH_SHORT).show();
} else {
adapterImage = new AdapterImage(getActivity(),arrayOfLatestImage);
recyclerView.setAdapter(adapterImage);
}
}
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
mSwipeRefreshLayout.setRefreshing(false); // Disables the refresh icon
}
}
DBHelper.java:
package com.example.util;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
import com.example.item.ItemAbout;
import com.example.item.ItemCategory;
import com.example.item.ItemGIF;
import com.example.item.ItemPhotos;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
public class DBHelper extends SQLiteOpenHelper {
private static String DB_NAME = "wallpaper.db";
private SQLiteDatabase db;
private final Context context;
private String DB_PATH;
String outFileName = "";
SharedPreferences.Editor spEdit;
public DBHelper(Context context) {
super(context, DB_NAME, null, 1);
this.context = context;
DB_PATH = "/data/data/" + context.getPackageName() + "/" + "databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
//------------------------------------------------------------
PackageInfo pinfo = null;
if (!dbExist) {
getReadableDatabase();
copyDataBase();
}
}
private boolean checkDataBase() {
File dbFile = new File(DB_PATH + DB_NAME);
return dbFile.exists();
}
private void copyDataBase() throws IOException {
InputStream myInput = context.getAssets().open(DB_NAME);
String outFileName = DB_PATH + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFileName);
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
public Cursor getData(String Query) {
String myPath = DB_PATH + DB_NAME;
Cursor c = null;
try {
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
c = db.rawQuery(Query, null);
} catch (Exception e) {
Log.e("Err", e.toString());
}
return c;
}
//UPDATE temp_dquot SET age='20',name1='--',rdt='11/08/2014',basic_sa='100000',plno='814',pterm='20',mterm='20',mat_date='11/08/2034',mode='YLY',dab_sa='100000',tr_sa='0',cir_sa='',bonus_rate='42',prem='5276',basic_prem='5118',dab_prem='100.0',step_rate='for Life',loyal_rate='0',bonus_rate='42',act_mat='1,88,000',mly_b_pr='448',qly_b_pr='1345',hly_b_pr='2664',yly_b_pr='5276' WHERE uniqid=1
public void dml(String Query) {
String myPath = DB_PATH + DB_NAME;
File file = new File(myPath);
if (file.exists() && !file.isDirectory())
if (db == null)
db = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
try {
db.execSQL(Query);
} catch (Exception e) {
Log.e("Error", e.toString());
}
}
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
public ArrayList<ItemPhotos> getAllData(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getAllDataPopular(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getAllDataShuffl(String table){
ArrayList<ItemPhotos> arrayList = new ArrayList<ItemPhotos>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
arrayList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemGIF> getAllDataGIF(){
ArrayList<ItemGIF> arrayList = new ArrayList<ItemGIF>();
Cursor cursor = getData("select * from gif");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String gid = cursor.getString(cursor.getColumnIndex("gid"));
String img = cursor.getString(cursor.getColumnIndex("image"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemGIF itemGIF = new ItemGIF(gid,img,views);
arrayList.add(itemGIF);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemCategory> getAllDataCat(String table){
ArrayList<ItemCategory> arrayList = new ArrayList<ItemCategory>();
Cursor cursor = getData("select * from '"+table+"'");
if(cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String tot_wall = cursor.getString(cursor.getColumnIndex("tot_wall"));
ItemCategory itemCategory = new ItemCategory(cid,cname,img,img_thumb,tot_wall);
arrayList.add(itemCategory);
cursor.moveToNext();
}
cursor.close();
}
return arrayList;
}
public ArrayList<ItemPhotos> getFavRow(String id, String table)
{
ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
// Select All Query
String selectQuery = "SELECT * FROM '"+table+"' WHERE pid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
dataList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public ArrayList<ItemGIF> getFavRowGIF(String id)
{
ArrayList<ItemGIF> dataList = new ArrayList<ItemGIF>();
// Select All Query
String selectQuery = "SELECT * FROM gif WHERE gid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String gid = cursor.getString(cursor.getColumnIndex("gid"));
String img = cursor.getString(cursor.getColumnIndex("image"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemGIF itemGIF = new ItemGIF(gid,img,views);
dataList.add(itemGIF);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public ArrayList<ItemPhotos> getCatList(String id, String table)
{
ArrayList<ItemPhotos> dataList = new ArrayList<ItemPhotos>();
// Select All Query
String selectQuery = "SELECT * FROM '"+table+"' WHERE cid="+"'"+id+"'";
Cursor cursor = getData(selectQuery);
if (cursor != null && cursor.getCount()>0) {
cursor.moveToFirst();
for (int i=0; i<cursor.getCount(); i++) {
String pid = cursor.getString(cursor.getColumnIndex("pid"));
String cid = cursor.getString(cursor.getColumnIndex("cid"));
String cname = cursor.getString(cursor.getColumnIndex("cname"));
String img = cursor.getString(cursor.getColumnIndex("img"));
String img_thumb = cursor.getString(cursor.getColumnIndex("img_thumb"));
String views = cursor.getString(cursor.getColumnIndex("views"));
ItemPhotos itemPhotos = new ItemPhotos(pid,cid,img,img_thumb,cname,views);
dataList.add(itemPhotos);
cursor.moveToNext();
}
cursor.close();
}
// return contact list
return dataList;
}
public void addtoFavorite(ItemPhotos itemPhotos, String table) {
dml("insert into '"+table+"' (pid,cid,cname,img,img_thumb,views) values ('"+itemPhotos.getId()+"','"+itemPhotos.getCatId()+"','"+itemPhotos.getCName()+"','"+itemPhotos.getImage()+"','"+itemPhotos.getImageThumb()+"','"+itemPhotos.getTotalViews()+"')");
}
public void addtoFavoriteGIF(ItemGIF itemGIF) {
dml("insert into gif (gid,image,views) values ('"+itemGIF.getId()+"','"+itemGIF.getImage()+"','"+itemGIF.getTotalViews()+"')");
}
public void addtoCatList(ItemCategory itemCategory, String table) {
dml("insert into '"+table+"' (cid,cname,img,img_thumb,tot_wall) values ('"+itemCategory.getId()+"','"+itemCategory.getName()+"','"+itemCategory.getImage()+"','"+itemCategory.getImageThumb()+"','"+itemCategory.getTotalWallpaper()+"')");
}
public void removeFav(String id) {
dml("delete from fav where pid = '"+id+"'");
}
public void removeFavGIF(String id) {
dml("delete from gif where gid = '"+id+"'");
}
public void updateView(String id, String totview) {
int views = Integer.parseInt(totview) + 1;
dml("update catlist set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update fav set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update latest set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
dml("update shuffl set views = '"+String.valueOf(views)+"' where pid = '"+id+"'");
}
public void updateViewGIF(String id, String totview) {
int views = Integer.parseInt(totview) + 1;
dml("update gif set views = '"+String.valueOf(views)+"' where gid = '"+id+"'");
}
public void addtoAbout() {
dml("delete from about");
dml("insert into about (name,logo,version,author,contact,email,website,desc,developed,privacy) values (" +
"'"+ Constant.itemAbout.getAppName()+"','"+ Constant.itemAbout.getAppLogo()+"','"+ Constant.itemAbout.getAppVersion()+"'" +
",'"+ Constant.itemAbout.getAuthor()+"','"+ Constant.itemAbout.getContact()+"','"+ Constant.itemAbout.getEmail()+"'" +
",'"+ Constant.itemAbout.getWebsite()+"','"+ Constant.itemAbout.getAppDesc()+"','"+ Constant.itemAbout.getDevelopedby()+"'" +
",'"+ Constant.itemAbout.getPrivacy()+"')");
}
public Boolean getAbout() {
String selectQuery = "SELECT * FROM about";
Cursor c = getData(selectQuery);
if (c != null && c.getCount()>0) {
c.moveToFirst();
for (int i=0; i<c.getCount(); i++) {
String appname = c.getString(c.getColumnIndex("name"));
String applogo = c.getString(c.getColumnIndex("logo"));
String desc = c.getString(c.getColumnIndex("desc"));
String appversion = c.getString(c.getColumnIndex("version"));
String appauthor = c.getString(c.getColumnIndex("author"));
String appcontact = c.getString(c.getColumnIndex("contact"));
String email = c.getString(c.getColumnIndex("email"));
String website = c.getString(c.getColumnIndex("website"));
String privacy = c.getString(c.getColumnIndex("privacy"));
String developedby = c.getString(c.getColumnIndex("developed"));
Constant.itemAbout = new ItemAbout(appname,applogo,desc,appversion,appauthor,appcontact,email,website,privacy,developedby);
}
c.close();
return true;
} else {
return false;
}
}
}
This is the logcat:
java.lang.NullPointerException:
at com.example.util.DBHelper.<init>(DBHelper.java:35)
at com.example.adapter.AdapterImage.<init>(AdapterImage.java:69)
at com.apphics.minimalwallpapers.PopularFragment.setAdapterToListview(PopularFragment.java:226)
at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:217)
at com.apphics.minimalwallpapers.PopularFragment$MyTask.onPostExecute(PopularFragment.java:141)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.access$500(AsyncTask.java:180)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5438)
at java.lang.reflect.Method.invoke(Native Method:0)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)
The exception is thrown when arrayOfLatestImage.size() is greater than or equal to 41. Initialize adapterImage in the else block in the setAdapterToListview() function. Hope it helps.

Attach a progress bar to an android activity

Hi i have the following code used to read contacts from an andorid phone and write them to a file - i am trying to show the progress of the process below is the code for reading and writing the contacts
package com.lightcone.readcontacts;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class ReadContacts extends Activity {
// To suppress notational clutter and make structure clearer, define some shorthand constants.
private static final Uri URI = ContactsContract.Contacts.CONTENT_URI;
private static final Uri PURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private static final String ID = ContactsContract.Contacts._ID;
private static final String DNAME = ContactsContract.Contacts.DISPLAY_NAME;
private static final String HPN = ContactsContract.Contacts.HAS_PHONE_NUMBER;
private static final String CID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
private static final String PNUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
private static final String PHONETYPE = ContactsContract.CommonDataKinds.Phone.TYPE;
private String id;
private String name;
private String ph[];
private String phType[];
private File root;
private int phcounter;
private TextView tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.TextView01);
// Allow for up to 9 email and phone entries for a contact
ph = new String[9];
phType = new String[9];
// Check that external media available and writable
checkExternalMedia();
ContentResolver ctr = getContentResolver();
Cursor cur = ctr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int numberOfContacts = cur.getCount();
Toast.makeText(this, "Reading" +String.valueOf(numberOfContacts)+ "Contacts", Toast.LENGTH_LONG).show();
File dir = new File (root.getAbsolutePath() + "/download");
dir.mkdirs();
File file = new File(dir, "phoneData.txt");
tv.append("Wrote " +numberOfContacts+" to "+file+"\nfor following contacts:\n");
try{
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
ContentResolver cr = getContentResolver();
Cursor cu = cr.query(URI, null, null, null, null);
if (cu.getCount() > 0) {
// Loop over all contacts
while (cu.moveToNext()) {
id = cu.getString(cu.getColumnIndex(ID));
name = cu.getString(cu.getColumnIndex(DNAME));
tv.append("\n"+id+" "+name);
phcounter = 0;
if (Integer.parseInt(cu.getString(cu.getColumnIndex(HPN))) > 0) {
Cursor pCur = cr.query(PURI, null, CID + " = ?", new String[]{id}, null);
while (pCur.moveToNext()) {
ph[phcounter] = pCur.getString(pCur.getColumnIndex(PNUM));
phType[phcounter] = pCur.getString(pCur.getColumnIndex(PHONETYPE));
phcounter ++;
}
pCur.close();
}
// Write identifiers for this contact to the SD card file
pw.println("<nc>"+name);
for(int i=0; i<phcounter; i++){
pw.println("\tphone="+ ph[i]);
}
}
}
// Flush the PrintWriter to ensure everything pending is output before closing
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.i("MEDIA", "*************** File not found. Did you" +
" add a WRITE_EXTERNAL_STORAGE permission to the manifest file? ");
} catch (IOException e) {
e.printStackTrace();
}
}
private void checkExternalMedia () {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Can't read or write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
root = android.os.Environment.getExternalStorageDirectory();
tv.append( "External storage: Exists="+mExternalStorageAvailable+", Writable="
+mExternalStorageWriteable+" Root="+root+"\n");
}
private String getPhoneType(String index){
if(index.trim().equals( "1")){
return "home";
} else if (index.trim().equals("2")){
return "mobile";
} else if (index.trim().equals("3")){
return "work";
} else if (index.trim().equals("7")){
return "other";
} else {
return "?";
}
}
}
use AsyncTask to write the contacts to file and show the progress bar in onPreExecute() method of AsyncTask and dismiss the progress in onPostExecute() method of AsyncTask.

How to get photo of the contact in Android?

I'm simply getting the all contact list to an object (PhoneBookContact):
private static final Uri PURI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
private static final String PID = ContactsContract.CommonDataKinds.Phone._ID;
private static final String PNAME = ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME;
private static final String PNUM = ContactsContract.CommonDataKinds.Phone.NUMBER;
String[] projection = new String[]{PID, PNAME, PNUM};
String sortOrder = PNAME + " COLLATE LOCALIZED ASC";
Cursor people = mContext.getContentResolver().query(PURI, projection, null, null, sortOrder);
int indexid = people.getColumnIndex(PID);
int indexName = people.getColumnIndex(PNAME);
int indexNumber = people.getColumnIndex(PNUM);
people.moveToFirst();
do {
PhoneBookContact phoneBookContact = new PhoneBookContact();
phoneBookContact.setmCursorId(people.getLong(indexid));
phoneBookContact.setmDisplayName(people.getString(indexName));
phoneBookContact.setmPhoneNumber(UriFactory.formatNumberToInternational(people.getString(indexNumber)));
phoneList.put(phoneBookContact.getmPhoneNumber(), phoneBookContact);
} while (people.moveToNext());
people.close();
To fetch the photo of the user from Android Contacts, I'am using this method:
public static Uri loadContactPhotoUri(ContentResolver contentResolver, long id) {
try {
Uri person = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
return person;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
Finally, this code gives this URI for a specific user:
content://com.android.contacts/contacts/5907
Since I'm calling this URI with ContactsContract.CommonDataKinds.Phone._ID id, I can't get the photo of the user successfully. In fact, it should be the id of ContactsContract.Contacts._ID. How can I query the photo of the user and fix this problem?
Instead of ContactsContract.CommonDataKinds.Phone._ID, you must use ContactsContract.CommonDataKinds.Phone.CONTACT_ID to save the cursorID of Contacts table. It solved my problem.
This file have funtion get contact photo
https://github.com/heinrisch/Contact-Picture-Sync/blob/master/src/heinrisch/contact/picture/sync/ContactHandler.java
package heinrisch.contact.picture.sync;
import java.io.InputStream;
import java.util.ArrayList;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDiskIOException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts.Data;
import android.provider.ContactsContract.RawContacts;
import android.util.Log;
public class ContactHandler {
public static ArrayList<String> getNumbers(String ID, Context context){
ArrayList<String> numbers = new ArrayList<String>();
ContentResolver cr = context.getContentResolver();
Cursor phones = cr.query(Phone.CONTENT_URI, null,Phone.CONTACT_ID + " = " + ID, null, null);
while (phones.moveToNext()) {
numbers.add(phones.getString(phones.getColumnIndex(Phone.NUMBER)));
}
phones.close();
return numbers;
}
public static void matchContactsToFriends(ArrayList<Friend> friends, Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
if(people == null){
Log.e("ContactHandler", "Could not find contacts...?");
return;
}
while(people.moveToNext()) {
String ID = null,name = null;
int columnIndex = people.getColumnIndex(ContactsContract.Contacts._ID);
if(columnIndex != -1) ID = people.getString(columnIndex);
columnIndex = people.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME);
if(columnIndex != -1) name = people.getString(columnIndex);
//ArrayList<String> numbers = getNumbers(ID,context); //"can't" get this from facebook
if(name == null) continue;
for(Friend f : friends){
if(f.isMatchedWithContact()) continue;
if(f.getName().equals(name)){
f.setContactID(ID);
Bitmap contactPhoto = getPhoto(context, ID);
if(contactPhoto != null) f.setContactPicture(contactPhoto);
break;
}
}
}
people.close();
}
public static void setContactPicture(Friend f, Context context){
f.setContactPicture(getPhoto(context, f.getContactID()));
}
public static int getNumberOfContacts(Context context) {
Cursor people = context.getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);
int numberOfContacts = people.getCount();
people.close();
return numberOfContacts;
}
public static Uri getPicture(Context context, String ID){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = null;
Cursor rawContactCursor = cr.query(RawContacts.CONTENT_URI, new String[] {RawContacts._ID}, RawContacts.CONTACT_ID + " = " + ID, null, null);
if(!rawContactCursor.isAfterLast()) {
rawContactCursor.moveToFirst();
rawContactUri = RawContacts.CONTENT_URI.buildUpon().appendPath(""+rawContactCursor.getLong(0)).build();
}
rawContactCursor.close();
return rawContactUri;
}
public static void setContactPicture(Context context, String ID, Bitmap picture){
ContentResolver cr = context.getContentResolver();
Uri rawContactUri = getPicture(context, ID);
if(rawContactUri == null){
Log.e("rawContactUri", "is null");
return;
}
ContentValues values = new ContentValues();
int photoRow = -1;
String where = ContactsContract.Data.RAW_CONTACT_ID + " == " +
ContentUris.parseId(rawContactUri) + " AND " + Data.MIMETYPE + "=='" +
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE + "'";
Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null, where, null, null);
int idIdx = cursor.getColumnIndexOrThrow(ContactsContract.Data._ID);
if(cursor.moveToFirst()){
photoRow = cursor.getInt(idIdx);
}
cursor.close();
values.put(ContactsContract.Data.RAW_CONTACT_ID,
ContentUris.parseId(rawContactUri));
values.put(ContactsContract.Data.IS_SUPER_PRIMARY, 1);
values.put(ContactsContract.CommonDataKinds.Photo.PHOTO, Tools.bitmapToByteArray(picture));
values.put(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE);
try{
if(photoRow >= 0){
cr.update(
ContactsContract.Data.CONTENT_URI,
values,
ContactsContract.Data._ID + " = " + photoRow, null);
} else {
cr.insert(
ContactsContract.Data.CONTENT_URI,
values);
}
}catch(SQLiteDiskIOException dIOe){
//TODO: should show this to the user..
dIOe.printStackTrace();
}
}
public static Bitmap getPhoto(Context context, String contactId) {
Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, Long.parseLong(contactId));
InputStream input = ContactsContract.Contacts.openContactPhotoInputStream(context.getContentResolver(), uri);
if (input == null) {
return null;
}
return BitmapFactory.decodeStream(input);
}
}

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"));
}
}

Extract contact list in vcf format

How could i run the android method that extract the contact list in a vcf format?
Is there an intent that can directly call this action?
thx
François
This may be helpful to you. Try this with your need -
package com.vcard;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
public class VCardActivity extends Activity
{
Cursor cursor;
ArrayList<String> vCard ;
String vfile;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
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 Conatact
* 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() {
// TODO Auto-generated method stub
vCard = new ArrayList<String>();
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.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));
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 {
fd = this.getContentResolver().openAssetFileDescriptor(uri, "r");
// Your Complex Code and you used function without loop so how can you get all Contacts Vcard.??
/* 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 out = new FileOutputStream(path);
out.write(VCard.toString().getBytes());
Log.d("Vcard", VCard);*/
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();
}
}
}
Here's how to extract to VCF file and share it via an intent, with the option of sharing a single contact if you wish:
#WorkerThread
#Nullable
public static Intent getContactShareIntent(#NonNull Context context, #Nullable String contactId, #NonNull String filePath) {
final ContentResolver contentResolver = context.getContentResolver();
Cursor cursor = TextUtils.isEmpty(contactId) ? contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null) :
contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, Data.CONTACT_ID + "=?", new String[]{contactId}, null);
if (cursor == null || !cursor.moveToFirst())
return null;
final File file = new File(filePath);
file.delete();
do {
String lookupKey = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_VCARD_URI, lookupKey);
AssetFileDescriptor fd;
try {
fd = contentResolver.openAssetFileDescriptor(uri, "r");
if (fd == null)
return null;
FileInputStream fis = fd.createInputStream();
IOUtils.copy(fis, new FileOutputStream(filePath, false));
cursor.moveToNext();
} catch (Exception e1) {
e1.printStackTrace();
}
} while (cursor.moveToNext());
Intent intent = new Intent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
intent.setType("*/*");
return intent;
}
You can do this manually in the contacts App. But there is no Intent for that. If you want your App to have such an export you unfortunately have to write it yourself or use code from here.vcardio
This has changed as of Sept., 2016. You can now export your contacts to a VCF file using the 'People' app: select 'Import/export' in the menu, then one of the export items. You'll still have to get the file off your phone but that's easy enough via ADB (or maybe email.)

Categories

Resources