2013-10-26 60 views
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?

+0

你可以,NPE很可能来自你的地图,在该行之前添加 “System.err.println(line_label_long +”:“+ trainLinesMap.get(line_label_long));” 它可能是空的 –

+0

看到我的答案在下面,我解决了这个问题,将trainLinesMap.get(line_label_long)的结果赋给一个临时变量,并从临时变量中调用.getColorInt()。 – pwnsauce

回答

1

我解决了这个通过破坏行:

final int line_color = trainLinesMap.get(line_label_long).getColorInt(); 

到:

Line thisLine = trainLinesMap.get(line_label_long); 
final int line_color = thisLine.getColorInt(); 

我不知道为什么这个工作,但我不再获得NullPointerException异常。