如何在Android中使用对象模型数据库获取日期和月份列 [英] how to get date and month column using object model database in android

查看:165
本文介绍了如何在Android中使用对象模型数据库获取日期和月份列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在数据库sqlite中添加了静态日期,我已经使用对象模型和日期和月份设置通知来获取这个日期和月份列,假设今天是4个人的生日,我已经通知这个4个人的名字,但是我已经传递对象获取日期和月份列,以获取错误



我的数据库列

  DataType 
TEXT整数整数
名称dd mm
Indira Gandhi1911
Bal Gangadhar Tilak237
Mangal Pandey197

Notification.java p>

  People people = new People(); 
日历calendar = Calendar.getInstance();
try {
String str_date = people.getDate();
Log.d(getClass()。getName(),strDate+ str_date);
String str_month = people.getMonth();
DateFormat格式化程序
日期日期,月份;
formatter = new SimpleDateFormat(dd-MMM);
date =(Date)formatter.parse(str_date);
Log.d(getClass()。getName(),str_date+ date);
month =(Date)formatter.parse(str_month);
Log.d(getClass()。getName(),str_month+ month);
calendar.setTime(date);
calendar.setTime(month);
calendar.set(Calendar.HOUR_OF_DAY,10);
calendar.set(Calendar.MINUTE,59);
calendar.set(Calendar.SECOND,0);
calendar.setTime(month);
} catch(ParseException e){
e.printStackTrace();
}


Intent intent1 = new Intent(Notification.this,MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getService(Notification.this,0,intent1,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am =(AlarmManager)Notification.this.getSystemService(Notification.this.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

MyReceiver

  @Override 
public void onReceive(Context context,Intent intent){
// TODO自动生成的方法存根


long when = System.currentTimeMillis();
NotificationManager notificationManager =(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

Intent notificationIntent = new Intent(context,NotificationOpen.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

PendingIntent pendingIntent = PendingIntent.getActivity(context,0,
notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);


Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
context).setSmallIcon(R.drawable.birthday_icon)
.setContentTitle(Alert Me!)
.setContentText(今天是生日)setSound(alarmSound)
.setAutoCancel(true).setWhen(when)
.setContentIntent(pendingIntent)
.setVibrate(new long [] {1000,1000,1000 ,1000,1000});
notificationManager.notify(0,mNotifyBuilder.build());


}

DataBaseHelper

  public List< People> getPeopleDate(){
列表<人物> peoples = new ArrayList<>();

尝试{
SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME,null,SQLiteDatabase.OPEN_READWRITE);
游标cursor = db.rawQuery(select * from people,null);
while(cursor.moveToNext()){
String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));

String peopleDate = cursor.getString(cursor.getColumnIndex(PEOPLE_DATE));
String peopleMonth = cursor.getString(cursor.getColumnIndex(PEOPLE_MONTH));
String peopleYear = cursor.getString(cursor.getColumnIndex(PEOPLE_YEAR));

人们=新人();

people.setPeopleImage(peopleImage);
people.setPeopleName(peopleName);

people.setDate(peopleDate);
people.setMonth(peopleMonth);
people.setYear(peopleYear);

peoples.add(people);
}
} catch(异常e){
Log.d(DB,e.getMessage());
}
返回人;
}

People.class

  public class People implements Serializable {
private String peopleImage;
private String peopleName;
private String id;
private String月,日,年;

public String getDate(){
return date;
}

public void setDate(String date){
this.date = date;
}

public String getMonth(){
return month;
}

public void setMonth(String month){
this.month = month;
}

public String getYear(){
return year;
}

public void setYear(String year){
this.year = year;
}

public String getId(){
return id;
}

public void setId(String id){
this.id = id;
}

public void setPeopleName(String peopleName){
this.peopleName = peopleName;
}

public String getPeopleName(){
return peopleName;
}

public void setPeopleImage(String peopleImage){
this.peopleImage = peopleImage;
}

public String getPeopleImage(){
return peopleImage;
}

}

解决方案

月份名称整数



您的问题和代码很复杂,但您似乎挂起了将月份存储为文本它的英文名称。



首先,不要这样做,不要按其名称存储一个月。使用1 - 12月的平均整数,1-12。



但是,如果需要,您可以将月份的英文名称转换为枚举对象,因为枚举对象恰好用英文标签定义。从月份对象请求整数月份号。

 月= Month.valueOf(NOVEMBER); 
int monthNumber = m.getValue();

这个数字加上月日数可以用来获取一个 MonthDay 对象,并以下面代码中的方式使用。

  MonthDay md = MonthDay.of (monthNumber,dayOfMonthNumber); 



ISO 8601



存储周期性周年作为使用标准ISO 8601格式的文本数据类型的组合月日值: - MM-DD 。这是使用连字符代替年份的标准日期格式, YYYY-MM-DD 。这种格式的好处包括使用其他日期时间格式明确,按字母排序也按时间顺序排列。



MonthDay



java.time类 MonthDay 表示没有一年,没有时区的这个月日值。该类也知道如何使用上述标准格式生成和解析字符串。

  String mdString = myResultSet.getString(...); 
MonthDay md = MonthDay.parse(mdString);



ZonedDateTime



现在得到今天的日期。这样做需要一个时区,在任何给定的时刻,日期根据地区在全球范围内变化。

  ZoneId z = ZoneId.of(America / Montreal); 
ZonedDateTime now = ZonedDateTime.now(z);



LocalDate



从那里我们可以提取一个只有日期的值。

  LocalDate today = now.toLocalDate ); 

