Android:带有notifyDataSetChanged()的NullPointerException

时间:2017-01-16 14:28:34

标签: java android nullpointerexception adapter notifydatasetchanged

当我想用CardView和RecyclerView更新我的适配器时,我有一个错误:NullPointerException。但我的适配器已经公布了,'adapter!= null'。

为什么会出现此错误?

我的片段:

public class EntreatyTab extends AbstractTab {
    private static final int LAYOUT = R.layout.entreaty_tab;
    private RecyclerView mRecyclerView;

    private RecyclerView.LayoutManager mLayoutManager;
    private CardViewAdapter mAdapter;
    private ArrayList<CardViewEntreaty> strtex = new ArrayList<>();

    public static EntreatyTab getInstance(Context context) {
        Bundle args = new Bundle();
        EntreatyTab fragment = new EntreatyTab();
        fragment.setArguments(args);

        fragment.setContext(context);
        fragment.setTitle(context.getString(R.string.entreaty_tab));

        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        view = inflater.inflate(LAYOUT,container, false);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.RecyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(view.getContext());
        mRecyclerView.setLayoutManager(mLayoutManager);
        strtex.add(new CardViewEntreaty("a","a",1,1,1));
        mAdapter = new CardViewAdapter(strtex);
        mRecyclerView.setAdapter(mAdapter);
        return view;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public void updateAdapter() {
        mRecyclerView.getAdapter().notifyDataSetChanged();
    }
}

我的适配器:

public class CardViewAdapter extends RecyclerView.Adapter<CardViewAdapter.ViewHolder> {
     private ArrayList<CardViewEntreaty> mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView; 

        public ViewHolder(View  v) {
            super(v);
            mTextView = (TextView) v.findViewById(R.id.editFrom);
        }
    } 

    public CardViewAdapter(ArrayList<CardViewEntreaty> myDataset) {
        this.mDataset = myDataset;
    }

    @Override
    public CardViewAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
        // create a new view
        View v = LayoutInflater.from(parent.getContext())
             .inflate(R.layout.card_view, parent, false);
        ViewHolder vh = new ViewHolder(v);
        return vh;
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        CardViewEntreaty card = mDataset.get(position);
        holder.mTextView.setText(card.getFrom());
    }

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

然后我的班级用CardView的对象:

public class CardViewEntreaty implements Parcelable {
    private String from;
    private String target;
    private int endYear;
    private int endMonth;
    private int endDay;

    public CardViewEntreaty(String from, String target, int endYear, int endMonth, int endDay) {
        this.from = from;
        this.target = target;
        this.endYear = endYear;
        this.endMonth = endMonth;
        this.endDay = endDay;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getTarget() {
        return target;
    }

    public void setEndYear(int endYear) {
        this.endYear = endYear;
    }

    public void setEndMonth(int endMonth) {
        this.endMonth = endMonth;
    }

    public void setEndDay(int endDay) {
        this.endDay = endDay;
    }

    public int getEndDay() {

        return endDay;
    }

    public int getEndMonth() {
        return endMonth;
    }

    public void setTarget(String target) {

        this.target = target;
    }

    public int getEndYear() {

        return endYear;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(from);
        dest.writeString(target);
        dest.writeInt(endYear);
        dest.writeInt(endMonth);
        dest.writeInt(endDay);
    }
}

我的错误记录

01-16 16:57:51.857 29550-29550/com.magicarm.helpener E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.magicarm.helpener, PID: 29550
java.lang.NullPointerException
   at com.example.magicarm.helpener.fragment.EntreatyTab$override.updateAdapter(EntreatyTab.java:63)
   at com.example.magicarm.helpener.fragment.EntreatyTab$override.access$dispatch(EntreatyTab.java)
   at com.example.magicarm.helpener.fragment.EntreatyTab.updateAdapter(EntreatyTab.java:0)
   at com.example.magicarm.helpener.MainActivity$8.onDateSet(MainActivity.java:245)
   at android.app.DatePickerDialog.tryNotifyDateSet(DatePickerDialog.java:148)
   at android.app.DatePickerDialog.onClick(DatePickerDialog.java:116)
   at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:136)
   at android.app.ActivityThread.main(ActivityThread.java:5045)
   at java.lang.reflect.Method.invokeNative(Native Method)
   at java.lang.reflect.Method.invoke(Method.java:515)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
   at dalvik.system.NativeStart.main(Native Method)

感谢您的帮助

已编辑:添加我的MainActivity,但不是完整的

package com.example.magicarm.helpener;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.app.DatePickerDialog.OnDateSetListener;
import android.os.Bundle;
import android.app.AlertDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;

import com.example.magicarm.helpener.adapter.TabsPagerFragmentAdapter;
import com.example.magicarm.helpener.fragment.EntreatyTab;

import java.util.ArrayList;
import java.util.Calendar;


public class MainActivity extends AppCompatActivity {

    private static final int LAYOUT = R.layout.activity_main;//Главное окно

    private Toolbar toolbar;
    private DrawerLayout drawerLayout;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private ActionBarDrawerToggle actionBarDrawerToggle; // Кнопка меню, анимация
    private Calendar dateAndTime=Calendar.getInstance();
    private DatePickerDialog dpd;
    public ArrayList<CardViewEntreaty> create_new_item;
    private String from,target;
    private int endYear,endMonth,endDay;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppDefault); // Тема
        super.onCreate(savedInstanceState);
        setContentView(LAYOUT);

        initToolbar(); // Загрузка toolbar
        initNavigationView(); // Боковое меню
        initTab(); // Вкладки


    }

    private void initTab() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);

        TabsPagerFragmentAdapter adapter = new TabsPagerFragmentAdapter(this, getSupportFragmentManager()); // подключаем адаптер
        viewPager.setAdapter(adapter);
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        tabLayout.setupWithViewPager(viewPager); //Запускаем вывод окна
    }


    DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener() {
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            onDateGet();
            if(year>=get_year && monthOfYear>=get_month && dayOfMonth>=get_day)
            {
                endYear = year;
                endMonth = monthOfYear;
                endDay = dayOfMonth;
                create_new_item.add(new CardViewEntreaty(from,target,endYear,endMonth,endDay));
                Bundle bundle=new Bundle();
                bundle.putParcelableArrayList("array",create_new_item);
                EntreatyTab fragobj=new EntreatyTab();
                fragobj.setArguments(bundle);
                fragobj.updateAdapter();
            }
            else {
                flag_data=true;
                dpd.hide();
                createDialog_Entreaty_Date();
            }
        }
    };
    private int get_year,get_month,get_day;
    public void onDateGet()
    {
        final Calendar c = Calendar.getInstance();
        get_year = c.get(Calendar.YEAR);
        get_month = c.get(Calendar.MONTH);
        get_day = c.get(Calendar.DAY_OF_MONTH);
    }

所以,我在initTab()中初始化我的片段(标签),并在最后一个公开UpdateAdapter中使用onDateSet

0 个答案:

没有答案