Excepción de puntero nulo al instanciar la resolución de contenido?

En mi Android, estoy leyendo los contactos mediante resolución de contenido. Pero la resolución de contenido no se está inicializando, da NullPointerException . Quiero utilizar los arrays de cadenas en otra clase y para obtener valores en ellos tengo que consultar la base de datos y leer los contactos del teléfono, pero se quedó con esa excepción como se señala en el código:

 //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 } 

No hagas esto …

 public class RefreshListView extends ListActivity{ public RefreshListView() { ... } } 

¡No utilice un constructor para una Activity Android!

Debe quitar ese constructor y poner el código en el onCreate(...) Activity onCreate(...) .

Consulte la documentación de Actividad y también lea Actividades .

Prueba algo como esto …

 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(); ... } } 

GetContentResolver () debería ser llamado dentro de una implementación de Activity – intentar anular onCreate (). Es más claro si lo llamas como this.getContentResolver() en tu actividad = más fácil de leer.

Echa un vistazo a este código de ejemplo (después de " Binding to Data " sección).

Puede utilizar ContentResolver en cualquier otro componente de la aplicación, sólo necesita un Contexto . En el caso de Actividad, se utiliza automáticamente el contexto de la Actividad. También puede utilizar el Contexto de la aplicación – que básicamente difieren en sus ciclos de vida.

  • NullPointerException en PreferenceManager.getDefaultSharedPreferences en el inicio
  • ViewRootImpl.setPausedForTransition (boolean) NullPointerException en ActivityTransitionCoordinator cuando la transición a otra Actividad se invoca demasiado pronto
  • Widget - No se puede instanciar el receptor
  • Excepción de puntero nulo durante la instrucción 'monitor-enter v1'
  • ¿Cuál es la diferencia entre abrir una aplicación desde la pantalla de aplicaciones y la lista de aplicaciones utilizadas recientemente? (androide
  • NullPointerException en SearchView con ActionBarSherlock
  • Acceder a un método de un fragmento de la actividad ViewPager
  • NullPointerExeption con AppCompat BottomSheets
  • Error de inicio de Android Studio v1.2.0: java.lang.NullPointerException
  • Android: NullPointerException a pesar de @NonNull
  • ¿Por qué obtengo NullPointerException cuando uso setCurrentText o setText para TextSwitcher?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.