获取当前年份,以便我们确定生日。

  int year = today.atYear(); 
LocalDate birthday = md.atYear(year);

生日可能在过去,我们希望将来。

  if(!birthday.isAfter(今)){
birthday = birthday.plusYears(1);
}



持续时间 h1>

获取现在和未来生日之间的时间间隔,创建一个持续时间。显然你的报警系统需要毫秒。所以我们需要时间的一天。我们将在这一天的第一刻。但是你可能希望比午夜晚些时候发起警报!

  ZonedDateTime闹钟= birthday.atStartOfDay() ; 
持续时间d =持续时间(现在,闹钟);
long millis = d.toMillis();



Android



很多java。时间功能被转移到Java 6& 7三台港运输项目。



提示



不要打电话给一个月的日子日期,因为它是模糊的。按照java.time类中看到的命名。



不要将一个月作为英文名称存储。更容易存储1 - 12月的整数1-12。在你的Java代码中,使用个月枚举对象而不是文字或数字。


I have add static date in database sqlite and i have get this date and month column using object model and date and month wise set notification suppose today is 4 people birthday i have notification this 4 people name but error i have pass object to get date and month column so getting error

My database Column

DataType
TEXT                    Integer   Integer
Name                     dd         mm
"Indira Gandhi"         "19"        11
"Bal Gangadhar Tilak"   "23"        7
"Mangal Pandey"         "19"        7

Notification.java

People people = new People();
    Calendar calendar = Calendar.getInstance();
    try {
        String str_date = people.getDate();
        Log.d(getClass().getName(), "strDate" + str_date);
        String str_month = people.getMonth();
        DateFormat formatter;
        Date date, month;
        formatter = new SimpleDateFormat("dd-MMM");
        date = (Date) formatter.parse(str_date);
        Log.d(getClass().getName(), "str_date" + date);
        month = (Date) formatter.parse(str_month);
        Log.d(getClass().getName(), "str_month" + month);
        calendar.setTime(date);
        calendar.setTime(month);
        calendar.set(Calendar.HOUR_OF_DAY, 10);
        calendar.set(Calendar.MINUTE, 59);
        calendar.set(Calendar.SECOND, 0);
        calendar.setTime(month);
    } catch (ParseException e) {
        e.printStackTrace();
    }


    Intent intent1 = new Intent(Notification.this, MyReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getService(Notification.this, 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
    AlarmManager am = (AlarmManager) Notification.this.getSystemService(Notification.this.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);

MyReceiver

@Override
public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub


        long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent notificationIntent = new Intent(context, NotificationOpen.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
            notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);


    Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder mNotifyBuilder = new NotificationCompat.Builder(
            context).setSmallIcon(R.drawable.birthday_icon)
            .setContentTitle("Alert Me!")
            .setContentText("Today is Birthday").setSound(alarmSound)
            .setAutoCancel(true).setWhen(when)
            .setContentIntent(pendingIntent)
            .setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
    notificationManager.notify(0, mNotifyBuilder.build());


}

DataBaseHelper

 public List<People> getPeopleDate() {
    List<People> peoples = new ArrayList<>();

    try {
        SQLiteDatabase db = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE);
        Cursor cursor = db.rawQuery("select * from people", null);
        while (cursor.moveToNext()) {
            String peopleImage = cursor.getString(cursor.getColumnIndex(PEOPLE_IMAGE));
            String peopleName = cursor.getString(cursor.getColumnIndex(PEOPLE_NAME));

            String peopleDate = cursor.getString(cursor.getColumnIndex(PEOPLE_DATE));
            String peopleMonth = cursor.getString(cursor.getColumnIndex(PEOPLE_MONTH));
            String peopleYear = cursor.getString(cursor.getColumnIndex(PEOPLE_YEAR));

            People people = new People();

            people.setPeopleImage(peopleImage);
            people.setPeopleName(peopleName);

            people.setDate(peopleDate);
            people.setMonth(peopleMonth);
            people.setYear(peopleYear);

            peoples.add(people);
        }
    } catch (Exception e) {
        Log.d("DB", e.getMessage());
    }
    return peoples;
}

