0

Я пытаюсь извлечь пользовательский InfoWindowAdapter в отдельный файл класса. Я начал с внутренним классом, который работает идеально:NullPointerException при раздувании пользовательского InfoWindowAdapter

public class FoobarMapActivity extends SherlockFragmentActivity { 

    protected GoogleMap mMap; 
    private final GoogleMap.InfoWindowAdapter mInfoWindowAdapter; 

    public FoobarMapActivity() { 
     mInfoWindowAdapter = new GoogleMap.InfoWindowAdapter() { 

      @Override 
      public View getInfoWindow(Marker marker) { 
       View window = getLayoutInflater().inflate(R.layout.custom_info_window, null); 
       render(marker, window); 
       return window; 
      } 

      @Override 
      public View getInfoContents(Marker marker) { 
       return null; 
      } 

      private void render(Marker marker, View view) { 
       ((ImageView) view.findViewById(R.id.badge)).setImageResource(0); 
       TextView titleTextView = ((TextView) view.findViewById(R.id.title)); 
       TextView snippetTextView = ((TextView) view.findViewById(R.id.snippet)); 
       titleTextView.setText(StringHelper.setTextOrEmpty(marker.getTitle())); 
       snippetTextView.setText(StringHelper.setTextOrEmpty(marker.getSnippet())); 
      } 

     }; 
    } 

Но как только я поставил же код в отдельный класс я бегу в NullPointerException, когда я раздуть макет.

Caused by: java.lang.NullPointerException 
    at android.view.LayoutInflater.from(LayoutInflater.java:210) 
    at com.example.foobar.activities.CustomInfoWindowAdapter.<init>(CustomInfoWindowAdapter.java:20) 
    at com.example.foobar.activities.FoobarMapActivity.<init>(FoobarMapActivity.java:107) 
    at java.lang.Class.newInstanceImpl(Native Method) 
    at java.lang.Class.newInstance(Class.java:1319) 
    at android.app.Instrumentation.newActivity(Instrumentation.java:1023) 
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1887) 

Вот пользовательский класс для InfoWindowAdapter:

package com.example.foobar.activities; 

import android.content.Context; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.widget.ImageView; 
import android.widget.TextView; 

import com.google.android.gms.maps.GoogleMap; 
import com.google.android.gms.maps.model.Marker; 

import com.example.foobar.R; 
import com.example.foobar.utils.StringHelper; 

public class CustomInfoWindowAdapter implements GoogleMap.InfoWindowAdapter { 

    protected View mWindow; 

    public CustomInfoWindowAdapter(Context context) { 
     LayoutInflater inflater = LayoutInflater.from(context); 
     mWindow = inflater.inflate(R.layout.custom_info_window, null); 
    } 

    @Override 
    public View getInfoWindow(Marker marker) { 
     render(marker, mWindow); 
     return mWindow; 


    @Override 
    public View getInfoContents(Marker marker) { 
     return null; 
    } 

    private void render(Marker marker, View view) { 
     ((ImageView) view.findViewById(R.id.badge)).setImageResource(0); 
     TextView titleTextView = ((TextView) view.findViewById(R.id.title)); 
     TextView snippetTextView = ((TextView) view.findViewById(R.id.snippet)); 
     titleTextView.setText(StringHelper.setTextOrEmpty(marker.getTitle())); 
     snippetTextView.setText(StringHelper.setTextOrEmpty(marker.getSnippet())); 
    } 

} 

Здесь я instatiate пользовательского адаптера:

public class FoobarMapActivity extends SherlockFragmentActivity { 

    private final GoogleMap.InfoWindowAdapter mInfoWindowAdapter; 

    public FoobarMapActivity() { 
     mInfoWindowAdapter = new CustomInfoWindowAdapter(getBaseContext()); // line 107 
    } 
+0

Предоставить свой xml custom_info_window – Dimmerg

+0

XML не должен быть проблемой, так как он работает с внутренним классом. – JJD

+0

@MDMalik Пожалуйста, верните свое изменение: я включил импорт цели, так как это может быть причиной проблемы, например. ссылка на 'R.'. – JJD

ответ

0

Я думаю, что у вас есть NullReference в визуализации функции Попробуйте добавить нуль проверка:

private void render(Marker marker, View view) { 
     if (view == null || marker == null) 
      return; 
     ((ImageView) view.findViewById(R.id.badge)).setImageResource(0); 
     TextView titleTextView = ((TextView) view.findViewById(R.id.title)); 
     TextView snippetTextView = ((TextView) view.findViewById(R.id.snippet)); 
     if (titleTextView != null) 
      titleTextView.setText(StringHelper.setTextOrEmpty(marker.getTitle())); 
     if (snippetTextView!= null) 
      snippetTextView.setText(StringHelper.setTextOrEmpty(marker.getSnippet())); 
    } 

Редакции:

Попытки получить LayoutInflater другого пути:

mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

, а также проверить, что контекст не пуст.

EDITED2:

Попробуйте

mInfoWindowAdapter = new CustomInfoWindowAdapter(this); 
+0

Пожалуйста, прочитайте stacktrace. Ошибка возникает, когда макет раздувается в конструкторе 'CustomInfoWindowAdapter'. – JJD

+0

Извините, вы правы. Я обновил свой пост. – Dimmerg

+0

Такое же исключение возникает, когда я использую 'context.getSystemService()' для извлечения надувателя. – JJD

0

Попробуйте использовать getApplicationContext() или контекст вашей деятельности в вместо getBaseContext(). Context context = this; make context globle для вашей деятельности.

+0

Передача 'getApplicationContext()' также вызывает 'NullPointerException. Это также противоречит [как использовать контекст] (http://www.doubleencore.com/2013/06/context/?utm_source=Android+Weekly&utm_campaign=78ad4cb95e-Android_Weekly_64&utm_medium=email&utm_term=0_4eb677ad19-78ad4cb95e-330180005). – JJD

2

Пожалуйста переместить эту строку:

mInfoWindowAdapter = new CustomInfoWindowAdapter(getBaseContext()); 

в onCreate и заменить getBaseContext() с this.

Вы делаете что-то против платформы. onCreate - ваш конструктор, и вы не должны использовать Java-конструктор при работе с Activities.

+2

Действительно, удалите свой конструктор и вместо этого используйте onCreate. Dianne Hackborn (из команды Android) сказала: «Простой ответ: если вы реализуете такой компонент, как Activity, Service и ContentProvider, не реализуйте конструктор (это просто использовать пустой конструктор по умолчанию). Что бы вы ни думали, хотите сделать в конструкторе ... вам очень нравится не делать этого и делать в onCreate() вместо этого ». - https://groups.google.com/forum/#!topic/android-developers/70VaBROqcxg – BoD

+0

Каково было бы ваше предположение, чтобы экземпляр был создан только один раз? – JJD

+1

@JJD 'onCreate' вызывается только один раз сразу после вызова конструктора. –