2013-10-26 2 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 правильно инициализирован и заполнен значениями. Он успешно повторяется в первом цикле, поэтому я знаю, что там есть значения. Но при доступе к LinkedHashMap из моего анонимного внутреннего класса он всегда равен нулю.

Мне удалось получить доступ к массиву String из этого внутреннего класса, почему я не могу получить доступ к LinkedHashMap?

+0

вы можете, NPE, скорее всего, от вашей карты, прямо перед тем, что линия добавить "System.err.println (line_label_long +": "+ trainLinesMap.get (line_label_long));" это, вероятно, будет null –

+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(); 

Я не знаю, почему это работает, но я больше не получите NullPointerExceptions.

Смежные вопросы