0
我有以下代碼:無法訪問的LinkedHashMap在內部類
final LinkedHashMap<String, Line> trainLinesMap = MetraRail.myDbHelper.getTrainLinesHashMap();
// Create an array of proper line names for the listview adapter.
String[] train_lines_long_names = new String[trainLinesMap.size()];
Iterator<Entry<String, Line>> it = trainLinesMap.entrySet().iterator();
for (int i = 0; it.hasNext(); i++) {
Map.Entry<String, Line> pairs = (Map.Entry<String, Line>) it.next();
train_lines_long_names[i] = (String) pairs.getKey();
}
// Override the default list adapter so we can do 2 things: 1) set custom background colors
// on each item, and 2) so we can more easily add onclick handlers to each item.
listview.setAdapter(
new ArrayAdapter<String>(this, R.layout.select_line_row_layout,
R.id.select_line_line_label, train_lines_long_names) {
@Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
// Change the background color of each item in the list.
final String line_label_long = textView.getText().toString();
final int line_color = trainLinesMap.get(line_label_long).getColorInt();
textView.setBackgroundColor(line_color);
// Add onclick handlers to each item.
textView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent();
i.setClassName("garrettp.metrarail",
"garrettp.metrarail.screens.SelectStations");
i.putExtra("garrettp.metrarail.line.short",
trainLinesMap.get(line_label_long).getShortName());
i.putExtra("garrettp.metrarail.line.long", line_label_long);
i.putExtra("garrettp.metrarail.line.color", line_color);
startActivity(i);
}
});
return textView;
}
});
在生產線:
final int line_color = trainLinesMap.get(line_label_long).getColorInt();
我得到一個NullPointerException:
10-26 16:10:35.922: E/AndroidRuntime(1785): java.lang.NullPointerException
10-26 16:10:35.922: E/AndroidRuntime(1785): at garrettp.metrarail.screens.SelectLine$1.getView(SelectLine.java:74)
這是爲什麼?在調試器中,我已驗證trainLinesMap已正確初始化並填充了值。它在第一個for循環中被成功迭代,所以我知道那裏有值。但是,當從我的匿名內部類訪問LinkedHashMap時,它始終爲空。
我能夠從這個內部類訪問一個字符串數組,爲什麼我不能訪問一個LinkedHashMap?
你可以,NPE很可能來自你的地圖,在該行之前添加 「System.err.println(line_label_long +」:「+ trainLinesMap.get(line_label_long));」 它可能是空的 –
看到我的答案在下面,我解決了這個問題,將trainLinesMap.get(line_label_long)的結果賦給一個臨時變量,並從臨時變量中調用.getColorInt()。 – pwnsauce