0

I am trying to have name of contacts in one array and their types in another array,but can't get through with null pointer exception.here is my code.I have pointed out the line where I am getting null pointer exception.please help..thanks in advance.

package application.test;
import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.database.SQLException;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;  
import android.provider.ContactsContract.Contacts.Data;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;

public final class TestActivity extends Activity {
String[] name;
String[] phoneType;
ListView lv;
ListViewAdapter lva;


    public static final String TAG = "ContactManager";
@Override
public void onCreate(Bundle savedInstanceState)
{
    Log.v(TAG, "Activity State: onCreate()");
    super.onCreate(savedInstanceState);
    LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);        
    LinearLayout mainLayout=new LinearLayout(this);
    mainLayout.setOrientation(LinearLayout.VERTICAL);               
    LayoutInflater layoutInflater = getLayoutInflater();        
    mainLayout.addView(layoutInflater.inflate(R.layout.main,null));
    mainLayout.addView(layoutInflater.inflate(R.layout.extra,null));

    this.addContentView(mainLayout, params);

      lv = (ListView)findViewById(android.R.id.list);
     lva = new ListViewAdapter(this,name,phoneType); 
    lv.setAdapter(lva);
    testGetContacts();
}


private void testGetContacts() { 

        ContentResolver cr = getContentResolver();

        String[] projection = new String[] { Data._ID,
                ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE}; 

        Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null); 


        if (cur != null && cur.moveToFirst()) { 

        try {

            int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
            int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
             int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

          while (cur.moveToNext()) {
             int  i=1;
              String id = cur.getString(indexID);    
 //HERE LIES NULL POINTER EXCEPTION   name[i] = cur.getString(indexName);  
 //HERE TOO              phoneType[i] =  cur.getString(indexPhoneType);

             i++;


              System.out.println(id + "\n");
              System.out.println(name + "\n");
              System.out.println(phoneType + "\n");


          }


        } catch (SQLException sqle) {
           //handling exception       
        } finally { 
         if (!cur.isClosed()) {
             cur.close();
         }     
     }

        }

}
}
2
  • 1
    disregard that, your name and phoneType are not initialized, so they are null Commented Nov 7, 2011 at 13:06
  • make your listview like: lv = (ListView)findViewById(R.id.listview); Commented Nov 8, 2011 at 7:26

5 Answers 5

1

You're not initializing your String[] name, so when you try to access it, you get a null pointer exception. I would suggest using more meaningful variable names. 'name' is very ambiguous.

Sign up to request clarification or add additional context in comments.

3 Comments

well program has run but unable to retrieve name and type..blank screen is what I am getting.any idea
Now you're dealing with a completely different question. I an others have answered your question. Your original question was about a Null Ref Exception. I'd suggest trying to find some resources to know your new problem, and ask a new question on Stack Overflow if needed.
Also, it seems like you're asking two new things. Displaying and Retrieving are different operations.
1

Your name and phone arrays have not been initialized.

String[] name = new String[EXPECTED_SIZE];
String[] phoneType = new String[EXPECTED_SIZE];

Any proper IDE should tell you that before you try to run it. Are you using Eclipse or IntelliJ? You should!

1 Comment

well program has run but unable to retrieve name and type..blank screen is what I am getting.any idea
0

Initialize String[] name before using it. You can do that like:

name=new String[cur.getCount()];
String s="";
while (cur.moveToNext()) {

     int  i=1;
     String id = cur.getString(indexID);    
     name[i] = cur.getString(indexName);  
     phoneType[i] =  cur.getString(indexPhoneType);         

     //System.out.println(id + "\n");
     //System.out.println(name + "\n");
     //System.out.println(phoneType + "\n");

     s=s+"id="+id+" name="+name[i]+" phoneType="+phoneType[i]+"\n";
     i++;
}
Toast.makeText(getApplicationContext(),i+" - "+s).show();

Edit :

Create an xml file in layout folder.

main.xml

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical" >    

    <ListView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listview"
        android:cacheColorHint="#0000"
        />
</LinearLayout>

now in your TestActivity.class:

public final class TestActivity extends Activity {

String[] name;
String[] phoneType;
ListView lv;
String s[];
public static final String TAG = "ContactManager";

@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.id.main);        

    testGetContacts();

    lv = (ListView)findViewById(R.id.listview);
    ArrayAdapter<String> sa=new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1,s);
    lv.setAdapter(sa);        
}


