CursorLoader导致Contacts.DISPLAY_NAME设置为NULL

时间:2013-11-29 23:59:25

标签: android android-loadermanager android-cursorloader

我在实现LoaderManager.LoaderCallbacks的FragmentActivity中创建CursorLoader时遇到问题。

创建CursorLoader时,我的android.provider.ContactsContract.Contacts.DISPLAY_NAME设置为NULL。

如果我使用“display_name”字符串,我仍然可以从我的光标中获取数据,但如果我使用Contacts.DISPLAY_NAME则不会,但它只会抛出NullPointerException。

代码中的日志消息仍会打印正确的“display_name”字符串但是在调试时DISPLAY_NAME为空并且我仍然得到NullPointer异常,它是否与后台任务中使用的线程的类加载器有关? / p>

这是我的FragmentActivity。

package com.example.test2;

import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.provider.ContactsContract.Contacts;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;

public class MainActivity extends FragmentActivity implements LoaderManager.LoaderCallbacks<Cursor> {

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

        String test = Contacts.DISPLAY_NAME;
        Log.d(ACTIVITY_SERVICE, test);

        getSupportLoaderManager().initLoader(0, null, this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
        final String select = "((" + Contacts.DISPLAY_NAME + " NOTNULL) AND ("
                + Contacts.DISPLAY_NAME + " != '' ))";

        final String[] projection = new String[] {
            Contacts._ID,
            Contacts.DISPLAY_NAME,
            Contacts.CONTACT_STATUS,
            Contacts.CONTACT_PRESENCE,
            Contacts.PHOTO_ID,
            Contacts.LOOKUP_KEY,
        };

        CursorLoader cursorLoader = new CursorLoader(
            this, 
            Contacts.CONTENT_URI,
            projection, 
            select, 
            null, 
            Contacts.DISPLAY_NAME);

        return cursorLoader;
    }

    @Override
    public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
        Log.d(ACTIVITY_SERVICE, Contacts.DISPLAY_NAME);

        arg1.moveToFirst();
        arg1.getString(arg1.getColumnIndex("display_name"));
        arg1.getString(arg1.getColumnIndex(Contacts.DISPLAY_NAME));
    }

    @Override
    public void onLoaderReset(Loader<Cursor> arg0) {
        // TODO Auto-generated method stub

    }

}

1 个答案:

答案 0 :(得分:0)

也许是迟到但应该是

IS NOT NULL 

代替

NOTNULL
相关问题