2010-08-01 3 views
1

довольно долго я пытался решить проблему с помощью Null Pointer Exception при заполнении ViewStub. То, что я пытаюсь сделать, находится в SlidingDrawer, который содержит некоторые кнопки изображения и ViewStubs, чтобы заполнить ViewStubs при нажатии кнопки ImageButton. Я слежу за ViewStub Class Overview, чтобы создать ViewStubs, но я все равно получаю исключение Null Pointer. Если бы кто-то мог мне помочь, это было бы здорово, потому что я действительно больше не знаю, что я должен сделать, чтобы решить эту проблему ... Я отправлю свой код нижеКак решить исключение Null Pointer при попытке заполнить ViewStub?

Спасибо вам большое!


Вот часть моего кода вызывает исключение:

btnExposure = (ImageButton) findViewById(R.id.button_exposure); 

     btnExposure.setOnClickListener(new OnClickListener() 
     { 

     @Override 
    public void onClick(View v) { 
      try{ 
      ViewStub stub = (ViewStub) findViewById(R.id.stub_exposure); 
      importStub = stub.inflate(); 
      }catch (Exception e){ 
       Log.e("ERROR", "Error in Code:" +e.toString());} 
    } 
     }); 

Это файл DrawingSlider XML, содержащий ViewStub:

<?xml version="1.0" encoding="utf-8"?> 

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="@drawable/shape_background_gradient" 
     > 
    <LinearLayout 
     android:layout_width="205px" 
     android:layout_height="155px" 
     android:background="#FFCCCCCC" 
     android:id="@+id/VideoViewHolder" 
     android:padding="2.5px" 
     android:layout_centerHorizontal="true" 
     android:layout_marginTop="5px" 
     android:layout_marginBottom="5px" 
     > 
    <VideoView 
    android:layout_width="200px" 
    android:layout_height="150px" 
    android:id ="@+id/VideoViewEdit" 
    android:layout_centerHorizontal="true" 

    > 
    </VideoView> 
    </LinearLayout> 
    <ScrollView 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_below="@id/VideoViewHolder"> 
    <TableLayout 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:stretchColumns="0"> 
    <TableRow 
     android:background="@drawable/shape_track_background" 
     android:padding="5px" 
     > 
    <ImageView android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/ic_editor_videotrack" 
      android:padding="5px" 
      android:layout_gravity="left"/> 

    </TableRow> 
    <TableRow 
     android:background="@drawable/shape_track_background" 
     android:padding="5px" 
     > 
     <ImageView android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/ic_editor_audiotrack" 
      android:padding="5px" 
      android:layout_gravity="left"/> 


    </TableRow> 
    <TableRow 
     android:background="@drawable/shape_track_background" 
     android:padding="5px" 
     > 
    <ImageButton android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:src="@drawable/ic_editor_add_media" 
      android:padding="5px" 
      android:layout_gravity="left" 
      /> 
    </TableRow> 
    </TableLayout> 
    </ScrollView> 
<SlidingDrawer 
    android:id="@+id/drawer" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal" 
    android:handle="@+id/handle" 
    android:content="@+id/content"> 

    <ImageView 
     android:id="@id/handle" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:src="@drawable/slider_handle" 
     /> 

    <LinearLayout 
     android:id="@id/content" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:orientation="vertical"> 
     <ImageButton 
     android:id="@+id/button_exposure" 
     android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#77000000" 
    android:src="@drawable/ic_slider_exposure" 
    android:padding="5px" 
    android:layout_marginBottom="1px" 
    android:layout_gravity="left"/> 
     <ImageButton 
     android:id="@+id/button_properties" 
     android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#77000000" 
    android:src="@drawable/ic_slider_properties" 
    android:padding="5px" 
    android:layout_marginBottom="1px" 
    android:layout_gravity="left"/> 
     <ImageButton 
     android:id="@+id/button_special_effects" 
     android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#77000000" 
    android:src="@drawable/ic_slider_special_effects" 
    android:padding="5px" 
    android:layout_marginBottom="1px" 
    android:layout_gravity="left"/> 
    <ImageButton 
     android:id="@+id/button_test1" 
     android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#77000000" 
    android:src="@drawable/ic_slider_exposure" 
    android:padding="5px" 
    android:layout_marginBottom="1px" 
    android:layout_gravity="left"/> 
     <ImageButton 
     android:id="@+id/button_test2" 
     android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="#77000000" 
    android:src="@drawable/ic_slider_exposure" 
    android:padding="5px" 
    android:layout_marginBottom="1px" 
    android:layout_gravity="left"/> 
    </LinearLayout> 
    <ViewStub 
     android:id="@+id/stub_exposure" 
     android:inflatedId="@+id/stub_exposure_view" 

     android:layout="@layout/exposureview" 

     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="#77000000"> 
    </ViewStub> 
    <ViewStub 
     android:id="@+id/stub_properties" 
     android:inflatedId="@+id/stub_properties_view" 

     android:layout="@layout/propertiesview" 

     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="#77000000"> 
    </ViewStub> 
    <ViewStub 
     android:id="@+id/stub_special_effects" 
     android:inflatedId="@+id/stub_special_effects_view" 

     android:layout="@layout/specialeffectsview" 

     android:layout_width="fill_parent" 
     android:layout_height="wrap_content" 
     android:background="#77000000"> 
    </ViewStub> 
