字符串数组导致应用停止

时间:2015-09-21 16:34:27

标签: android arrays

这里的代码从名为Homepage.java的一个类开始 -

这是初始声明 -

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

然后使用以下块来获取电话簿联系人 -

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

以下是返回String Array&的方法。整数

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

现在名为Contactss.java的第二个类代码如下 -

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


}

以上代码导致应用程序停止,不知道为什么我的应用程序将停止。 请帮忙。

1 个答案:

答案 0 :(得分:3)

您可以在此处查看整个结果:

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

但是永远不要再次重置为第一个元素,因此Cursor中没有更多元素,并且您在数组中没有设置任何内容。使用Cursor#moveToFirst()进行计数后,您可以移至第一个,甚至可以使用Cursor#getcount()方法进行计数。

作为旁注,请在下次遇到问题时添加logcat日志,这会让您(以及我们)的工作变得更加轻松