获取java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.setText(java.lang.CharSequence)'

时间:2019-02-20 18:32:21

标签: java android android-fragments nullpointerexception

我在犯罪犯类中出错,该类是

'java.lang.NullPointerException:Attempt to invoke virtual method 
'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference' 

我复制了从亚马逊购买的那本书中粘贴的大部分代码。

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;


public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
    mCrimeRecyclerView = (RecyclerView) view
            .findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    updateUI();
    return view;
}
private void updateUI() {
    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();
    mAdapter = new CrimeAdapter(crimes);
    mCrimeRecyclerView.setAdapter(mAdapter);
}

//

private class CrimeHolder extends RecyclerView.ViewHolder {
    private Crime mCrime;
    private TextView mTitleTextView;
    private TextView mDateTextView;
    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_crime, parent, false));
        mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
    }
    public void bind(Crime crime) {
        mCrime = crime;
        mTitleTextView.setText(mCrime.getmTitle());
        mDateTextView.setText(mCrime.getmDate().toString());
    }
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
    private List<Crime> mCrimes;
    public CrimeAdapter(List<Crime> crimes) {
        mCrimes = crimes;
    }

    @Override
    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        return new CrimeHolder(layoutInflater, parent);
    }

    @Override
    public void onBindViewHolder(CrimeHolder holder, int position) {
        Crime crime = mCrimes.get(position);
        holder.bind(crime);
    }

    @Override
    public int getItemCount() {
        return mCrimes.size();
    }
}
}

//

import android.support.v4.app.Fragment;


public class CrimeActivity extends SingleFragmentActivity {


@Override
protected Fragment createFragment() {
    return new CrimeFragment();
}
}

//

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;

private Button mDateButton;
public CheckBox mSolvedCheckBox;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mCrime = new Crime();
}

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.fragment_crime, container, false);
    mTitleField = (EditText) v.findViewById(R.id.crime_title);
    mTitleField.addTextChangedListener(new TextWatcher() {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count)
        {
            mCrime.setmTitle(s.toString());
        }

        @Override
        public void afterTextChanged(Editable s) {

        }




    });
    mDateButton = (Button) v.findViewById(R.id.crime_date);
    mDateButton.setText(mCrime.getmDate().toString());
    mDateButton.setEnabled(false);
    mSolvedCheckBox = (CheckBox)v.findViewById(R.id.crime_solved);
    mSolvedCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            mCrime.setmSolved(isChecked);
        }
    });
    return v;




}


}

//

import android.content.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class CrimeLab {
private static CrimeLab sCrimeLab;
private List<Crime> mCrimes;
public static CrimeLab get(Context context) {
    if (sCrimeLab == null) {
        sCrimeLab = new CrimeLab(context);
    }
    return sCrimeLab;
}
private CrimeLab(Context context) {
    mCrimes = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        Crime crime = new Crime();
        crime.setmTitle("Crime #" + i);
        crime.setmSolved(i % 2 == 0); // Every other one
        mCrimes.add(crime);
    }
}
public List<Crime> getCrimes() {
    return mCrimes;
}
public Crime getCrime(UUID id) {
    for (Crime crime : mCrimes) {
        if (crime.getmId().equals(id)) {
            return crime;
        }
    }
    return null;
}
}

//

import android.support.v4.app.Fragment;

public class CrimeListActivity extends SingleFragmentActivity {
@Override
protected Fragment createFragment() {
    return new CrimeListFragment();
}
}

//

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;


public class CrimeListFragment extends Fragment {
private RecyclerView mCrimeRecyclerView;
private CrimeAdapter mAdapter;

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_crime_list, container, false);
    mCrimeRecyclerView = (RecyclerView) view
            .findViewById(R.id.crime_recycler_view);
    mCrimeRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
    updateUI();
    return view;
}
private void updateUI() {
    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();
    mAdapter = new CrimeAdapter(crimes);
    mCrimeRecyclerView.setAdapter(mAdapter);
}
private class CrimeHolder extends RecyclerView.ViewHolder {
    private Crime mCrime;
    private TextView mTitleTextView;
    private TextView mDateTextView;
    public CrimeHolder(LayoutInflater inflater, ViewGroup parent) {
        super(inflater.inflate(R.layout.list_item_crime, parent, false));
        mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
        mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);
    }
    public void bind(Crime crime) {
        mCrime = crime;
        mTitleTextView.setText(mCrime.getmTitle());
        mDateTextView.setText(mCrime.getmDate().toString());
    }
}
private class CrimeAdapter extends RecyclerView.Adapter<CrimeHolder> {
    private List<Crime> mCrimes;
    public CrimeAdapter(List<Crime> crimes) {
        mCrimes = crimes;
    }

    @Override
    public CrimeHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
        return new CrimeHolder(layoutInflater, parent);
    }

    @Override
    public void onBindViewHolder(CrimeHolder holder, int position) {
        Crime crime = mCrimes.get(position);
        holder.bind(crime);
    }

    @Override
    public int getItemCount() {
        return mCrimes.size();
    }
}
}

//

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;

public abstract class SingleFragmentActivity extends AppCompatActivity {
protected abstract Fragment createFragment();
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment);

    FragmentManager fm = getSupportFragmentManager();
    Fragment fragment = fm.findFragmentById(R.id.fragment_container);
    if (fragment == null) {
        fragment = createFragment();
        fm.beginTransaction()
                .add(R.id.fragment_container, fragment)
                .commit();
    }
}
}

//activity_fragment.xmml

FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/fragment_container"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CrimeActivity">



</FrameLayout>



//fragment_crime.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp"
android:orientation="vertical">
<TextView
    style="?android:listSeparatorTextViewStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_title_label"/>

<EditText
    android:id="@+id/crime_title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:hint="@string/crime_title_hint" />
<TextView
    style="?android:listSeparatorTextViewStyle"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_details_label"/>
<Button
    android:id="@+id/crime_date"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
<CheckBox
    android:id="@+id/crime_solved"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/crime_solved_label"/>

   </LinearLayout>

//

  //fragment_crime_list.xml

<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/crime_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>



//list_item_crime.xml

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="crime_title"/>
<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/crime_date"
    android:text="crime_date"/>

2 个答案:

答案 0 :(得分:0)

您没有正确找到视图,您正在调用super(),同时尝试从itemView查找textview,但我不在哪里初始化它。请执行以下操作:

替换

Items

使用

    mTitleTextView = (TextView) itemView.findViewById(R.id.crime_title);
    mDateTextView = (TextView) itemView.findViewById(R.id.crime_date);

OR

替换

    mTitleTextView = (TextView) findViewById(R.id.crime_title);
    mDateTextView = (TextView) findViewById(R.id.crime_date);

使用

super(inflater.inflate(R.layout.list_item_crime, parent, false));

答案 1 :(得分:0)

尝试如下

在您的CrimeAdapter的onCreateViewHolder下,将视图传递给CrimeHolder 课

    @NonNull
    @Override
    public CrimeHolder onCreateViewHolder(@NonNull ViewGroup viewGroup,int i){
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View view = layoutInflater.inflate( R.layout.list_item_crime, viewGroup, false );
        // here pass view as a constructor 
        return new CrimeHolder(view);
    }

在您的CrimeHolder中,设置为超类并按以下方式检索其他属性

    private class CrimeHolder extends RecyclerView.ViewHolder{
        private TextView mTitleTextView;
        private TextView mDateTextView;

        CrimeHolder(View view){
            super(view);
            mTitleTextView = view.findViewById(R.id.textView);
            mDateTextView = view.findViewById(R.id.textView2);
        }
    }