目的是从 MYSQL 表中检索数据并将其输入到 ListView 中。为了做到这一点,我将值放入一个数组中。但是,数组的长度似乎必须等于从表中获取的值的数量(可能会有所不同);否则应用将以空指针异常作为响应。
我的问题是:如何将数组的长度设置为动态的,这样错误就不会演变?或者有其他方法吗?
定义使用的数组:
public String titleId[] = new String[2]; //Defining the arrays used
public Integer imageId[] = new Integer[2];
将数组设置为等于值:(目前,这将执行 2 次迭代)
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
titleId[i] = "test";
imageId[i] = R.drawable.ic_launcher;
}
使用数组设置ListView:
CustomList adapter = new
CustomList(getActivity(), data.titleId, data.imageId);
listView.setAdapter(adapter);
CustomList.java(用于设置自定义适配器)
public class CustomList extends ArrayAdapter<String>{
private final Activity context;
private final String[] titleId;
private final Integer[] imageId;
public CustomList(Activity context,
String[] titleId, Integer[] imageId) {
super(context, R.layout.single_row, titleId);
this.context = context;
this.titleId = titleId;
this.imageId = imageId;
}
@Override
public View getView(int position, View view, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View rowView= inflater.inflate(R.layout.single_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.tvTitle);
ImageView imageView = (ImageView) rowView.findViewById(R.id.ivIcon);
txtTitle.setText(titleId[position]);
imageView.setImageResource(imageId[position]);
return rowView;
}
}
最佳答案
我建议您使用 JDK 提供的动态数据结构。更具体地说,那些实现 List
接口(interface)的人似乎符合您的目标。
您应该将数据收集在 List
对象中,稍后您可以从中生成一个数组。
例如:
List<String> titleId = new ArrayList();
假设您从 JDBC 结果集中获取数据:
while(res.next())
{
titleId.add(res.getString("dbTableColumn"));
}
最后,您从列表中生成一个数组并将其传递给 CustomList
构造函数:
CustomList adapter = new CustomList(getActivity(), data.titleId.toArray(), ...);
关于java - 如何设置可扩展大小的数组以防止空指针异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24467374/