RecyclerView:列表和适配器为空

时间:2019-02-15 15:41:56

标签: java android android-fragments android-recyclerview

我想从片段2中的editTexts中输入内容,为片段1中的recyclerview添加项目,然后单击fab以添加包含我在片段2中输入的详细信息的项目。问题是当我调试mExampleAdapter /适配器为null以及mExampleList,我不知道为什么

这是片段1 JAVA代码

package com.example.admin.test2;


import android.os.Bundle;
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.Toast;

import java.util.ArrayList;


/**
 * A simple {@link Fragment} subclass.
 */
public class MainScreen extends Fragment {

    private ArrayList <ExampleItem> mExampleList;

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

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

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_main_screen, container, false);

        DataHandlers dataHandlers = new DataHandlers();

        try {
            String deTails = dataHandlers.getDetails();
            int aMount = dataHandlers.getAmount();
            Toast.makeText(getActivity().getApplicationContext(), deTails + "" + aMount, Toast.LENGTH_LONG).show();
            //TAS DITO KA NA MAG SET TEXT SA MGA TEXTVIEW NG AMOUNT AT DETAILS

        } catch (Exception ex) {
            Toast.makeText(getActivity().getApplicationContext(), ex.getMessage().toString(), Toast.LENGTH_LONG).show();
        }

        mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);

        mExampleList = new ArrayList <>();
        //   mExampleList.add(new ExampleItem(R.drawable.ic_library_add_black_24dp, "", "", "ADD EXPENSES"));


        mRecyclerView = view.findViewById(R.id.recyclerView);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getContext());
        mAdapter = new ExampleAdapter(mExampleList);

        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setAdapter(mAdapter);

        return view;
    }

    public void insertItem() {
        // String amount = String.valueOf(amountt.getText());
        //  String details = String.valueOf((detailss.getText()));
        // String date = String.valueOf((datee.getText()));
/*
        Bundle bundle = getArguments();
        String deTails = bundle.getString("Details");
        String aMount = bundle.getString("Amount");
*/
        //int position = bundle.getInt("Position");
        DataHandlers dataHandlers = new DataHandlers();

        String deTails = dataHandlers.getDetails();
        int aMount = dataHandlers.getAmount();

        mExampleList.add(0, new ExampleItem(R.drawable.food, "Food & Drink", "" + deTails, "₱ " + aMount));
        mAdapter.notifyDataSetChanged();


    }
}

这是来自2个JAVA代码的片段

package com.example.admin.test2;


import android.app.DatePickerDialog;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
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.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class Expense extends Fragment {


    public Expense() {
        // Required empty public constructor
    }
    //SPINNER
    Spinner sp1;
    CustomAdapter adapter;
    String[] names = {"Food & Drink", "Shopping", "Transportation", "Home", "Bills & Fees", "Entertainment", "Healthcare", "Education", "Beauty", "Others"};
    int[] images = {R.drawable.food, R.drawable.shopping, R.drawable.transportation, R.drawable.home, R.drawable.bills, R.drawable.entertainment, R.drawable.medical, R.drawable.education, R.drawable.beauty, R.drawable.others};

    //DATE PICKER
    private EditText mDisplayDate;
    private DatePickerDialog.OnDateSetListener mDateSetListener;

    //FOR THE ADD ITEM
    FloatingActionButton fab;
    private ArrayList<ExampleItem> mExampleList;
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    EditText amount;
    EditText detail;

    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate (R.layout.fragment_expense, container, false);


        //spinner
        sp1 = (Spinner)view.findViewById(R.id.customSpinner);

        adapter = new CustomAdapter(getActivity(), names, images);
        sp1.setAdapter(adapter);

        //fab onClick - sending values to the recycler view
        fab = (FloatingActionButton) view.findViewById(R.id.fabs);
        amount = (EditText) view.findViewById(R.id.textAmountt);
        detail = (EditText) view.findViewById(R.id.textDetailss);

        final DataHandlers dataHandlers = new DataHandlers();

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
        //        String amountValue = amount.getText().toString();
        //        String detailValue = detail.getText().toString();

        //        mExampleList.add(0, new ExampleItem(R.drawable.entertainment, "Entertainment", detailValue, "₱ " + amountValue));
        //        mAdapter.notifyDataSetChanged();

                dataHandlers.setAmount(Integer.parseInt(amount.getText().toString()));
                dataHandlers.setDetails(detail.getText().toString());
                Toast.makeText(getActivity().getApplicationContext(), dataHandlers.getDetails() + dataHandlers.getAmount(), Toast.LENGTH_LONG).show();

                android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                MainScreen ms = new MainScreen();
                ms.insertItem();
                fragmentTransaction.replace(R.id.replaceLayout, ms);
                fragmentTransaction.commit();

            }
        });

        int pos = sp1.getSelectedItemPosition();

        //date picker
        mDisplayDate = (EditText) view.findViewById(R.id.datePick);

        mDisplayDate.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Calendar cal = Calendar.getInstance();
                int year = cal.get(Calendar.YEAR);
                int month = cal.get(Calendar.MONTH);
                int day = cal.get(Calendar.DAY_OF_MONTH);

                DatePickerDialog dialog = new DatePickerDialog(getActivity(),
                        android.R.style.Theme_Holo_Light_Dialog_MinWidth,
                        mDateSetListener,
                        year, month, day);
                dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
                dialog.show();

            }
        });

        mDateSetListener = new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int day) {
                //Calendar calendar = Calendar.getInstance();
                //String currentDate = DateFormat.getDateInstance().format(calendar.getTime());

                month = month + 1;
                String date = month + "-" + day + "-" + year;
                mDisplayDate.setText(date);


            }
        };

        return view;
    }

}

这是适配器的Java代码

package com.example.admin.test2;

import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;

public class ExampleAdapter extends RecyclerView.Adapter<ExampleAdapter.ExampleViewHolder> {

    private ArrayList<ExampleItem> mExampleList;


    public static class ExampleViewHolder extends RecyclerView.ViewHolder
    {

        public ImageView mImageView;
        public TextView mLabel;
        public TextView mDetails;
        public TextView mAmount;

        public ExampleViewHolder(View itemView) {
            super(itemView);

            mImageView = itemView.findViewById(R.id.imageIcon);
            mLabel = itemView.findViewById(R.id.textLabel);
            mDetails = itemView.findViewById(R.id.textDetails);
            mAmount = itemView.findViewById(R.id.textAmount);
        }
    }

    public ExampleAdapter(ArrayList<ExampleItem> exampleList)
    {
        mExampleList = exampleList;
    }

    @NonNull
    @Override
    public ExampleViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.customlist, parent, false);
        ExampleViewHolder evh = new ExampleViewHolder(view);
        return evh;
    }

    @Override
    public void onBindViewHolder(@NonNull ExampleViewHolder holder, int position) {
        ExampleItem currentItem = mExampleList.get(position);

        holder.mImageView.setImageResource(currentItem.getmImageResource());
        holder.mLabel.setText(currentItem.getMlabel());
        holder.mDetails.setText(currentItem.getMdetails());
        holder.mAmount.setText(currentItem.getMamount());
    }

    @Override
    public int getItemCount() {
        if (mExampleList == null)
            return 0;
        else
            return  mExampleList.size();
    }
}

这是项目的获取器和设置器

package com.example.admin.test2;

public class ExampleItem {

    private int mImageResource;
    private String mlabel;
    private String mdetails;
    private String mamount;

    public ExampleItem(int imageResource, String label, String details, String amount)
    {
        mImageResource = imageResource;
        mlabel = label;
        mdetails = details;
        mamount = amount;
    }

    public int getmImageResource()
    {
        return mImageResource;
    }

    public String getMlabel() {
        return mlabel;
    }

    public String getMdetails() {
        return mdetails;
    }

    public String getMamount() {
        return mamount;
    }


}

这就是错误

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.admin.test2, PID: 30713
                  java.lang.NullPointerException: Attempt to invoke virtual method 'void java.util.ArrayList.add(int, java.lang.Object)' on a null object reference
                      at com.example.admin.test2.MainScreen.insertItem(MainScreen.java:82)
                      at com.example.admin.test2.Expense$1.onClick(Expense.java:101)
                      at android.view.View.performClick(View.java:6897)
                      at android.view.View$PerformClick.run(View.java:26101)
                      at android.os.Handler.handleCallback(Handler.java:789)
                      at android.os.Handler.dispatchMessage(Handler.java:98)
                      at android.os.Looper.loop(Looper.java:164)
                      at android.app.ActivityThread.main(ActivityThread.java:6944)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:327)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1374)

根据调试mExampleList和mAdapter为null。

mExampleList.add(0, new ExampleItem(R.drawable.food, "Food & Drink", "" + deTails, "₱ " + aMount));
        mAdapter.notifyDataSetChanged();

0 个答案:

没有答案