我正在尝试在片段内创建列表视图。导致空指针异常的数组来自一个名为" 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
}
}
答案 0 :(得分:0)
您没有设置阵列,只是声明它。
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
}
}
答案 1 :(得分:0)
将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]
指定长度。但如果您不知道最终长度,我建议您使用我的上述代码。