繁体   English   中英

使用CustomList适配器时,空指针异常

[英]Null Pointer Exception when using CustomList Adapter

我试图在一个片段中创建一个列表视图。 导致空指针异常的数组是从称为“ getData”的单独类中获取的。

要创建列表视图,我正在使用“自定义列表适配器”。 仅当我将数组放入自定义列表适配器中时,我才收到错误。

错误发生的片段:

package com.example.testapp;

import android.os.Bundle;

public class FragmentA extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    View V = inflater.inflate(R.layout.fragment_a, container, false);

    ListView listView = (ListView)V.findViewById(R.id.list);


        Integer[] imageId = {
                R.drawable.ic_launcher,
                R.drawable.ic_launcher,
               };

        getData data = getData.getMyData();

      CustomList adapter = new
            CustomList(getActivity(), data.myArray, imageId); //This is where i put the array.      
      listView.setAdapter(adapter);

    return V;
}
}

getData类(从中获取数组的类):

package com.example.testapp;

import java.io.BufferedReader;

public class getData{ 

    private static getData _instance; 


    public String myArray[]; //Array set up


    public static getData getMyData() //This is what the fragment calls to get the array.
    {
        if(_instance == null)
            _instance = new getData();

        return _instance;
    }

public void runData(){
       getData data = getData.getMyData();

       data.myArray[0] = "test"; //Array given value

}

}

您不是在设置数组而是在声明它。

public String myArray[];

下一行将给出NP,因为尚未初始化数组对象。

data.myArray[0] = "test";

您可以像这样创建数组对象。

public String myArray[] = new String[10];

这是更新的getData类,它不是100%封装和单例的,但可以使用。 了解有关封装数据和单例的更多信息。

package com.example.testapp;

import java.io.BufferedReader;

public class getData{ 

    private static getData _instance; 


    public String myArray[] = new String[10]; //Array set up


    public static getData getMyData() //This is what the fragment calls to get the array.
    {
        if(_instance == null)
            _instance = new getData();
            _instance.runData();

        return _instance;
    }

    private void runData(){       
           this.myArray[0] = "test"; //Array given value

    }
}

将您的GetData更改为

package com.example.testapp;

import java.io.BufferedReader;

public class GetData
{
    private static GetData _instance; 
    public List<String> myArray = null;

    public static GetData getMyData() //This is what the fragment calls to get the array.
    {
        if(_instance == null) _instance = new GetData();
        return _instance;
    }

    private GetData()
    {
        myArray = new LinkedList<String>();
    }

    public void runData()
    {
        GetData data = GetData.getMyData();
        myArray.add(0, "test"); //Array given value
    }
}

您的阵列未正确初始化。 如果要使用String[]数组,则必须指定长度,例如使用new String[5] 但是,如果您不知道最终长度,建议您使用上面的代码。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM