@Chesterfield25

Как получить id всех записей из sqlite?

У меня есть бд из которой нужно получить id каждой записи и вставить этот id в уведомление.
Вот исхожный код уведомлений

public class AlertReceiver  extends BroadcastReceiver {

    private static final String TAG = "AlertReceiver";

    @Override
    public void onReceive(Context mContext, Intent intent) {

        String Title = intent.getStringExtra(Constants.title);
        long id = intent.getLongExtra(Constants.title, -1);
        String content = intent.getStringExtra(Constants.title);
        String channelId = mContext.getResources().getString(R.string.channel_id);
        CharSequence name = mContext.getResources().getString(R.string.channel_name);
        String description = mContext.getResources().getString(R.string.channel_description);
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext.getApplicationContext(), channelId);
        Intent ii = new Intent(mContext.getApplicationContext(), MainActivity.class);
        ii.putExtra(Constants.title, id);
        Log.e(TAG, "onReceive: "+id );
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, ii, 0);

        NotificationCompat.BigTextStyle bigText = new NotificationCompat.BigTextStyle();
        bigText.bigText(content);
        bigText.setBigContentTitle(Title);
        bigText.setSummaryText(content);

        mBuilder.setContentIntent(pendingIntent);
        mBuilder.setSmallIcon(R.drawable.ic_fav);
        mBuilder.setContentTitle(Title);

        mBuilder.setContentText(content);
        mBuilder.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/alarm_gentle"));
        Log.e("jmbjgjg", "onReceive: " +Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                + "://" + mContext.getPackageName() + "/raw/alarm_gentle").toString() );
        mBuilder.setColor(Color.RED);
        mBuilder.setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 });
        mBuilder.setPriority(Notification.PRIORITY_MAX);
        mBuilder.setStyle(bigText);
        mBuilder.setAutoCancel(true);
        NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        NotificationChannel mChannel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            mChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_HIGH);
            mChannel.setLightColor(Color.RED);
            mChannel.enableLights(true);
            mChannel.setShowBadge(true);
            mChannel.setDescription(description);
            AudioAttributes audioAttributes = new AudioAttributes.Builder()
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .build();
            mChannel.setSound(Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE
                    + "://" + mContext.getPackageName() + "/raw/alarm_gentle"), audioAttributes);

            if (mNotificationManager != null) {
                mNotificationManager.createNotificationChannel( mChannel );
            }
        }
        assert mNotificationManager != null;
        mNotificationManager.notify(1, mBuilder.build());
    }
}

В нем я получаю уведомления только одной записи, а нужно всех.

Пробовал таким образом, но нечего не работает
assert mNotificationManager != null;

        Bundle mBundle = new Bundle();
        try {
            id = mBundle.getLong(Constants.id);
            if (id>0) {
                long finalId = id;
                databaseWriteExecutor.execute(() -> {
                    NoteDao dao = INSTANCE.noteDao();
                    dao.getNoteById(finalId);
                    mNotificationManager.notify((int) finalId, mBuilder.build());
                });
            }

        }catch (Exception e){
            Log.e(TAG, "onCreate: "+e);
        }


Вот как выгладит NoteDao interface

@Dao
public interface NoteDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    long insert(NoteModel noteModel);

    @Query("DELETE FROM note_tables")
    void deleteAll();

    @Query ("DELETE FROM note_tables WHERE id = :id")
    void deleteById(long id);

    @Query("SELECT * from note_tables ORDER BY id DESC")
    LiveData<List<NoteModel>> getAllNotes();

    @Query("SELECT * from note_tables WHERE id = :id")
    NoteModel getNoteById(long id);

    @Query("UPDATE note_tables SET title=:mTtitle, note=:mNote, day=:day, month=:month, year=:year, hour=:hour, minute=:minute, lastEdited=:mLastEdited, isReminderSet=:mIsReminderSet, ampm=:mAM_PM WHERE id = :id")
    void update(
                String mTtitle,
                String mNote,
                int day,
                int month,
                int year,
                int hour,
                int minute,
                String mLastEdited,
                boolean mIsReminderSet,
                String mAM_PM,
                long id);
}


NoteAdapter

public class NoteAdapter extends RecyclerView.Adapter<NoteAdapter.ViewHolder> {

    private LayoutInflater inflater;
    private List<NoteModel> list;
    private Context context;
    private NoteClickListener noteClickListener;

    public NoteAdapter(Context context, NoteClickListener noteClickListener) {
        this.context = context;
        inflater = LayoutInflater.from(context);
        this.noteClickListener= noteClickListener;
    }

    @NonNull
    @Override
    public NoteAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        return new ViewHolder(NoteLayoutBinding.inflate(inflater,
                parent, false));
    }

    @Override
    public void onBindViewHolder(@NonNull NoteAdapter.ViewHolder holder, int position) {
        String upperString = list.get(position).getTitle().substring(0, 1).toUpperCase()
                + list.get(position).getTitle().substring(1).toLowerCase();
        holder.noteLayoutBinding.titleTv.setText(upperString);
        holder.noteLayoutBinding.lastUpdated.setText(list.get(position).getLastEdited());
        if (list.get(position).isReminderSet()){
            holder.noteLayoutBinding.layoutReminder.setVisibility(View.VISIBLE);
            holder.noteLayoutBinding.reminder.setText(list.get(position).getDay()+" "
                    +getMonth(list.get(position).getMonth()+"")
                    + " "+list.get(position).getYear()
                    +" "+list.get(position).getHour()+":"+list.get(position).getMinute()+""+list.get(position).getAM_PM());
        }else {
            holder.noteLayoutBinding.layoutReminder.setVisibility(View.GONE);
        }
        holder.noteLayoutBinding.noteMcv.setOnClickListener(view -> noteClickListener.getNoteId(list.get(position).getId()));
    }

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

    public static class ViewHolder extends RecyclerView.ViewHolder {

        private NoteLayoutBinding noteLayoutBinding;

        public ViewHolder(@NonNull NoteLayoutBinding noteLayoutBinding) {
            super(noteLayoutBinding.getRoot());
            this.noteLayoutBinding = noteLayoutBinding;
        }
    }

    public void setNote(List<NoteModel> noteModels) {
        list = noteModels;
        notifyDataSetChanged();
    }
}
  • Вопрос задан
  • 185 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы