【发布时间】:2014-02-03 19:19:50
【问题描述】:
我的代码:
public ArrayList<People_Attendance> attendance_reader() {
ArrayList<People_Attendance> attendance_list = new ArrayList<People_Attendance>();
String file_string = "";
try {
InputStream filestream = openFileInput("Attendance_File");
if (filestream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(filestream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
file_string = stringBuilder.toString();
String parse_array[] = file_string.split(";");///splits into individual People_Attendance items.
String item_name; String item_number; String item_status; ///declares all the item strings
for(String person_item : parse_array) {
String item_parse_array[] = person_item.split(",");
item_name = item_parse_array[0];
item_number = item_parse_array[1];
item_status = item_parse_array[2];
attendance_list.add(new People_Attendance(item_name, item_number, item_status));
///above is an example of an initialization method, custom inside of People_Attendance class.
}
}
在线:
People_Attendance item = new People_Attendance(item_name, item_number, item_status);
这个初始化怎么错了?它给出了一个 NullPointerException,所以大概我的字符串之一是空的? 我调试了一下,发现错误就在这里。我还发现我的阅读器阅读正确,因为我插入了一条调试线,并从中获取了文本。我倾向于认为我在 String.Split() 上做错了什么 经过更多调试后,我发现拆分后得到了两个字符串-名称和状态,但由于某种原因没有数字……非常困惑。我的调试技巧:
Log.d("DEBUG", person_item);
String item_name = item_parse_array[0];
Log.d("DEBUG", item_name);
String item_number = item_parse_array[1];
Log.d("DEBUG", item_number);
String item_status = item_parse_array[2];
Log.d("DEBUG", item_status);
所以我一定要拿到号码??
【问题讨论】:
-
我建议:
String item_parse_array[] = person_item.split(","); if (item_parse_array.length != 3) LOG.i("oops: " + Arrays.toString(item_parse_array));看看输出是什么... -
我有一种感觉,它在最后一个冒号上分裂,你的最后一个元素最终接近空(可能最多有一个换行符)。
-
NPE 表示数组一开始就为空。它应该在前面有两行 NPE。
-
@John The one-arg
split在创建返回的数组之前丢弃尾随的空标记。 -
在此处设置断点,
item_name = item_parse_array[0];使用调试器单步执行。检查数组。它的内容是什么?我想这个字符串不是你想象的那样。你真的应该学习如何调试。您可以在 30 秒内找到它。
标签: java android string split filereader