java - 如何设置可扩展大小的数组以防止空指针异常?

标签 java android arrays listview

目的是从 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/

相关文章:

android - 在 cordova plugin.xml 中使用 gradleReference 特性

在最后一个循环之前崩溃

c - 如何返回指向 void* 指向的数组中的数组位置的指针?

javascript - Selenium 中图像验证的 NullPointerException

java - 无法在 SOAPUI 中导入 WSDL 文件 - NT 身份验证弹出窗口(加载 WSDL 时出错)

java - Selenium webdriver 显式等待

android - FIrebase 归因中的 (not-set) 是什么意思?

java - Cassandra 写入后读取与 LOCAL_QUORUM 不一致

android - 如何在没有 SuperSU 的情况下授予 root 访问权限

javascript - JS 将 JSON 对象转换为数组