固定字符串的意外nullPointerException

时间:2018-02-24 15:50:59

标签: java android nullpointerexception

在这个片段中,

public class BlankFragment extends Fragment {

  public BlankFragment() {
    // Required empty public constructor
  }


  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
    RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
    rv.setNestedScrollingEnabled(false);
    SimpleDateFormat localDateFormat = new SimpleDateFormat("HH:mm");

    SunTimes suntime = SunTimes.compute().at(latlang.Lat,latlang.Lang).today().execute();
    String sun_rise = localDateFormat.format(suntime.getRise());
    String sun_set  = localDateFormat.format(suntime.getSet());
    Date sunnoon = suntime.getNoon();
    System.out.println("SUNRISE "+ sun_rise);


    TextView cityField = rootView.findViewById(R.id.tv_city);
    TextView sunrise = rootView.findViewById(R.id.tv_sunrt);
    TextView sunset = rootView.findViewById(R.id.tv_sunst);

    cityField.setText("Hello World");   //Line 45
    sunrise.setText(sun_rise);
    sunset.setText(sun_set);
    return rootView;
  }

我收到错误:

  java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
  at com.example.phocast.BlankFragment.onCreateView(BlankFragment.java:45)
  at android.support.v4.app.Fragment.performCreateView(Fragment.java:2354)

问题是,当我将普通字符串作为文本时,它如何获得零点异常?

我做错了什么?

更新 fragment_blank没有id,因为它只是一个inflater:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <android.support.v4.widget.SwipeRefreshLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/swiperefresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <android.support.v7.widget.RecyclerView
            android:id="@+id/rv_recycler_view"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
        </android.support.v7.widget.RecyclerView>
    </android.support.v4.widget.SwipeRefreshLayout>
</RelativeLayout>

该ID位于item_blank.xml中:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="120sp" >

    <android.support.v7.widget.CardView
        android:id="@+id/card_view"
        xmlns:card_view="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_margin="10dp"
        android:layout_height="120sp"
        card_view:cardCornerRadius="4dp"
        card_view:elevation="14dp">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <ImageView
                android:id="@+id/iv_image"
                android:layout_width="120sp"
                android:layout_height="fill_parent"
                android:scaleType="fitStart"
                card_view:srcCompat="@drawable/property_image_3">
            </ImageView>

            <TextView
                android:id="@+id/tv_city"
                android:layout_width="wrap_content"
                android:layout_height="30sp"
                android:layout_marginBottom="1sp"
                android:layout_toRightOf="@+id/iv_image"
                android:gravity="top"
                android:paddingLeft="5sp"
                android:text="Hello World"
                android:textAppearance="@style/TextAppearance.AppCompat.Large">
            </TextView>
.....

并在适配器中定义:

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
    private String[] mDataset;

    // Provide a reference to the views for each data item
    // Complex data items may need more than one view per item, and
    // you provide access to all the views for a data item in a view holder
    public static class MyViewHolder extends RecyclerView.ViewHolder {
        public CardView mCardView;
        public TextView mTextView;
        public MyViewHolder(View v) {
            super(v);

            mCardView = (CardView) v.findViewById(R.id.card_view);
            mTextView = (TextView) v.findViewById(R.id.tv_city);
        }
    }

    // Provide a suitable constructor (depends on the kind of dataset)
    public MyAdapter(String[] myDataset) {
        mDataset = myDataset;
    }

    // Create new views (invoked by the layout manager)
    @Override
    public MyAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent,
                                                     int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.card_item, parent, false);
        // set the view's size, margins, paddings and layout parameters
        MyViewHolder vh = new MyViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, final int position) {
        holder.mTextView.setText(mDataset[position]);
        holder.mCardView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String currentValue = mDataset[position];
                Log.d("CardView", "CardView Clicked: " + currentValue);
            }
        });
    }

    @Override
    public int getItemCount() {
        return mDataset.length;
    }
}

所以我期待从适配器读取cardview,因为它适用于这种情况:

public class BlankFragment extends Fragment {

  public BlankFragment() {
    // Required empty public constructor
  }
//
//  @Override
//  public void onCreate(Bundle savedInstanceState) {
//    super.onCreate(savedInstanceState);
//
//  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
                           Bundle savedInstanceState) {

    // Inflate the layout for this fragment
    final View rootView = inflater.inflate(R.layout.fragment_blank, container, false);

    RecyclerView rv = rootView.findViewById(R.id.rv_recycler_view);
    rv.setNestedScrollingEnabled(false);

    Weather_OWM.placeIdTask asyncTask = new Weather_OWM.placeIdTask(new Weather_OWM.AsyncResponse() {
      public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn, String weather_iconText, String sun_rise, String sun_set) {

        TextView cityField = rootView.findViewById(R.id.tv_city);
        TextView sunrise = rootView.findViewById(R.id.tv_sunrt);
        TextView sunset = rootView.findViewById(R.id.tv_sunst);

        cityField.setText(weather_city);
        sunrise.setText(sun_rise);
        sunset.setText(sun_set);
      }

    });
    asyncTask.execute(Double.toString(latlang.Lat), Double.toString(latlang.Lang)); //  asyncTask.execute("Latitude", "Longitude")

    rv.setHasFixedSize(true);
    MyAdapter adapter = new MyAdapter(new String[]{"Today", "Golden Hour", "Blue Hour", "Civil Twilight", "Nautical Twilight", "Astronomical Twilight", "Hello", "World"});
    rv.setAdapter(adapter);

    LinearLayoutManager llm = new LinearLayoutManager(getActivity());
    rv.setLayoutManager(llm);

    return rootView;
  }
}

1 个答案:

答案 0 :(得分:0)

这不是字符串参数,而是cityField TextView您正在调用setText()。你正在用

初始化它
rootView.findViewById(R.id.tv_city);

如果找不到视图,则返回null。因此,您的fragment_blank布局没有ID为tv_city的视图。