После удаления заметки пользователь не получает уведомление - PullRequest
0 голосов
/ 08 января 2019

Я хочу добиться этого, если пользователь удаляет замечание, он получает уведомление об удаленном примечании. Но пока в моем приложении это не работает. Ничего не происходит, если пользователь удаляет замечание.

Ниже я разместил код класса, в котором я хочу реализовать уведомление. После нажатия на кнопку «Удалить», пользователь должен получить уведомление об изменении в базе данных.

Я пытался:

  1. Используйте YouTube, чтобы сделать уведомление, но они делают это без канала
  2. Изменить положение кода об уведомлении
  3. Создать функцию с кодом уведомления

... ничего из этого не сработало ...

public class EditDataActivity extends AppCompatActivity {

    private static final String TAG = "EditDataActivity";

    private String CHANNEL_ID = "ID";
    private int notifId = 1000;

    private Button btnSave,btnDelete;
    private EditText editable_item;
    DatabaseHelper mDatabaseHelper;
    private String selectedName;
    private int selectedID;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.edit_data_layout);
        btnSave = (Button) findViewById(R.id.btnSave);
        btnDelete = (Button) findViewById(R.id.btnDelete);
        editable_item = (EditText) findViewById(R.id.editable_item);
        mDatabaseHelper = new DatabaseHelper(this);


        //get the intent extra from the ListDataActivity
        Intent receivedIntent = getIntent();

        //now get the itemID we passed as an extra
        selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value

        //now get the name we passed as an extra
        selectedName = receivedIntent.getStringExtra("name");

        //set the text to show the current selected name
        editable_item.setText(selectedName);

        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String item = editable_item.getText().toString();
                if(!item.equals("")){
                    mDatabaseHelper.updateName(item,selectedID,selectedName);
                }else{
                    toastMessage("You must enter a name");
                }
            }
        });

        btnDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mDatabaseHelper.deleteName(selectedID,selectedName);
                editable_item.setText("");

                Intent intent = new Intent(EditDataActivity.this, ListDataActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                PendingIntent pendingIntent = PendingIntent.getActivity(EditDataActivity.this, 0, intent, 0);

                createNotificationChannel();

                final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(EditDataActivity.this, CHANNEL_ID)
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setContentTitle("NOTIFTITLE")
                        .setContentText("TEXT")
                        .setContentIntent(pendingIntent)
                        .setPriority(NotificationCompat.PRIORITY_DEFAULT);


                toastMessage("removed from database");
            }
        });

    }

    /**
     * customizable toast
     * @param message
     */
    private void toastMessage(String message){
        Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
    }

    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            CharSequence name = "Name of the channel";
            String description = "Description of the channel";
            int importance = NotificationManager.IMPORTANCE_DEFAULT;
            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
            channel.setDescription(description);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }
    }

}

1 Ответ

0 голосов
/ 08 января 2019

Вы забыли какой-то код. Добавьте эту строку в ваш код

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(id, b.build());

Полный код

 btnDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mDatabaseHelper.deleteName(selectedID,selectedName);
            editable_item.setText("");

            Intent intent = new Intent(EditDataActivity.this, ListDataActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            PendingIntent pendingIntent = PendingIntent.getActivity(EditDataActivity.this, 0, intent, 0);

            createNotificationChannel();

            final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(EditDataActivity.this, CHANNEL_ID)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("NOTIFTITLE")
                    .setContentText("TEXT")
                    .setContentIntent(pendingIntent)
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT);
            //ADD THIS LINES 
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(id, mBuilder.build());
            toastMessage("removed from database");
        }
    });

Вы можете использовать случайное целое число для идентификатора или один идентификатор, если вы хотите обновить уведомление или отменить его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...