</SlidingDrawer> 
</RelativeLayout> 

И это расположение XML ViewStub (exposureview.xml), который вызывается для раздувания заглушки:

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
> 
<TextView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="@+String/hello" 
></TextView> 
<SeekBar 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:thumb="@drawable/seek_thumb" 
    android:progress="50" 
    android:max="100"> 
</SeekBar> 

</RelativeLayout> 
+0

В какой строке находится NPE? – JRL

+0

в этой строке 'importStub = stub.inflate();' – kivy

ответ

0

Видимо, findViewById(R.id.stub_exposure); возвращает null для вас. Вы правильно перекомпилировали свой класс, чтобы восстановить файл R.java?

Кроме того, я заметил, что вы определили одно текстовое свойство вашего текстового вида в своем представлении XML-файла заглушки как android:text="@+String/hello".

Не знаю, является ли это опечаткой или нет, но имеет ли должным образом R.java? Если у вас есть существующее значение в strings.xml (обратите внимание на заглавные буквы), компилятор должен подать жалобу.

Вам следует попытаться выполнить проект -> Очистить, чтобы узнать, получаете ли вы предупреждения или ошибки (если вы используете Eclipse).

+0

android: text = "@ + String/hello" Это была действительно глупая опечатка, но я исправил ее и по-прежнему получаю ту же ошибку. И я также очистил проект, но у меня нет никаких предупреждений или ошибок :( Что вы подразумеваете под «правильной перекомпиляцией класса и восстановлением файла R.java снова»? – kivy

+0

Я имел в виду, что вы скомпилировали класс и файл R.java был регенерирован. Вы проверяли, существует ли идентификатор 'stub_exposure' в сгенерированном' R.java'? – JRL

+0

Он существует: 'public static final int stub_exposure = 0x7f06000a;' – kivy

0

Как подозреваемых JrL, это потому, что findViewById(R.id.stub_exposure) не находит/см/поймать stub_exposure хотя идентификатор хорошо генерируется в R.class, а затем, метод возвращает null и когда inflate() называется ничего не происходит, потому что stub все еще не инициализирован, это всего лишь объект null. Вы можете увидеть это, используя отладчик.

Таким образом, мы можем видеть, что, возможно, есть некоторые проблемы с синтаксическим анализатором или компилятором XML. Я решил проблему, поставив View на использование StubView из одного выделенного файла XML в файл XML, где у меня был основной интерфейс с более Layout и View. Я положил его внутри первого родителя Layer, который был , но мне пришлось встроить его в FrameLayout вместе с моим StubView, чтобы все токи Layer появлялись. Я думаю, что это должно быть важно, потому что у вас также есть StubView s внутри Layer s, но это не сработает. Поэтому постарайтесь поставить StubView s на разные уровни иерархии.

0

Надувание или отображение ViewStub приводит к его удалению из макета (вся его точка должна быть заменена другим видом). Ваш метод onClick будет работать только в первый раз. Вы должны (а) проверить нуль, возвращаемый из findViewById, и (б) использовать идентификатор вида, который вы надуваете в заглушку после инфляции.