简体   繁体   中英

App crashes after deletion due to Intent.PutExtra sending firebase node to another activity for editing

I have created two methods for deletion of post and editing a post.i am able to successfully perform both jobs. all posts can be deleted. i have created an edit button which throws the user to the post writing edit-text activity (Cleaning) and simultaneously all the information of the task which is going to be edited is retrieved to the edit-text boxes.All the editing are also done successfully. the problem arises only after when the user tries to delete the edited task. the application directly crashes and it says something about the put-extra method which sends key of the post being edited to another class for filling the edit-text boxes. the post which are not edited and just added by the user are deleted without any problems. its just the posts which are edited crashes the application although the posts are deleted from the firebase database even after the crash...

I hope my problem makes sense Below is my code

public class MyPosts extends AppCompatActivity {

    private static final String TAG = "MyPosts";

    Toolbar toolbar;
    DatabaseReference WorkingData;
    DatabaseReference WorkingDataForDeletion;
    DatabaseReference tasks;

    private BottomNavigationView navigationView;
    RecyclerView recyclerView;
    ArrayList<WorkInformation> workList;

    private AppCompatButton deletePost;
    private AppCompatButton editPost;
    String currentUserID, postKey;
    private FirebaseAuth firebaseAuth;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_posts);

        toolbar = (Toolbar) findViewById(R.id.my_post_toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("My Posts");
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        navigationView = findViewById(R.id.bottomNavigationView);
        firebaseAuth = FirebaseAuth.getInstance();

        currentUserID = firebaseAuth.getCurrentUser().getUid();
        WorkingData = FirebaseDatabase.getInstance().getReference().child("UserIndividualTasks");
        WorkingData.keepSynced(true);

        recyclerView = findViewById(R.id.my_post_recycler_view);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setReverseLayout(true);
        linearLayoutManager.setStackFromEnd(true);
        recyclerView.setLayoutManager(linearLayoutManager);

        deletePost = findViewById(R.id.myPostDelete);
        editPost = findViewById(R.id.myPostEdit);

    }
      @Override
    protected void onStart() {
        super.onStart();


    }


    @Override
    protected void onResume() {
        super.onResume();



        Query query = WorkingData.child(FirebaseAuth.getInstance().getCurrentUser().getUid());
        FirebaseRecyclerOptions<WorkInformation> options = new FirebaseRecyclerOptions.Builder<WorkInformation>()
                .setQuery(query, WorkInformation.class)
                .build();


        final FirebaseRecyclerAdapter<WorkInformation, MyViewHolder> adapter = new FirebaseRecyclerAdapter<WorkInformation, MyViewHolder>(options) {
            @Override
            protected void onBindViewHolder(@NonNull final MyViewHolder holder, int position, @NonNull final WorkInformation model) {


                holder.title.setText(model.getWorkTitle());
                holder.date.setText(model.getWorkDueDate());
                Picasso.get().load(model.getImg()).into(holder.imageView);


                holder.deleteBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        postKey = getRef(holder.getAdapterPosition()).getKey();
                        deleteUserPost();

                    }
                });

                holder.editBtn.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        postKey = getRef(holder.getAdapterPosition()).getKey();
                        Intent goToCleaningForEditPost = new Intent(MyPosts.this, Cleaning.class);
                        Bundle bundle = new Bundle();
                        bundle.putString("PostKey", postKey);
                        goToCleaningForEditPost.putExtras(bundle);
                        startActivity(goToCleaningForEditPost);
                    }
                });

            }

            @NonNull
            @Override
            public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

                View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.my_posts_individual_row_layout, parent, false);
                MyViewHolder viewHolder = new MyViewHolder(view);
                return viewHolder;
            }
        };

        recyclerView.setAdapter(adapter);
        adapter.startListening();


    }


    public static class MyViewHolder extends RecyclerView.ViewHolder {

        public AppCompatTextView title;
        public AppCompatTextView date;
        public CircleImageView imageView;
        public AppCompatButton deleteBtn;
        public AppCompatButton editBtn;
        public ConstraintLayout constraintLayout;

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

            title = itemView.findViewById(R.id.my_posts_title);
            date = itemView.findViewById(R.id.myPostDate);
            imageView = itemView.findViewById(R.id.UserImage);
            deleteBtn = itemView.findViewById(R.id.myPostDelete);
            editBtn = itemView.findViewById(R.id.myPostEdit);
        }
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                startActivity(new Intent(MyPosts.this, Services.class));
                break;
        }


        return super.onOptionsItemSelected(item);
    }



      private void deleteUserPost() {
        WorkingDataForDeletion = FirebaseDatabase.getInstance().getReference().child("UserIndividualTasks")
                .child(currentUserID)
                .child(postKey);
        WorkingDataForDeletion.removeValue();


        tasks = FirebaseDatabase.getInstance().getReference().child("Tasks").child(postKey);
        tasks.removeValue();

    }

}

