MD Farog
MD Farog

Reputation: 1

String array causing app to stop

Here code begins of one class named as Homepage.java -

This is initial declarations -

int j=0,i=0;
String[] fetch_name,fetch_num;

Then following block is used to fetch phonebook contacts -

Cursor phones1 = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null );
    while(phones1.moveToNext())
    {
        j=j+1;
    }
    fetch_name = new String[j];
    fetch_num = new String[j];
    while(phones1.moveToNext())
    {
        fetch_name[i]= phones1.getString(phones1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
        fetch_num[i] = phones1.getString(phones1.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
        i =i + 1;
    }
    phones1.close();

Now following are methods returning String Array & integer

public String[] getfname()
{
    return(fetch_name);
}
public  String[] getfnum()
{
    return(fetch_num);
}
public  int getj()
{
    return(j);
}

Now in second class named as Contactss.java code is as follow -

public class Contactss extends android.support.v4.app.Fragment 
{
Homepage hp = new Homepage();
Chatss cs = new Chatss();
int k = hp.getj();
public View onCreateView(LayoutInflater inflater,
        @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    View v = inflater.inflate(R.layout.fragment_contactss, container, false);
    loadd();
    return v;
}
public void loadd() {
    // TODO Auto-generated method stub
    String xyz  []= hp.getfnum();
    Toast.makeText(getActivity(), "jhbh" + xyz.length, Toast.LENGTH_LONG).show();
}


}

The above code causing app to stop, no idea why my app is going to stop. Please help.

Upvotes: 0

Views: 43

Answers (1)

MByD
MByD

Reputation: 137282

You go through the entire results here:

while(phones1.moveToNext())
{
    j=j+1;
}

But never reset to the first element again, so you have no more elements in the Cursor, and you set nothing in the arrays. You can either move to the first when you are done counting using Cursor#moveToFirst(), or even better, count using the Cursor#getcount() method.

As a side note, please add logcat log next time you have a problem, it will make yours (and our) work much easier

Upvotes: 3

Related Questions