Иногда получает значение NULL от (View) .findViewByID - PullRequest
1 голос
/ 08 декабря 2011

У меня есть приложение для Android @ Android Market.И я продолжаю получать сообщения о сбоях, в которых утверждается, что некоторые пользователи получают исключение NullPointerException.

Я обнаружил код, который, по-видимому, вызывает эту проблему.

Это метод getView ArrayAdapters.

if (v == null) {
                LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                v = vi.inflate(R.layout.subcatategory_row, null);
                holder = new ViewHolder();
                v.setTag(holder);
            }
            else {
                holder=(ViewHolder)v.getTag();

                if(holder == null){
                    holder = new ViewHolder();

                }
            }



            TextView tl = (TextView) v.findViewById(R.id.label);

            tl.setTextAppearance(getContext(), R.style.styleA);

Последняя строка в этом фрагменте, похоже, вызывает сбой.Однако я никогда не испытывал это, и я проверял это на нескольких устройствах.

Помощь будет принята с благодарностью !!

РЕДАКТИРОВАТЬ:

subcategory_row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/row_layout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="0dip"
    android:background="@drawable/background"
    android:weightSum="80">

    <TextView
        android:id="@+id/label"
        android:layout_weight="9"
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_marginRight="6dip"
        android:gravity="center_vertical|center"
        android:text="C.r"
        android:textSize="12sp"
        android:textColor="@color/default_textcolor"
        />

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dip"
        android:layout_weight="53"
        android:layout_height="fill_parent">
        <TextView
            android:id="@+id/text_bb"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:layout_marginLeft="4dip"
            android:gravity="bottom"
            android:textSize="13sp"
            android:textColor="@color/default_textcolor"

        android:ellipsize="end" android:singleLine="true"/>
        <TextView
            android:id="@+id/text_ba"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:layout_marginLeft="4dip"
            android:gravity="top"
            android:textSize="13sp"
            android:textColor="@color/default_textcolor"
        android:ellipsize="end" android:singleLine="true"/>
    </LinearLayout>

    <LinearLayout
        android:orientation="vertical"
        android:layout_width="0dip"
        android:layout_weight="8"
        android:layout_height="fill_parent"
        >
        <TextView
            android:id="@+id/text_a"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:gravity="bottom|right"
            android:textSize="13sp"
            android:text="0"
            android:textColor="@color/default_textcolor"
        />
        <TextView
            android:id="@+id/text_b"
            android:layout_width="fill_parent"
            android:layout_height="0dip"
            android:layout_weight="1"
            android:gravity="top|right"
            android:textSize="19sp"
            android:text="0"
            android:textColor="@color/default_textcolor"
        />
    </LinearLayout>


   <LinearLayout
       android:layout_width="0dip"
       android:layout_height="wrap_content"
       android:layout_gravity="center_vertical|right"
       android:layout_weight="10"
       android:orientation="vertical"
       android:paddingLeft="10dp" >

       <ImageView
           android:id="@+id/arrow"
           android:layout_width="wrap_content"
           android:layout_height="40dp"
           android:paddingLeft="-10dip"
           android:paddingRight="10dip"
           android:src="@drawable/arrow"
           android:visibility="visible" />

   </LinearLayout>

</LinearLayout>

Ответы [ 2 ]

1 голос
/ 08 декабря 2011

У меня также была эта проблема в опубликованных приложениях. После долгих поисков души я воссоздал его - двумя разными способами!

Причина 1) Оказывается, причина, по которой он нулевой, заключается в том, что в то время не было памяти для его выделения. Просто нужно было написать больше защитного кода и завершить работу.

Причина 2) Далвик в некоторых случаях убедился, что я им не пользуюсь, и освободил его. Мне пришлось изменить свой код, чтобы убедиться, что в глазах Далвика он более «зацеплен».

Однако 9 раз из 10 это была причина 1.

Проблема в том, что вы не можете воспроизвести его, когда используете тестовые устройства, у других людей одновременно работают все виды вещей.

1 голос
/ 08 декабря 2011

Вы должны хранить TextView внутри вашего объекта ViewHolder

Вот пример того, что я использовал

class DataObjectContainer {
    TextView title;
}

public View getView(final Activity activity, View convertView, ViewGroup parent) {

    final DataObjectContainer container;

    if (convertView == null) {
        convertView = (LinearLayout) activity.getLayoutInflater().inflate(R.layout.dataobjectitem, null);

        container = new DataObjectContainer();

        container.title = (TextView) convertView.findViewById(R.id.textview_title);

        convertView.setTag(container);

    } else {
        container = ((DataObjectContainer) convertView.getTag());
    }

    container.title.setText(getValueString(DataObject.Table.NAME));

    return convertView;

}
...