我在android studio上有一个Java代码,通过取消或提交来关闭对话框时,我一直收到以下错误。
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:233)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
at com.shaden.wesal.NotificationListAdapter.<init>(NotificationListAdapter.java:27)
at com.shaden.wesal.NotificationsFragment$1.onDataChange(NotificationsFragment.java:134)
at com.google.android.gms.internal.firebase_database.zzfc.zza(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzgx.zzdr(Unknown Source)
at com.google.android.gms.internal.firebase_database.zzhd.run(Unknown Source)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6816)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1565)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1453)
这是我的对话框代码,用于在通知列表上发布通知,通知已成功发布,当我再次打开应用程序时,我在列表中找到了它。但是当关闭添加对话框时,应用程序中断了。
public class NotificationDialog extends AppCompatDialogFragment {
private EditText notification;
private EditText notificationSubject;
private TextView whatsnew;
private NotificationDialogListener listener;
Typeface typeface;
@Override
public void onAttach(Context context) {
super.onAttach(context);
try{
listener = (NotificationDialogListener) context;
}catch(ClassCastException e){
throw new ClassCastException(context.toString() + "must implement NotificationDialogListener");
}
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.layout.layout_dialog, null);
typeface = Typeface.createFromAsset(getActivity().getAssets(),"fonts/GE_SS_Two_Light.otf");
builder.setView(view)
.setTitle("إضافة إعلان")
.setNegativeButton("إلغاء", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
})
.setPositiveButton("نشر", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String notificationText = notification.getText().toString();
String notificationSubjectText = notificationSubject.getText().toString();
if(notificationSubjectText.isEmpty()){
notification.setText("بدون عنوان");
}
if(notificationText.isEmpty()){
Toast.makeText(getContext(),"لم يتم نشر الإعلان لأن حقل محتوى الإعلان مطلوب",Toast.LENGTH_LONG).show();
}
else {
listener.applyTexts(notificationSubjectText, notificationText);
}
}
});
notification = view.findViewById(R.id.notEditText);
notificationSubject = view.findViewById(R.id.notSubEditText);
whatsnew = view.findViewById(R.id.whatsnew);
whatsnew.setTypeface(typeface);
// notificationSubject.setTypeface(typeface);
// notification.setTypeface(typeface);
return builder.create();
}
public interface NotificationDialogListener {
void applyTexts(String subject, String notification);
}
}
这是适配器代码
public class NotificationListAdapter extends ArrayAdapter<notifications>{
Context mCtx;
int resource;
List<notifications> notificationsList;
int index;
public NotificationListAdapter (Context mCtx, int resource, List<notifications> notificationsList){
super(mCtx, resource, notificationsList);
this.mCtx = mCtx;
this.resource = resource;
this.notificationsList = notificationsList;
}
@NonNull
@Override
public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(mCtx);
View view = inflater.inflate(resource, null);
TextView notSubject = view.findViewById(R.id.notSubject);
TextView notBody = view.findViewById(R.id.notBody);
TextView notDate = view.findViewById(R.id.notDate);
notifications not = notificationsList.get(position);
notSubject.setText(not.getSubject());
notBody.setText(not.getBody());
notDate.setText(not.getTime());
return view;
}
}
此外,这是启动对话框的通知片段
public class NotificationsFragment extends Fragment implements NotificationDialog.NotificationDialogListener {
SwipeMenuListView listView;
List<notifications> notsList;
NotificationListAdapter adapter;
FirebaseDatabase database;
DatabaseReference ref;
notifications not;
TextView noNots;
Typeface typeface;
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
@Override
public void applyTexts(String subject, String notification) {
}
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
ImageView addBTN;
private OnFragmentInteractionListener mListener;
public NotificationsFragment() {
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* @param param1 Parameter 1.
* @param param2 Parameter 2.
* @return A new instance of fragment NotificationsFragment.
*/
// TODO: Rename and change types and number of parameters
public static NotificationsFragment newInstance(String param1, String param2) {
NotificationsFragment fragment = new NotificationsFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_notifications, container, false);
database = FirebaseDatabase.getInstance();
ref= database.getReference().child("notifications");
getActivity().setTitle("إعلانات المدرسة");
typeface = Typeface.createFromAsset(getActivity().getAssets(),"fonts/GE_SS_Two_Light.otf");
not = new notifications();
listView = (SwipeMenuListView) v.findViewById(R.id.notsList);
notsList = new ArrayList<>();
noNots = (TextView) v.findViewById(R.id.noNots);
noNots.setTypeface(typeface);
ref.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
notsList.clear();
for (DataSnapshot ds:dataSnapshot.getChildren())
{
not = ds.getValue(notifications.class);
notsList.add(0, not);
}
adapter = new NotificationListAdapter(getContext(), R.layout.not_info,notsList);
listView.setAdapter(adapter);
if(notsList.isEmpty()){
noNots.setText("لا يوجد تنبيهات حاليّا");
}
SwipeMenuCreator creator = new SwipeMenuCreator() {
@Override
public void create(SwipeMenu menu) {
// create "delete" item
SwipeMenuItem deleteItem = new SwipeMenuItem(
getContext());
// set item background
deleteItem.setBackground(new ColorDrawable(Color.rgb(0xFF,
0x00, 0x00)));
// set item width
deleteItem.setWidth(230);
// set a icon
deleteItem.setIcon(R.drawable.rubbish);
// add to menu
menu.addMenuItem(deleteItem);
}
};
listView.setMenuCreator(creator);
listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setTitle("هل أنت متأكد من حذف التنبيه؟");
builder.setPositiveButton("نعم", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("notifications").child(notsList.get(position).getNotId());
ref.removeValue();
//notifyDataSetChanged();
Toast.makeText(getContext(),"تم حذف التنبيه بنجاح",Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("لا", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
// false : close the menu; true : not close the menu
return false;
}
});
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
addBTN = (ImageView) v.findViewById(R.id.addNotificationBTN);
addBTN.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openDialog();
//FragmentManager fragmentManager = getFragmentManager();
//fragmentManager.beginTransaction().replace(R.id.main_frame, addNotFragment ).commit();
}
});
// Inflate the layout for this fragment
return v;
}
public void openDialog(){
NotificationDialog ND = new NotificationDialog();
ND.show(getFragmentManager(), "ND");
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
非常感谢您的帮助,谢谢。 :3