片段中使用适配器时出现空指针异常

时间:2017-10-24 07:10:57

标签: android android-fragments nullpointerexception

我正在使用包含多个片段的Activity。 每当我从其他Activity或Fragment更新List时,我在onStart方法中就会出现NullPointerException。

  

adapter = new MedicineAdapter(getActivity(),medicineList);

这是我的片段

public class frag_stock extends Fragment {

DatabaseReference databaseRoot;
DatabaseReference databaseMedicines;

EditText etSearch;

TextView tvAdd;

private ProgressBar spinner;

ListView listViewMedicine;

List<Medicine> medicineList;

MedicineAdapter adapter;

TextView emptyTextView;

int medicineCount =0;

private FirebaseAuth mAuth;

public HashMap<String , Integer> mapForDate = new HashMap<String , Integer>();

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_stock, container, false);
}

@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    mAuth = FirebaseAuth.getInstance();

    spinner = (ProgressBar)view.findViewById(R.id.progressBar1);

    emptyTextView = (TextView)view.findViewById(R.id.empty_view);

    medicineList = new ArrayList<>();

    databaseRoot = FirebaseDatabase.getInstance().getReference();
    databaseMedicines = databaseRoot.child("Medicines");

    listViewMedicine = (ListView)view.findViewById(R.id.list);
    listViewMedicine.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
            Medicine currentMedicine = adapter.getItem(position);

            assert currentMedicine != null;
            String name = currentMedicine.getMedicineName();
            int quantity = currentMedicine.getMedicineQuantity();
            String id = currentMedicine.getId();
            String type = currentMedicine.getType();

            Intent intent = new Intent(getActivity(),UpdateActivity.class);
            intent.putExtra("name",name);
            intent.putExtra("mapForDate",mapForDate);
            intent.putExtra("quantity",quantity);
            intent.putExtra("id",id);
            intent.putExtra("type",type);

            startActivity(intent);
        }
    });
    /*
    etSearch = (EditText)view.findViewById(R.id.etSearch);
    etSearch.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            List<Medicine> newList = new ArrayList<Medicine>();
            String filter = charSequence.toString();
            for (int i=0;i<medicineList.size();i++)
            {
                if (medicineList.get(i).getMedicineName().toLowerCase().contains(filter.toLowerCase()))
                {
                    newList.add(medicineList.get(i));
                }
            }

            if(newList.isEmpty()){
                emptyTextView.setText("No Medicines found!");
            }
            adapter = new MedicineAdapter(getActivity(),newList);

            listViewMedicine.setAdapter(adapter);

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
    */
}

@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

@Override
public void onStart() {
    super.onStart();

    if (getActivity() != null) {

        spinner.setVisibility(View.VISIBLE);
        databaseMedicines.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (!medicineList.isEmpty()) {
                    adapter = new MedicineAdapter(getActivity(), medicineList);
                    listViewMedicine.setAdapter(adapter);
                }
                medicineList.clear();


                for (DataSnapshot medicineSnapshot : dataSnapshot.getChildren()) {
                    Medicine medicine = medicineSnapshot.getValue(Medicine.class);
                    medicineList.add(medicine);
                }
                //Toast.makeText(MainActivity.this, medicineList.size() + "", Toast.LENGTH_SHORT).show();

                adapter = new MedicineAdapter(getActivity(), medicineList);

                listViewMedicine.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });
        spinner.setVisibility(View.GONE);
    }
}

logcat的

 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
                                                                                              at android.view.LayoutInflater.from(LayoutInflater.java:234)
                                                                                              at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:178)
                                                                                              at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:163)
                                                                                              at com.example.android.hospitalmanagementsystem.MedicineAdapter.<init>(MedicineAdapter.java:0)
                                                                                              at com.example.android.hospitalmanagementsystem.frag_stock$2.onDataChange(frag_stock.java:166)
                                                                                              at com.google.android.gms.internal.zzbmz.zza(Unknown Source)
                                                                                              at com.google.android.gms.internal.zzbnz.zzYj(Unknown Source)
                                                                                              at com.google.android.gms.internal.zzboc$1.run(Unknown Source)
                                                                                              at android.os.Handler.handleCallback(Handler.java:739)
                                                                                              at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                              at android.os.Looper.loop(Looper.java:148)
                                                                                              at android.app.ActivityThread.main(ActivityThread.java:7331)
                                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
                                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

适配器类

public class MedicineAdapter extends ArrayAdapter<Medicine> {

private Activity context;
private Filter medicineFilter;
private List<Medicine> medicineList;

public MedicineAdapter(Activity context, List<Medicine> medicines) {
    super(context,0,medicines);
    this.context = context;
    this.medicineList = medicines;
}

@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {

    LayoutInflater inflater = context.getLayoutInflater();

    View listItemView = convertView;

    if (listItemView == null) {
        listItemView = inflater.inflate(R.layout.list_item,null,true);
    }

    TextView medicineNameTV = (TextView)listItemView.findViewById(R.id.medicineName);
    TextView medicineQuantityTV = (TextView)listItemView.findViewById(R.id.medicineQuantity);
    TextView medicineType = (TextView)listItemView.findViewById(R.id.medicineType);

    Medicine currentMedicine = getItem(position);

    GradientDrawable quantityCircle = (GradientDrawable) medicineQuantityTV.getBackground();


    assert currentMedicine != null;
    int quantityColor = getQuantityColor(currentMedicine.getMedicineQuantity());

    quantityCircle.setColor(quantityColor);

    assert currentMedicine != null;
    medicineNameTV.setText(currentMedicine.getMedicineName());
    medicineQuantityTV.setText(String.valueOf(currentMedicine.getMedicineQuantity()));
    medicineType.setText(currentMedicine.getType());

    return listItemView;
}

public int getQuantityColor(int quantity){
    int quanColor = 0;
    if(quantity <= 30){
        quanColor = ContextCompat.getColor(getContext(), R.color.quantity1);
    }
    else if(quantity > 30 && quantity < 100){
        quanColor = ContextCompat.getColor(getContext(), R.color.quantity2);
    }
    else if(quantity >= 100){
        quanColor = ContextCompat.getColor(getContext(), R.color.quantity3);
    }
    else{
        quanColor = ContextCompat.getColor(getContext(), R.color.quantity4);
    }

    return quanColor;
}

}

3 个答案:

答案 0 :(得分:4)

在frag_stock类中创建一个变量并从onAttach()方法获取上下文并传递context

 Context c =null;

@Override
public void onAttach(Context context) {
    super.onAttach(context);
   c= context;
}

将此c变量传递给适配器。

并在适配器中进行更改。

public MedicineAdapter(Context context, List<Medicine> medicines) {
super(context,0,medicines);
this.context = context;
this.medicineList = medicines;

}

  

Donot使用 getActivity()使用 onAttach()中的context

希望这会有所帮助。

答案 1 :(得分:-1)

可能是因为getActivity()MedicineAdapter构造函数的第一个参数)。尝试从片段的上下文或父片段/活动中获取活动。

答案 2 :(得分:-1)

我认为您可以通过覆盖onAttach的{​​{1}}方法来解决该问题:

Fragment

更改列表时使用public static class YourClass extends Fragment{ ... @Override public void onAttach(Activity activity) { super.onAttach(activity); adapter = new MedicineAdapter(getActivity(), medicineList); listViewMedicine.setAdapter(adapter); } }