This is the classs where Iam now sending the key for editing the posts

    public class Cleaning extends AppCompatActivity implements DatePickerDialog.OnDateSetListener {
    private static final String TAG = "Cleaning";


    private BottomNavigationView navigationView;

    DatabaseReference UsersRef, WorkingData, userIndividualPostHistory;

    public static final int ERROR_DIALOG_REQUEST = 9001;
    ConstraintLayout constraintLayout;
    Toolbar toolbar;
    AppCompatEditText title;
    AppCompatEditText description;
    ElegantNumberButton budget;
    AppCompatTextView total;
    AppCompatEditText date;
    private String currentUserID, image, userNameForPost, saveDateForTask, saveTimeForTask, postRandomName, PostKey;
    AppCompatEditText places;
    private FirebaseAuth firebaseAuth;
    AppCompatButton continueservices;
    ElegantNumberButton WorkForce;
    private final static int MY_PERMISSION_FINE_LOCATION = 101;
    private final static int PLACE_PICKER_REQUEST = 1;
    double finalBudget, finalBudget2;
    private ProgressDialog loadingBar;
    private DatabaseReference WorkingDataForEdit, WorkingDataForPostEdit;

    Bundle bundle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_cleaning);
        toolbar = findViewById(R.id.CleaningToolBar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle("Cleaning service");

        navigationView = findViewById(R.id.bottomNavigationView);
        navigationView.setSelectedItemId(R.id.Services);
        firebaseAuth = FirebaseAuth.getInstance();

        currentUserID = firebaseAuth.getCurrentUser().getUid();
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        constraintLayout = findViewById(R.id.cleaningConstraintLayout);
        UsersRef = FirebaseDatabase.getInstance().getReference().child("Users");
        WorkingData = FirebaseDatabase.getInstance().getReference("Tasks");
        userIndividualPostHistory = FirebaseDatabase.getInstance().getReference("UserIndividualTasks");

        loadingBar = new ProgressDialog(this);

        title = findViewById(R.id.TaskTitle);
        description = findViewById(R.id.TaskDescription);
        budget = findViewById(R.id.TaskBudget);
        total = findViewById(R.id.tasktotal);


        date = findViewById(R.id.datepickerr);
        date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogFragment datepicker = new DatePickerFragment();
                datepicker.show(getSupportFragmentManager(), "Select Date");

            }
        });

        requestPermission();


        places = findViewById(R.id.locationPicker);
        places.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();
                try {
                    Log.d(TAG, "onClick: asking permission 3");
                    Intent intent = builder.build(Cleaning.this);
                    Log.d(TAG, "onClick: asking permission 4");
                    startActivityForResult(intent, PLACE_PICKER_REQUEST);
                } catch (GooglePlayServicesRepairableException e) {
                    e.printStackTrace();
                } catch (GooglePlayServicesNotAvailableException e) {
                    e.printStackTrace();
                }
            }
        });
    UsersRef.child(currentUserID).addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                if (dataSnapshot.exists()) {

                    if (dataSnapshot.hasChild("profileimage")) {
                        image = dataSnapshot.child("profileimage").getValue().toString();
                        userNameForPost = dataSnapshot.child("First Name").getValue().toString();

                    } else {
                        Toast.makeText(Cleaning.this, "Profile name do not exists...", Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        continueservices = findViewById(R.id.ContinueServicesButton);
        continueservices.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (PostKey != null) {
                    editIfAlreadyExist();
                    bundle = null;
                } else {
                    addWorkingTask();
                }

            }
        });


        WorkForce = findViewById(R.id.workforce);

        WorkForce.setOnClickListener(new ElegantNumberButton.OnClickListener() {
            @Override
            public void onClick(View view) {

                finalBudget = Double.parseDouble(WorkForce.getNumber());
                finalBudget2 = Double.parseDouble(budget.getNumber());
                finalBudget = finalBudget * finalBudget2;
                total.setText(String.valueOf(finalBudget) + " BD ");
            }
        });


        budget.setOnClickListener(new ElegantNumberButton.OnClickListener() {
            @Override
            public void onClick(View view) {
                finalBudget2 = Double.parseDouble(budget.getNumber());
                finalBudget = Double.parseDouble(WorkForce.getNumber());
                finalBudget2 = finalBudget2 * finalBudget;

                total.setText(String.valueOf(finalBudget2) + " BD ");

            }
        });

     navigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                int id = item.getItemId();
                switch (id) {
                    case R.id.Services:
                        break;
                    case R.id.Search:
                        startActivity(new Intent(Cleaning.this, Search.class));
                        break;
                    case R.id.Task:
                        break;
                    case R.id.Message:
                        break;
                    case R.id.Settings:
                        startActivity(new Intent(Cleaning.this, UserProfile.class));
                        break;
                }


                return false;
            }
        });




        bundle = getIntent().getExtras();
        if (bundle != null) {
            PostKey = bundle.get("PostKey").toString();
            WorkingDataForEdit = FirebaseDatabase.getInstance().getReference().child("UserIndividualTasks").child(currentUserID).child(PostKey);
            WorkingDataForPostEdit = FirebaseDatabase.getInstance().getReference().child("Tasks").child(PostKey);

        }


        if (PostKey != null) {
            WorkingDataForEdit.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

//Error occurred here line @239

  String mtitle = dataSnapshot.child("workTitle").getValue().toString();
                    String mdescription = 
   dataSnapshot.child("workDescription").getValue().toString();
                    String mdate = 
  dataSnapshot.child("workDueDate").getValue().toString();
                    String mlocation = 
     dataSnapshot.child("workLocation").getValue().toString();
                    String mMen = 
   dataSnapshot.child("workForce").getValue().toString();
                    String mbudget =  
    dataSnapshot.child("workBudget").getValue().toString();
                    String mtotal = 
   dataSnapshot.child("total").getValue().toString();

                    title.setText(mtitle);
                    description.setText(mdescription);
                    date.setText(mdate);
                    places.setText(mlocation);
                    WorkForce.setNumber(mMen);
                    budget.setNumber(mbudget);
                    total.setText(mtotal);


                }

                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {

                }
            });
        }


    }

    private void editIfAlreadyExist() {
        WorkingDataForEdit.child("workTitle").setValue(title.getText().toString());
        WorkingDataForEdit.child("workDescription").setValue(description.getText().toString());
        WorkingDataForEdit.child("workDueDate").setValue(date.getText().toString());
        WorkingDataForEdit.child("workLocation").setValue(places.getText().toString());
        WorkingDataForEdit.child("workForce").setValue(WorkForce.getNumber());
        WorkingDataForEdit.child("workBudget").setValue(budget.getNumber());
        WorkingDataForEdit.child("total").setValue(total.getText().toString());


        WorkingDataForPostEdit.child("workTitle").setValue(title.getText().toString());
        WorkingDataForPostEdit.child("workDescription").setValue(description.getText().toString());
        WorkingDataForPostEdit.child("workDueDate").setValue(date.getText().toString());
        WorkingDataForPostEdit.child("workLocation").setValue(places.getText().toString());
        WorkingDataForPostEdit.child("workForce").setValue(WorkForce.getNumber());
        WorkingDataForPostEdit.child("workBudget").setValue(budget.getNumber());
        WorkingDataForPostEdit.child("total").setValue(total.getText().toString());

        startActivity(new Intent(Cleaning.this, Search.class));


    }

     private void requestPermission() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, MY_PERMISSION_FINE_LOCATION);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        switch (requestCode) {
            case MY_PERMISSION_FINE_LOCATION:
                if (grantResults[0] != PackageManager.PERMISSION_GRANTED) {
                    Toast.makeText(getApplicationContext(), "This app requires location permissions to be granted", Toast.LENGTH_LONG).show();
                    finish();
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult: asking permission 2");
        if (requestCode == PLACE_PICKER_REQUEST) {
            if (resultCode == RESULT_OK) {
                Place place = PlacePicker.getPlace(Cleaning.this, data);
                places.setText(place.getName() + " " + place.getAddress());

            }
        }
    }

    private void addWorkingTask() {

        loadingBar.setMessage("Posting task.Please Wait....");
        loadingBar.show();
        loadingBar.setCanceledOnTouchOutside(true);

     Calendar callForTime = Calendar.getInstance();
        SimpleDateFormat currentTime = new SimpleDateFormat("HH:mm:ss");
        saveTimeForTask = currentTime.format(callForTime.getTime());

     Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy, HH:mm");
        String currentDateandTime = sdf.format(d);


        String taskTitle = title.getText().toString();
        String taskDescription = description.getText().toString();
        String date = this.date.getText().toString();
        String location = places.getText().toString();
        String workMen = WorkForce.getNumber();
        String budget = this.budget.getNumber();
        String total = this.total.getText().toString();

        if (!TextUtils.isEmpty(taskTitle)) {
            if (!TextUtils.isEmpty(taskDescription)) {
                if (!TextUtils.isEmpty(date)) {
                    if (!TextUtils.isEmpty(location)) {
                        String id = WorkingData.push().getKey();
                        WorkInformation workInformation = new WorkInformation(id, taskTitle, taskDescription
                                , date, location, workMen
                                , budget
                                , total, image
                                , currentUserID
                                , userNameForPost, currentDateandTime, saveTimeForTask);

                        WorkingData.child(id).setValue(workInformation);

                        userIndividualPostHistory.child(currentUserID).child(id).setValue(workInformation);

                        Toast.makeText(this, "Work Information saved", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                        startActivity(new Intent(Cleaning.this, Search.class));


                    } else {
                        Toast.makeText(this, "Something is missing", Toast.LENGTH_SHORT).show();
                        loadingBar.dismiss();
                    }
                }

            }
        }

    }


    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(calendar.getTime());
        date.setText(currentDateString);

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case android.R.id.home:
                finish();
                break;
        }


        return super.onOptionsItemSelected(item);
    }
}

Error :

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.saqib.smarttaskk, PID: 13977
              java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.Object.toString()' on a null object reference
                  at com.example.saqib.smarttaskk.Cleaning$8.onDataChange(Cleaning.java:239)
                  at com.google.firebase.database.obfuscated.zzap.zza(com.google.firebase:firebase-database@@16.0.2:75)
                  at com.google.firebase.database.obfuscated.zzca.zza(com.google.firebase:firebase-database@@16.0.2:63)
                  at com.google.firebase.database.obfuscated.zzcd$1.run(com.google.firebase:firebase-database@@16.0.2:55)
                  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:6938)
                  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)

Application terminated.

The error occured because there is no such child workTitle or if its present there is no data under that node in your firebase database.I suggest you check if value should not be null.

Object title = dataSnapshot.child("workTitle").getValue();
if(title != null)
{
 String mtitle = title.toString();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM