【问题标题】:null pointer exception while instantiating content resolver?实例化内容解析器时出现空指针异常?
【发布时间】:2011-12-06 12:05:54
【问题描述】:

在我的 Android 中,我正在使用内容解析器读取联系人。但内容解析器没有被初始化,它给出了NullPointerException。 我想在另一个类中使用字符串数组并在其中获取值我必须查询数据库并从手机中读取联系人,但正如代码中指出的那样,遇到了该异常:

//this code is in some other class...     
et= (EditText) findViewById(R.id.searchcontact);
        et.addTextChangedListener(new TextWatcher() {

             public void onTextChanged(CharSequence s, int start, int before, int
             count) { // TODO Auto-generated method stub
                 lva.getFilter().filter(s);

RefreshListView rlv=new RefreshListView();<----class is getting called from here
                 lva.notifyDataSetInvalidated();
                 lva = new ListViewAdapterContacts(AllContactsActivity.this, rlv.names, rlv.types, rlv.phones, rlv.ids);

                 lv.setAdapter(lva);


             }

             public void beforeTextChanged(CharSequence s, int start, int count,
             int after) { // TODO Auto-generated method stub

             }

             public void afterTextChanged(Editable s) { 
                 // TODO Auto-generated  method stub


            // lva.notifyDataSetChanged();
             }
             });

...............********.........

public class RefreshListView extends ListActivity{

            String[] names,phones,types,ids;
            String name,id,phoneNumber;
            int type;
            ArrayList <String> newValues;

        public void onCreate(Bundle b){
        super.onCreate(b);

        newValues=SetNewList.getNames();
        getContacts();
    }



public void getContacts(){
                int foo = 0;


    ContentResolver cr = getContentResolver();<---//null pointer exception

    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,
                        null, null, "UPPER(" + ContactsContract.Contacts.DISPLAY_NAME
                        + ") ASC");
                if (cur.getCount() > 0) {

                    names = new String[cur.getCount()];
                    phones = new String[cur.getCount()];
                    types = new String[cur.getCount()];
                    ids = new String[cur.getCount()];

                    while (cur.moveToNext()) {

                        name = cur
                        .getString(cur
                                .getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                        for(int i=0;i<=newValues.size();i++){           
                            if(newValues.get(i).equalsIgnoreCase(name)) {
                                id = cur.getString(cur
                                        .getColumnIndex(ContactsContract.Contacts._ID));
                                String hasPhone = cur
                                .getString(cur
                                        .getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));

                                if (Integer.parseInt(hasPhone) == 1) {

                                    Cursor phones = getContentResolver().query(
                                            ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                                            null,
                                            ContactsContract.CommonDataKinds.Phone.CONTACT_ID
                                            + " = " + id, null, null);

                                    while (phones.moveToNext()) {
                                        phoneNumber = phones
                                        .getString(phones
                                                .getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                                        type = phones.getInt(phones.getColumnIndex(Phone.TYPE));

                                    } // while

                                    phones.close();
                                }// if

                                else {
                                    phoneNumber = "unknown";
                                    type = 0;

                                }// else



                                phones[foo] = phoneNumber;
                                names[foo] = name;
                                ids[foo] = id;

                                if (type == 0) {
                                    String value = "unknown";
                                    types[foo] = value;
                                }

                                else if (type == 1) {
                                    String value = "home";
                                    types[foo] = value;
                                }// if

                                else if (type == 2) {
                                    String value = "mobile";
                                    types[foo] = value;
                                }// else if

                                else if (type == 3) {
                                    String value = "Work";
                                    types[foo] = value;
                                }

                                else if (type == 4) {
                                    String value = "Workfax";
                                    types[foo] = value;
                                }

                                else if (type == 5) {
                                    String value = "Home Fax";
                                    types[foo] = value;

                                } else if (type == 6) {
                                    String value = "Pager";
                                    types[foo] = value;
                                }

                                else {
                                    String value = "Other";

                                    types[foo] = value;
                                }

                                foo++;
                            }
                        }
                    }// while
                }// if


            }// get contacts

        }

【问题讨论】:

  • RefreshListView()-->它是一个构造函数。
  • 不要在 Android Activity 中使用构造函数 - 这不是 Activity 的工作方式。 Android OS 负责处理构造——使用标准的onXXXXX(...) 方法,例如onCreate(...), onStart(...), onResume(...)` 等

标签: java android nullpointerexception android-contentprovider


【解决方案1】:

别这样……

public class RefreshListView extends ListActivity{

    public RefreshListView() {

        ...

    }
}

不要为 Android Activity 使用构造函数!!!

您应该删除该构造函数并将代码放入 Activity onCreate(...) 方法中。

请参阅Activity 的文档并阅读Activities

试试这样的...

public class RefreshListView extends ListActivity{

    String[] names,phones,types,ids;
    String name,id,phoneNumber;
    int type;
    ArrayList <String> newValues;
    ContentResolver cr = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        cr = getContentResolver();
        newValues=SetNewList.getNames();//getnames is of static type
        getContacts();
    }

    public void getContacts() {
        int foo = 0;

        // REMOVE THE NEXT LINE !!!
        // ContentResolver cr = getContentResolver();

        ...

    }
}

【讨论】:

  • 哇,我无法意识到这是一个构造函数,我还以为它是一个方法... +1(facepalm)
  • @hovanessyan:大声笑,我花了一段时间才发现它。在Activity 中看到构造函数是一件很陌生的事情,并不是很明显。
  • 但是当我没有通过调用意图开始活动时,我如何在创建时使用。顺便说一下,我尝试创建但课程甚至没有开始
  • @picaso:好吧,看来你不明白Activity 是什么。如果你没有将它作为 MAIN/LAUNCHER Activity 启动它并且你没有使用 startActivity(...)Intent 启动它,你怎么能期望代码运行?请阅读我发布的链接中的文档,特别是第二个developer.android.com/guide/topics/fundamentals/activities.html
  • @MisterSquonk 我只想使用内容解析器。有什么方法可以在不扩展任何活动的情况下完成它。我需要像在 java 中那样通过实例化它的对象来调用该类,但是我认为内容解析器在没有扩展活动的情况下无法工作。
【解决方案2】:

getContentResolver() 应该在 Activity 的实现中调用 - 尝试覆盖 onCreate()。如果您在活动中将其称为 this.getContentResolver() 会更清楚 = 更易于阅读。

查看this example code(在“绑定到数据”部分之后)。

您可以在所有其他应用程序组件中使用 ContentResolver,您只需要一个 Context。对于 Activity,您会自动使用 Activity 的上下文。您也可以使用Application Context - 它们的生命周期基本上不同。

【讨论】:

    猜你喜欢
    • 2020-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-31
    • 2014-01-18
    • 2012-02-04
    • 1970-01-01
    • 1970-01-01
    • 2021-01-02
    相关资源
    最近更新 更多