2014-02-03 3 views
0

Примечание: я refered подобные вопросы и до сих пор не может найти какие-либо ошибкиNullPointerException в addHeaderView и setAdapter


NullPointerException на

listView.addHeaderView(header); 

И

listView.setAdapter(adapter); 

подробный код:

Veg v = new Veg(); 
v.setId(1); 
v.setName("some"); 
v.setPrice(15.0); 

List<Veg> vegData = new ArrayList<Veg>(); 

// dummy add for testing 
vegData.add(v); 
vegData.add(v); 
vegData.add(v); 

CustomAdapter adapter = new CustomAdapter(this, 
     R.layout.custom_list_rows, vegData); 
listView = (ListView) findViewById(R.id.listView1); 


View header = getLayoutInflater().inflate(
     R.layout.custom_list_header, null); 

listView.addHeaderView(header); 

listView.setAdapter(adapter); 

GetView() часть

public class CustomAdapter extends ArrayAdapter<Veg> { 

    Context context; 
    int layoutResourceId; 
    List<Veg> data; 

    public CustomAdapter(Context context, int resource, List<Veg> data) { 
     super(context, resource); 
     this.context = context; 
     this.layoutResourceId = resource; 
     this.data = data; 
    } 

    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     View row = convertView; 
     CustomHolder holder = null; 

     if (row == null) { 
      LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
      row = inflater.inflate(layoutResourceId, parent, false); 

      holder = new CustomHolder(); 
      holder.at = (TextView) row.findViewById(R.id.customheaderbutton1); 
      holder.bt = (TextView) row.findViewById(R.id.customheaderbutton2); 
      holder.ct = (TextView) row.findViewById(R.id.customheaderbutton3); 
      row.setTag(holder); 
     } else { 
      holder = (CustomHolder) row.getTag(); 
     } 

     holder.at.setText(String.valueOf(data.get(position).getId())); 
     holder.bt.setText(data.get(position).getName()); 
     holder.ct.setText(String.valueOf(data.get(position).getPrice())); 

     return row; 
    } 

    static class CustomHolder { 
     TextView at; 
     TextView bt; 
     TextView ct; 
    } 

} 

Основная деятельность XML-файл

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:background="#FFFFFF"> 

    <ListView 
     android:id="@+id/listView1" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" /> 

</LinearLayout> 

custom_list_header.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" > 

    <Button 
     android:id="@+id/customheaderbutton1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.8" 
     android:text="marketname" /> 

    <Button 
     android:id="@+id/customheaderbutton2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.1" 
     android:text="edit" /> 

    <Button 
     android:id="@+id/customheaderbutton3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.1" 
     android:text="+" /> 

</LinearLayout> 

custom_list_rows.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 

    <TextView 
     android:id="@+id/elementIDtext" 
     android:layout_width="11dp" 
     android:layout_height="wrap_content" 
     android:text="" 
     android:textAppearance="?android:attr/textAppearanceSmall" /> 

    <TextView 
     android:id="@+id/elementName" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="0.30" 
     android:text="@string/elementName" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <TextView 
     android:id="@+id/elementSummary" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="@string/elementValue" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="62dp" 
     android:layout_height="wrap_content" 
     android:text="@string/_" /> 

</LinearLayout> 
+0

разместить макет XML и код, в котором вы установите раскладку на активность – Raghunandan

+0

почтового кода из GetView() .. – Ranjit

+2

Узнайте, что нуль - проверка ваш логарифм. Затем убедитесь, что он не равен нулю. Я думаю, что это 'listView'. – 323go

ответ

1

Похоже listView это null, что означает findViewById() вернулся null: он не мог найти контроль, который вы ищете , Не видя своего макета, нет возможности отлаживать его дальше, но убедитесь, что R.id.listView1 ссылается на действительный элемент.

+0

Это будет комментарий, а не ответ.Вы запрашиваете дополнительную информацию. – 323go

+0

@ 323go Учитывая предоставленную информацию, это лучший ответ, который любой может ему дать. Если появится больше информации, я обновлю этот ответ. В этом нет ничего плохого. Пересмотрите ваш downvote. – TypeIA

+0

И если дополнительная информация не * становится доступной, то ваш комментарий просто добавляет шум в Stackoverflow. Пожалуйста, пересмотреть свой «ответ» и опубликовать его, как только у вас есть информация, чтобы ответить на него. – 323go

