为联系人生成 vcf 文件时出现空指针异常

Null pointer exception while generating vcf file for the contacts

public class MainActivity extends AppCompatActivity {

Cursor cursor;
ArrayList<String> vCard;
String vfile;
static Context mContext;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    getVCF();
}

public static void getVCF() {
    final String vfile = "Contacts.vcf";

    Cursor phones = mContext.getContentResolver().query(    // exception here at this line
            ContactsContract.Contacts.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();
        }
    }
}
}

错误

    FATAL EXCEPTION: main  Process: com.example..myapplication, P  
    java.lang.RuntimeException: Unable to start activity 
 ComponentInfo{com.example..myapplication/com.example.myapplication.MainActivity
  }: java.lang.NullPointerException: Attempt to invoke virtual method 
  'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference                                                                                     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object referenc   at com.example..myapplication.MainActivity.getVCF(MainActivity.java:36at com.example..myapplication.MainActivity.onCreate(MainActivity.java:30)

你得到 NPE 是因为你的上下文为空,或者你可以说你没有初始化上下文。因此需要设置上下文或将引用传递给上下文变量。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mContext = MainActivity.this;
    getVCF();
}

java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object reference Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.ContentResolver android.content.Context.getContentResolver()' on a null object referenc at com.example..myapplication.MainActivity.getVCF(MainActivity.java:36at com.example..myapplication.MainActivity.onCreate(MainActivity.java:30)

您的异常清楚地表明 mContext 在这一行为空:

Cursor phones = mContext.getContentResolver().query(    // exception here at this line
            ContactsContract.Contacts.CONTENT_URI, null,  
            null, null, null);

在调用 getVCF();

之前在 onCreate 中添加这一行
mContext = MainActivity.this;

或者简单地删除调用 getContentResolver()mContext 简单地像这样使用它:

getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null, null, null);

因为你在activity中有方法,你不必使用context.你可以直接访问ContentResolver

public static void getVCF() {
        final String vfile = "Contacts.vcf";

        Cursor phones = getContentResolver().query(    // exception here at this line
                ContactsContract.Contacts.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 = 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();
            }
        }
    }
    }