Android TextView SetText null对象引用错误

时间:2016-09-19 04:27:48

标签: java android listview android-fragments android-arrayadapter

我是Android新手,我正在接受

Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
我的应用上的

错误。我已经在这里阅读了其他问题- java.lang.NullPointerException - setText on null object reference,但我仍然遇到同样的问题。我的格式有点不同,因为这是在片段中完成的,而我正在做的是从列表视图中获得自定义适配器。这是我的代码

fragment_song_genre.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:bind="http://schemas.android.com/tools">

<data class="SongGenreBinding">

    <variable
        name="handler"
        type="com.mgrmobi.joox.fragments.FilterSongGenreFragment" />

</data>

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#000">

    <RelativeLayout
        android:id="@+id/toprow"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="24dp">

        <ImageButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="16dp"
            android:background="@null"
            android:onClick="@{ handler.onCloseClicked }"
            android:src="@drawable/search_close" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_centerVertical="true"
            android:layout_marginLeft="80dp"
            android:text="Genre"
            android:textColor="#fff"
            android:textSize="20sp" />

        <TextView
            android:onClick="@{ handler.reset }"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:layout_marginRight="15dp"
            android:text="@string/reset"
            android:textAllCaps="true"
            android:textColor="#fff"
            android:textSize="12sp" />

    </RelativeLayout>

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/toprow"
        android:layout_marginTop="24dp"></ListView>

</RelativeLayout>

这是主页面,它在Bottom中有一个Listview,这里是调用xml布局的片段

 public class FilterSongGenreFragment extends BaseFragment {

    private SongGenreBinding binding;
    private ArrayList<String> genres;
    String[] names= {"Johm","Paul","Mike"};

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
    }


    private static final String GENRES_KEY = "genres";

    public static FilterSongGenreFragment newInstance(ArrayList<String> genres) {

        Bundle args = new Bundle();
        args.putStringArrayList(GENRES_KEY, genres);
        FilterSongGenreFragment fragment = new FilterSongGenreFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_song_genre, container, false);
        binding.setHandler(this);
        genres = getArguments().getStringArrayList(GENRES_KEY);

        initList();
        return binding.getRoot();
    }

    private void initList() {

    // ArrayAdapter adapter = new ArrayAdapter(getActivity(), R.layout.genre_list_text, android.R.id.text1, genres);
     FilterSongsAdapter filterSongsAdapter= new FilterSongsAdapter(getActivity(),names);


        binding.list.setAdapter(filterSongsAdapter);

        binding.list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> adapterView, View view,int position, long l) {
               ((SongFilterListener) getActivity()).onGenreSelected(genres.get(position));
/*
                    textView = (ImageView) view.findViewById(R.id.selected_genre);
                    textView.setVisibility(View.VISIBLE);
*/
              //  close();
            }

        });

    }

    private void close() {
        getActivity().getFragmentManager().beginTransaction().remove(this).commit();
    }

    public void onCloseClicked(View view) {
        close();
    }

    public void reset(View view) {
        ((SongFilterListener) getActivity()).onResetFilters();
        close();
    }

}

以下是listview自定义样式的xml genre_list_text.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="wrap_content"
    android:orientation="horizontal">

    <TextView
    android:id="@android:id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:gravity="center_vertical|left"
    android:text="Genre"
    android:paddingBottom="16dp"
    android:paddingLeft="4dp"
    android:paddingTop="16dp"
    android:textColor="#fff"
    android:textSize="16sp" />

        <ImageView
            android:id="@+id/selected_genre"
            android:layout_height="24dp"
            android:layout_width="24dp"
            android:visibility="invisible"
            android:src="@drawable/check_circle"
            android:layout_marginStart="140dp"
            android:layout_centerVertical="true" />

    </RelativeLayout>

这是我的适配器,如前所述,在SetText区域发生错误

  public class FilterSongsAdapter extends ArrayAdapter<String> {

    private Context c;
    String[] names= {};
    LayoutInflater inflater;

    public FilterSongsAdapter(Context context,String[] names) {
        super(context,R.layout.genre_list_text,names);
        this.c=context;
        this.names=names;

    }

    public static class ViewHolder {

       TextView text1;


    }



    @Override
    public View getView(int position,View convertView,ViewGroup parent) {
        ViewHolder holder;
     if(convertView==null){
         holder  = new ViewHolder();
         inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
         convertView = inflater.from(c).inflate(R.layout.genre_list_text, null);
         // Initialize
         holder.text1=(TextView) convertView.findViewById(R.id.text1);

          convertView.setTag(holder);
    }else {
         holder = (ViewHolder) convertView.getTag();
     }

        holder.text1.setText(names[position]);

        return convertView;
    }




}

GetView中的SetText每次抛出异常,TextView应该有名字字符串数组中的3个对象名称,我已经看到它有。基于错误,我知道我在FindByID方法找到TextView之前设置了SetText,但是我已经移动了一些东西并且没有任何效果。任何帮助都会很棒。我也一直在关注本教程以供参考https://www.youtube.com/watch?v=99C_UpLcBRk。我不知道是否有片段的东西是不同的。

3 个答案:

答案 0 :(得分:4)

在您的布局中,您已将默认ID设为TextView android:id="@android:id/text1"

并在JAVA文件中提供R.id.text1

在xml或java中进行更改。

以xml从android:id="@android:id/text1"更改为android:id="@+id/text1" 或者在java android.R.id.text1

答案 1 :(得分:0)

@Override
public View getView(int position,View convertView,ViewGroup parent) {
 ViewHolder holder  = new ViewHolder(); //because error says null object reference, it means object of TextView `text1` is not found.
 inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 if(convertView==null){

     convertView = inflater.inflate(R.layout.genre_list_text, null);

     holder.text1=(TextView) convertView.findViewById(R.id.text1);
     holder.text1.setText(names[position]);
     convertView.setTag(holder);

}else {
     holder = (ViewHolder) convertView.getTag();
 }
 return convertView;
}

根据您提供的XML代码,我发现您没有为TextView提供正确的ID。将XMLandroid:id="@android:id/text1"更改为android:id="@+id/text1"

答案 2 :(得分:0)

在你的genre_list_text.xml中将android:id =“@ android:id / text1”更改为android:id =“@ + id / text1”

和你的getView方法

Object.keys