1

В GetView, изменить

holder.at = (TextView) row.findViewById(R.id.customheaderbutton1); 
    holder.bt = (TextView) row.findViewById(R.id.customheaderbutton2); 
    holder.ct = (TextView) row.findViewById(R.id.customheaderbutton3); 

в

holder.at = (TextView) row.findViewById(R.id.elementIDtext); 
    holder.bt = (TextView) row.findViewById(R.id.elementName); 
    holder.ct = (TextView) row.findViewById(R.id.elementSummary); 
+0

yup am check it –

+0

Вы помогли мне избежать другой ошибки. спасибо за помощь :) –

0

Заменить код С ниже:

package com.example.listview; 

import java.util.ArrayList; 

import android.app.Activity; 
import android.content.Context; 
import android.os.Bundle; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.ViewGroup; 
import android.widget.ArrayAdapter; 
import android.widget.ListView; 
import android.widget.TextView; 

public class List extends Activity 
{ 
    private ListView listview; 
    Veg Veg = new Veg(); 
    ArrayList<Veg> data = new ArrayList<Veg>(); 
    CustomAdapter adapter; 
    @Override 
    protected void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_list); 

     listview = (ListView)findViewById(R.id.listView); 

     for(int i=1;i<101;i++) 
     { 
      Veg = new Veg(); 
      Veg.setName("Item "+i); 
      Veg.setID("ID "+i); 
      Veg.setPrice("Price "+i); 

      data.add(Veg); 
     } 

     View headerView = getLayoutInflater().inflate(
        R.layout.custom_list_header, null); 


       listview.addHeaderView(headerView); 

       adapter = new CustomAdapter(this,R.layout.custom_list_rows,data); 
       listview.setAdapter(adapter); 
    } 

    class CustomAdapter extends ArrayAdapter<Veg> 
    { 
     Context con; 
     int Res; 
     ArrayList<Veg> data; 
     public CustomAdapter(Context context, int resource, ArrayList<Veg> data) { 
      super(context, resource,data); 
      // TODO Auto-generated constructor stub 
      con = context; 
      Res = resource; 
      this.data = data; 
     } 

     @Override 
     public View getView(int position, View convertView, ViewGroup parent) { 
      View row = convertView; 
      CustomHolder holder = null; 

      if (row == null) { 
       LayoutInflater inflater = getLayoutInflater(); 
       row = inflater.inflate(Res, parent, false); 

       holder = new CustomHolder(); 
       holder.at = (TextView) row.findViewById(R.id.elementIDtext); 
       holder.bt = (TextView) row.findViewById(R.id.elementName); 
       holder.ct = (TextView) row.findViewById(R.id.elementSummary); 
       row.setTag(holder); 
      } else { 
       holder = (CustomHolder) row.getTag(); 
      } 

      holder.at.setText(String.valueOf(data.get(position).getID())); 
      holder.bt.setText(data.get(position).getName()); 
      holder.ct.setText(String.valueOf(data.get(position).getPrice())); 

      return row; 
     } 

     class CustomHolder { 
      TextView at; 
      TextView bt; 
      TextView ct; 
     } 

    } 
} 

Также вы должны изменить свой XML-то, как ниже вместо давая статическую ширину, как 11 дп.

custom_list_rows.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:orientation="horizontal" > 

    <TextView 
     android:id="@+id/elementIDtext" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:text="ID" 
     android:gravity="center" 
     android:textAppearance="?android:attr/textAppearanceSmall" /> 

    <TextView 
     android:id="@+id/elementName" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:text="elementName" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <TextView 
     android:id="@+id/elementSummary" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:text="elementValue" 
     android:textAppearance="?android:attr/textAppearanceLarge" /> 

    <Button 
     android:id="@+id/button1" 
     android:layout_width="0dp" 
     android:layout_height="wrap_content" 
     android:layout_weight="1" 
     android:text="btn" /> 

</LinearLayout> 
+0

Попробуйте этот код. Я сделал небольшую модификацию в вашем коде. Я тестировал это и работал как Charm. –

+0

ОК плохо попробуйте и обновите :) –

+0

Не забудьте принять мой ответ, если он работает, или вам нравится :-) –

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