People.class

public class People implements Serializable {
private String peopleImage;
private String peopleName;
private String id;
private String month, date, year;

public String getDate() {
    return date;
}

public void setDate(String date) {
    this.date = date;
}

public String getMonth() {
    return month;
}

public void setMonth(String month) {
    this.month = month;
}

public String getYear() {
    return year;
}

public void setYear(String year) {
    this.year = year;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public void setPeopleName(String peopleName) {
    this.peopleName = peopleName;
}

public String getPeopleName() {
    return peopleName;
}

public void setPeopleImage(String peopleImage) {
    this.peopleImage = peopleImage;
}

public String getPeopleImage() {
    return peopleImage;
}

}

解决方案

Month name to integer

Your Question and code are quite convoluted, but you seem to be hung up on storing month as text by its name in English.

Firstly, don't do this, don't store a month by its name. Use a plain integer, 1-12 for January-December.

But if you must, you can convert an English name of month to a Month enum object, as the enum objects happen to be defined with labels in English. From that Month object ask for the integer month number.

Month m = Month.valueOf( "NOVEMBER" );
int monthNumber = m.getValue();

This number plus the day-of-month number can be used to get a MonthDay object and used in a manner seen in code below.

MonthDay md = MonthDay.of( monthNumber , dayOfMonthNumber );

ISO 8601

Store a recurring anniversary as a combined month-day value in a text data-type using standard ISO 8601 format: --MM-DD. That is the standard date format using a hyphen in place of the year, YYYY-MM-DD. Benefits of this format include bring unambiguous with other date-time formats, and sorting alphabetically is also chronological.

MonthDay

The java.time class MonthDay represents this month-day value without a year and without a time zone. This class also knows how to generate and parse strings in that standard format described above.

String mdString = myResultSet.getString( … );
MonthDay md = MonthDay.parse( mdString );

ZonedDateTime

Now get today’s date. Doing so requires a time zone as for any given moment the date varies around the globe by zone.

ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( z );

LocalDate

From that we can extract a date-only value.

LocalDate today = now.toLocalDate();

Get the current year so we might determine the birthday.

int year = today.atYear();
LocalDate birthday= md.atYear( year );

That birthday may be in the past, and we want the future.

if( ! birthday.isAfter( today ) ) {
    birthday = birthday.plusYears( 1 );
}

Duration

Get the span of time between now and that future birthday, create a Duration. Apparently your alarm system needs milliseconds. So we need time-of-day. We will go with first moment of the day here. But you probably want a later time-of-day than midnight to fire an alarm!

ZonedDateTime alarm = birthday.atStartOfDay();
Duration d = Duration.between( now , alarm );
long millis = d.toMillis();

Android

Much of the java.time functionality was back-ported to Java 6 & 7 the ThreeTen-Backport project. Further adapted to Android in the ThreeTenABP project.

Tips

Do not call a day-of-month a "date" as it is ambiguous. Follow the naming seen in the java.time classes.

Do not store a month as an English name. Simpler to store an integer 1-12 for January-December. And in your Java code, use the Month enum objects rather than text or numbers.

这篇关于如何在Android中使用对象模型数据库获取日期和月份列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