private void testGetContacts() { 

    ContentResolver cr = getContentResolver();    
    String[] projection = new String[] { Data._ID,
                ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};     
    Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                projection, null, null, null);     

    if (cur != null && cur.moveToFirst()) { 

        try {

            int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
            int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
             int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

          name=new String[cur.getCount()];
          s=new String[cur.getCount()];

          while (cur.moveToNext()) {

               int  i=1;
               String id = cur.getString(indexID);    
               name[i-1] = cur.getString(indexName);  
               phoneType[i-1] =  cur.getString(indexPhoneType);       


              String temp="id="+id+"-name="+name[i-1]+"-phoneType="+phoneType[i-1];
              s[i-1]=temp;
              i++;
}    

}

15 Comments

well program has run but unable to retrieve name and type..blank screen is what I am getting.any idea
That is because you didn't display the things on the screen.You will see this printed things using System.out.println(""); in consol. Try to use Toast or TextView to see those things on screen.
Please see the edit in answer. I have shown items in listview.
I tried running your code,but getting null pointer exception at(lv.setadapter(sa))..I am after this thing for a week and exhausted now.please help..
please see my edited answer. It was by mistake s=new String[cur,getCount()]; and also i have updated s[i] with s[i-1] in while loop.
|
0

You are getting null pointer because you are accessing wrong index.

try this:

s=new String[cur.getCount()];
int  i=1;
while (cur.moveToNext()) {    

                   String id = cur.getString(indexID);    
                   name[i-1] = cur.getString(indexName);  
                   phoneType[i-1] =  cur.getString(indexPhoneType);       


                  String temp="id="+id+"-name="+name[i-1]+"-phoneType="+phoneType[i-1];
                  s[i-1]=temp;
                  i++;
    }

and also lv=(ListView)findViewById(R.id.listview); instead of lv=(ListView)findViewById(android.R.id.list);

You should add a condition here:

    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);      
       testGetContacts();

if(s.length()>0)
{
    lv = (ListView)findViewById(R.id.listview);
    ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,s);
    lv.setAdapter(sa);
}
else
{
   Toast.makeText(getApplicationContext(),"Nothing Found",Toast.LENGTH_SHORT).show();
}

9 Comments

i have tried that index..still same exception and null values
see the edited answer.make all changes and tell what is happening.
you also need to put efforts.it should be s.length()>0.
s.length is absolutely correct...what I see while debugging that at lines[String id = cur.getString(indexID); name[i-1] = cur.getString(indexName); phoneType[i-1] = cur.getString(indexPhoneType); ],indexid is getting 0,indexname=1,and indexphonetype=2;i think they all should get same index...
put int i=1 outside of while...because of it it write new string always at the same place...try this
|
0

Try this and tell me i it helped:

  @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);        

            lv = (ListView)findViewById(R.id.listview);
            testGetContacts();
            ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,s);
              lv.setAdapter(sa);        

        }//method


        private void testGetContacts() { 

            ContentResolver cr = getContentResolver();    
            String[] projection = new String[] { Data._ID,
                        ContactsContract.Contacts.DISPLAY_NAME, Phone.TYPE};     
            Cursor cur = cr.query(ContactsContract.Data.CONTENT_URI,
                        projection, null, null, null);     

            if (cur != null && cur.moveToFirst()) { 

                try {

                    int indexID =  cur.getColumnIndexOrThrow(ContactsContract.Contacts._ID);
                    int indexName = cur.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME);
                     int indexPhoneType = cur.getColumnIndexOrThrow(Phone.TYPE);

                  name=new String[cur.getCount()];
                  phoneType=new String[cur.getCount()];
                  s=new String[cur.getCount()];
                  int  i=1;
                  while (cur.moveToNext()) {

                       String id = cur.getString(indexID);    
                       name[i] = cur.getString(indexName);  
                       phoneType[i] =  cur.getString(indexPhoneType);       


                      String temp="id="+id+"-name="+name[i]+"-phoneType="+phoneType[i];
                      s[i-1]=temp;
                      i++;                  
                   }//while
             ArrayAdapter<String> sa=new ArrayAdapter<String>(getApplicationContext(),               android.R.layout.simple_list_item_1,s);
             lv.setAdapter(sa);
             }catch(Exception e){

        e.printStackTrace();    
            }//catch

            }//if

        }//method

1 Comment

I tried it and able to get list view but not as I expected.first thing I am getting twice the contacts I saved in AVD and second thing name and phonetypes are showing same thing,i.e the contact name.I am not been able to get the types ,i.e(home,work).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.