I am facing a issue while adding a alarmManager.
Basicly I'm trying to add a alarm on specific time and it's working fine whether app is in background or in foreground. but the issue is that it's not going to trigger when app is removed from background or app is killed.
I want to trigger alarm whether app is running or not (issue faced when app is closed).
I'm little bit desperate.
Here is my Code :
public class AlarmReciver extends BroadcastReceiver {
public AlarmReciver(){
super();
}
#Override
public void onReceive(Context context, Intent intent) {
Log.d("called","called");
Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
//This will send a notification message and show notification in notification tray
/* ComponentName comp = new ComponentName(context.getPackageName(),
AlarmNotificationService.class.getName());
startWakefulService(context, (intent.setComponent(comp)));*/
try {
ManageDatabase manageDatabase = new ManageDatabase();
// manageDatabase.setupdatabase(context);
// For our recurring task, we'll just display a message
// Toast.makeText(context, "Alarm received!", Toast.LENGTH_LONG).show();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
String today_date=String.valueOf(calendar.get(Calendar.DAY_OF_MONTH))+"/"+String.valueOf((calendar.get(Calendar.MONTH)+1))+"/"+String.valueOf(calendar.get(Calendar.YEAR));
today_date= datetimeformat.getdate(today_date);
String id = intent.getStringExtra("id").toString();
String pid = intent.getStringExtra("pid").toString();
manageDatabase.cancelallreminders_without_update(context);
manageDatabase.setallactivatedalarm(context);
manageDatabase.addtodaysidlist(id,today_date,context);
// Enable a receiver
/* ComponentName receiver = new ComponentName(context, AlarmReciver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);*/
Intent service1 = new Intent(context, Show_Reminder.class);
service1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
service1.putExtra("id", id);
service1.putExtra("pid", pid);
context.startActivity(service1);
Toast.makeText(context,"alarm is triggered...", Toast.LENGTH_LONG).show();
Log.d("alarm is","triggered");
}catch (Exception e)
{
Log.e("error",e.toString());
e.printStackTrace();
}
}
}
Manifest file :
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name="com.pragma.healthopediaplus.Medicine_reminder.Utils.Reminders.AlarmReciver"
android:exported="false"
android:process=":remote">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PACKAGE_RESTARTED" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
</intent-filter>
</receiver>
set alarm from database.java
public void setallactivatedalarm(Context context) {
db= context.openOrCreateDatabase("Reminder"+ SharedPreference.getvalue("username",context)+".db",Context.MODE_PRIVATE,null);
Cursor c1 = db.rawQuery("select * from reminderdata",null);
Log.d("Set all activate alarm","inside");
while (c1.moveToNext())
{
if(c1.getString(6).equals("active"))
{
Date date_type=new Date();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try {
Gson gson = new Gson();
ArrayList<Info> infodata = gson.fromJson(c1.getString(2), new TypeToken<ArrayList<Info>>() {
}.getType());
// Log.d("reminder", " setReminder " + c1.getString(1) + " " + c1.getString(3) + " " + c1.getString(5) + " " + infodata + " " + Integer.parseInt(c1.getString(4)) + " " + context + " " + Integer.parseInt(c1.getString(0)));
String alltime[]=infodata.get(7).getValue().split(",");
String maxtime= datetimeformat.gettimehhmm(alltime[0]);
String weekday;
for(int i=1;i<alltime.length;i++)
{
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
Date inTime = sdf.parse(maxtime);
Date outTime = sdf.parse(datetimeformat.gettimehhmm(alltime[i]));
if(outTime.compareTo(inTime) > 0){
maxtime= datetimeformat.gettimehhmm(alltime[i]);
}
}
String timedata=maxtime;
String timearray[]=timedata.split(":");
date_type = format.parse(c1.getString(3));
Calendar newtime = Calendar.getInstance();
newtime.setTime(date_type);
newtime.set(Calendar.MINUTE,Integer.parseInt(timearray[1]));
newtime.set(Calendar.SECOND,00);
newtime.set(Calendar.HOUR_OF_DAY,Integer.parseInt(timearray[0]));
Calendar currenttime=Calendar.getInstance();
if(newtime.getTimeInMillis()<=currenttime.getTimeInMillis())
{
/* flag 1 for everyday 2 for month 3 for everyyear 4 onetime*/
if(c1.getString(4).equals("1"))
{
newtime.add(Calendar.DATE, 1);
}
else if(c1.getString(4).equals("2"))
{
newtime.add(Calendar.MONTH, 1);
}
else if(c1.getString(4).equals("3"))
{
newtime.add(Calendar.YEAR, 1);
}
else if(c1.getString(4).equals("5"))
{
int weekdayint = 0;
int dayOfWeek=newtime.get(Calendar.DAY_OF_WEEK);
String weekDay = null;
if (Calendar.MONDAY == dayOfWeek) {
weekdayint=Calendar.MONDAY;
weekDay = context.getString(R.string.Monday);
} else if (Calendar.TUESDAY == dayOfWeek) {
weekdayint=Calendar.TUESDAY;
weekDay = context.getString(R.string.Tuesday);
} else if (Calendar.WEDNESDAY == dayOfWeek) {
weekdayint=Calendar.WEDNESDAY;
weekDay = context.getString(R.string.Wednesday);
} else if (Calendar.THURSDAY == dayOfWeek) {
weekdayint=Calendar.THURSDAY;
weekDay = context.getString(R.string.Thursday);
} else if (Calendar.FRIDAY == dayOfWeek) {
weekdayint=Calendar.FRIDAY;
weekDay = context.getString(R.string.Friday);
} else if (Calendar.SATURDAY == dayOfWeek) {
weekdayint=Calendar.SATURDAY;
weekDay = context.getString(R.string.Saturday);
} else if (Calendar.SUNDAY == dayOfWeek) {
weekdayint=Calendar.SUNDAY;
weekDay = context.getString(R.string.Sunday);
}
weekday=infodata.get(9).getValue();
String day[]=weekday.split(",");
String next="";
int nxtday = 0;
int addday;
int count[]={1,2,3,4,5,6,7,1,2,3,4,5,6,7};
String getweek[]={"",context.getString(R.string.Sunday),context.getString(R.string.Monday),context.getString(R.string.Tuesday)
,context.getString(R.string.Wednesday), context.getString(R.string.Thursday),
context.getString(R.string.Friday),context.getString(R.string.Saturday)};
for(int i=weekdayint;i<weekdayint+7;i++)
{
int c=count[i];
if (Arrays.asList(day).contains(getweek[c])) {
next=getweek[c];
nxtday=c;
break;
}
}
if(nxtday>weekdayint)
{
addday=nxtday-weekdayint;
}else
{
addday=nxtday-weekdayint+7;
}
newtime.add(Calendar.DATE, addday);
}
int thisYear = newtime.get(Calendar.YEAR);
int thisMonth = newtime.get(Calendar.MONTH);
int thisDay = newtime.get(Calendar.DAY_OF_MONTH);
String newdate=thisDay+"/"+(thisMonth+1)+"/"+thisYear;
newdate=datetimeformat.getdate(newdate);
db.execSQL("update reminderdata set duedate='"+newdate+"'where id='"+c1.getString(0)+"'");
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("error",e.toString());
}
Gson gson = new Gson();
ArrayList<Info> infodata = gson.fromJson(c1.getString(2), new TypeToken<ArrayList<Info>>() {
}.getType());
// Log.d("reminder", " setReminder "+c1.getString(1)+" "+c1.getString(3)+" "+ c1.getString(5)+" "+ infodata+" "+Integer.parseInt(c1.getString(4))+" "+ context+" "+Integer.parseInt(c1.getString(0)));
String alltime[]=infodata.get(7).getValue().split(",");
Log.d("all time",infodata.get(7).getValue());
Log.d("all time length",alltime.length+"");
String pid[]=getPidsfromrid(Integer.parseInt(c1.getString(0)),context).split(",");
for(int i=0;i<alltime.length;i++)
{Log.d("pids",pid[i]);
Log.d("set reminder called",alltime[i]);
setReminder( c1.getString(3), context,
Integer.parseInt(c1.getString(0)),alltime[i],Integer.parseInt(pid[i]));
}
}
}
db.close();
}
public boolean setReminder(String date,Context context,int id,String time,int pid) {
Intent myIntent = new Intent(context, AlarmReciver.class);
myIntent.putExtra("id",String.valueOf(id));
myIntent.putExtra("pid",String.valueOf(pid));
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, myIntent,
0);
Date date_type=new Date();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
try
{
date_type = format.parse(date);
} catch (Exception e) {
e.printStackTrace();
}
String timedata= datetimeformat.gettimehhmm(time);
String timearray[]=timedata.split(":");
Calendar calendar = Calendar.getInstance();
calendar.setTime(date_type);
calendar.set(Calendar.MINUTE,Integer.parseInt(timearray[1]));
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.HOUR_OF_DAY,Integer.parseInt(timearray[0]));
Calendar current = Calendar.getInstance();
Log.d("set reminder inside",time);
if(calendar.compareTo(current) <= 0){
calendar.add(Calendar.DATE, 1);
Log.d("set reminder inside ","not set alarm"+time);
// Toast.makeText(context,"Invalid Date/Time",Toast.LENGTH_LONG).show();
} else{
Log.d("set reminder inside ","set alarm"+time);
Log.d("set reminder inside",time);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(),
pendingIntent);
/* int SDK_INT = Build.VERSION.SDK_INT;
if (SDK_INT < Build.VERSION_CODES.KITKAT)
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
else if (Build.VERSION_CODES.KITKAT <= SDK_INT && SDK_INT < Build.VERSION_CODES.M)
alarmManager.setExact(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
else if (SDK_INT >= Build.VERSION_CODES.M) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), pendingIntent);
}
*/
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+2000, pendingIntent);
}else {
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis()+2000, pendingIntent);
}*/
}
try {
//Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
return true;
}
Closing the app closes all the Alarms as well. What you need instead is to set up Alarms from a Background Service instead.
You can reuse almost all of your existing code, and will have to create an additional class (preferably in new file) for the service. You'll also have to register the service in the manifest file, and move the code for creating alarm into the service class.
Example for creating a background service is here: https://developer.android.com/training/run-background-service/create-service
Note the background services have some limitations, but they can be set to be active even after REBOOT of the device.
Depending on your use case, you could also look into JobScheduler, that can run periodically and use that to set Alarms (dynamically, or otherwise). If your Alarms don't have to be 'Exact', you can just get the task done in JobScheduler itself, as it's almost as accurate as Alarm Manager. I say this because after Android O, doze mode takes away accuracy of Alarm Manager as well as JobScheduler.
Related
How to handle datepicker control in Katalon studio?
I am very new to Katalon studio.
Here is custom keyword to handle bootstrap date-picker.
package framework
class component{
#Keyword
public static void handleDatepicker(TestObject calender, String exp_Date, String exp_Month,
String exp_Year) throws Exception {
String expDate = null, calYear = null,datepickerText=null,minYear=null,maxYear=null;
int expMonth = 0, expYear = 0;
WebElement datePicker;
List<WebElement> noOfDays=null,noOfMonths=null,noOfYears=null;
boolean dateNotFound = true;
List<String> monthList = Arrays.asList("None","Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul",
"Aug", "Sep", "Oct", "Nov", "Dec");
def driver = DriverFactory.getWebDriver()
WebElement SelectCalender = WebUiCommonHelper.findWebElement(calender, 20);
SelectCalender.click()
expDate = (exp_Date);
expMonth = Integer.parseInt(exp_Month);
expYear = Integer.parseInt(exp_Year);
WebElement datePicker_Heading1 =(driver).findElement(By.xpath("//div[#class='datepicker-days']/table/thead/tr[1]/th[2]"));
WebDriverWait wait = new WebDriverWait(driver,10);
wait.until(ExpectedConditions.elementToBeClickable(datePicker_Heading1));
datePicker_Heading1.click();
WebElement datePicker_Heading2 =(driver).findElement(By.xpath("//div[#class='datepicker-months']/table/thead/tr[1]/th[2]"));
wait.until(ExpectedConditions.elementToBeClickable(datePicker_Heading2));
datePicker_Heading2.click();
while (dateNotFound) {
WebElement datePicker_Heading3 =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[2]"));
wait.until(ExpectedConditions.visibilityOf(datePicker_Heading3));
datepickerText =datePicker_Heading3.getText();
String[] datepickerYear = datepickerText.split("-");
minYear =datepickerYear[0];
maxYear = datepickerYear[1];
if((expYear >= Integer.parseInt(minYear)) && (expYear<=Integer.parseInt(maxYear)))
{
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-years']/table"));
noOfYears = datePicker.findElements(By.xpath("//span[contains(#class,'year')]"));
firstloop:
for (WebElement year : noOfYears) {
if (year.getText().equalsIgnoreCase((String)exp_Year)) {
year.click();
Thread.sleep(1500);
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-months']/table"));
//noOfMonths = datePicker.findElements(By.xpath("//span[#class='month']"));
noOfMonths = datePicker.findElements(By.cssSelector("span.month"));
Thread.sleep(1000);
for (WebElement month : noOfMonths) {
System.out.println(" the expected month in int is : "+expMonth);
System.out.println(" the expected month is : "+monthList.get(expMonth));
System.out.println(" the Actual month is : "+month.getText());
if ((monthList.get(expMonth)).equalsIgnoreCase(month.getText())) {
System.out.println("days ");
month.click();
datePicker = (driver).findElement(By.xpath("//div[#class='datepicker-days']/table"));
noOfDays = datePicker.findElements(By.xpath("//td[#class='day']"));
Thread.sleep(1500);
for (WebElement cell : noOfDays) {
if (cell.getText().equalsIgnoreCase(expDate)) {
System.out.println("days ");
cell.click();
break firstloop;
}
}
}
}
}
}
dateNotFound = false;
}else if (expYear > Integer.parseInt(maxYear)) {
WebElement Next =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[#class='next']"));
if(Next.getAttribute("style").equalsIgnoreCase("visibility: visible;"))
{// Click on next button of date picker.
Next.click();
}else {
throw new Exception("This is exception")
}
}
// If current selected month and year are greater than expected
// month and year then go Inside this condition.
else if (expYear < Integer.parseInt(minYear)) {
WebElement Previous =(driver).findElement(By.xpath("//div[#class='datepicker-years']/table/thead/tr[1]/th[#class='prev']"));
if(Previous.getAttribute("style").equalsIgnoreCase("visibility: visible;"))
{
// Click on previous button of date picker.
Previous.click();
}else{
throw new Exception("This is exception")
}
}
}
}
}
You can use above keyword as below
CustomKeywords.'framework.component.handleDatepicker'(findTestObject('testobject'),'10', '12', '1990')
Note : "Framework" folder had been created by us as inside the Keyword folder and then We had created the "component" keyword
This way you can able to create custom keyword as per your component.
I hope this might help you and other developers.
Maybe this can help, it seems to be a similar situation:
https://forum.katalon.com/discussion/1999/how-to-handle-date-pickers-in-katalon.
There are some generic project templates in Katalon Studio 6.2.0. One of them is "Tips and Tricks with Katalon Studio" that contains a "Datepicker.groovy" file with this generic datepicker code that you can adapt as you wish:
import static com.kms.katalon.core.testobject.ObjectRepository.findTestObject
import com.kms.katalon.core.annotation.Keyword
import com.kms.katalon.core.model.FailureHandling
import com.kms.katalon.core.testobject.TestObject
import com.kms.katalon.core.webui.keyword.WebUiBuiltInKeywords as WebUI
import static java.util.Calendar.*
import org.apache.xerces.jaxp.datatype.XMLGregorianCalendarImpl.DaysInMonth
class Datepicker {
Date date;
TestObject obj;
Datepicker() {}
Datepicker(TestObject object, String input_date) {
this.obj = object;
date = new Date().parse("MM/dd/yyyy", input_date)
}
def open_calendar_form() {
WebUI.waitForElementClickable(this.obj, 0)
WebUI.click(this.obj)
}
def displaying_month() {
WebUI.waitForElementVisible(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_month'), 0)
return WebUI.getText(
findTestObject('Object Repository/jqueryui/widgets/datepicker/date_month'),
FailureHandling.STOP_ON_FAILURE)
}
def displaying_year() {
WebUI.waitForElementVisible(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_year'), 0)
return WebUI.getText(
findTestObject('Object Repository/jqueryui/widgets/datepicker/date_year'),
FailureHandling.STOP_ON_FAILURE)
}
def displaying_date() {
return new Date().parse("MMM/yyyy", displaying_month() + "/" + displaying_year())
}
def pick_year() {
if (displaying_date()[YEAR] == date[YEAR]) return
while (displaying_date()[YEAR] < date[YEAR]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Next'))
}
while (displaying_date()[YEAR] > date[YEAR]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Prev'))
}
}
def pick_month() {
if (displaying_date()[MONTH] == date[MONTH]) return
while (displaying_date()[MONTH] < date[MONTH]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Next'))
}
while (displaying_date()[MONTH] > date[MONTH]) {
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/Prev'))
}
}
def pick_day() {
println date[DAY_OF_MONTH]
WebUI.click(findTestObject('Object Repository/jqueryui/widgets/datepicker/date_day', [('day') : date[DAY_OF_MONTH]]))
}
def pick_date() {
pick_year()
pick_month()
pick_day()
}
#Keyword
def pickDate(TestObject ob, String date) {
def picker = new Datepicker(ob, date)
picker.open_calendar_form()
picker.pick_date()
}
}
If your datepicker widget is anything like the ones in Zoho (it auto-populates with today's date, and setting the text to different date either has no effect or appends to today's date string), try this out:
public final class GeneralWebUIUtils {
public static final String VALUE = "value";
public static String GetTextValue(TestObject to) {
return WebUI.getAttribute(to, this.VALUE)
}
public static Keys GetCommandKey() {
final String os = System.getProperty("os.name")
if (os.toUpperCase().contains("WINDOWS"))
return Keys.CONTROL;
return Keys.COMMAND;
}
public static void ClearAndEnterText(TestObject to, String text) {
WebUI.sendKeys(to,
Keys.chord("${this.GetCommandKey().toString()}A"),
FailureHandling.STOP_ON_FAILURE);
WebUI.sendKeys(to, text, FailureHandling.STOP_ON_FAILURE);
}
public static void UpdateDateField(TestObject to, Date newDate) {
this.WaitForTextFieldNonEmpty(to, 1, FailureHandling.CONTINUE_ON_FAILURE)
if (newDate == null) {
WebUI.clearText(to, FailureHandling.STOP_ON_FAILURE);
return;
}
final String fieldTextValue = this.GetTextValue(to),
newDateTextValue = SMDDateUtils.ToDateString(newDate);
if ((!newDateTextValue.isEmpty()) && (!fieldTextValue.equals(newDateTextValue))) {
this.ClearAndEnterText(to, newDateTextValue);
KeywordUtil.logInfo("'${newDateTextValue}' written to the date field")
}
WebUI.sendKeys(to, Keys.TAB.toString());
KeywordUtil.logInfo("After trying to write to the field, it has value '${this.GetTextValue(to)}'")
}
public static boolean WaitForElementCondition(Closure<Boolean> onCheckCondition, Closure onContinue, TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
final long startTime = System.currentTimeMillis()
boolean isConditionSatisfied = false;
while ((System.currentTimeMillis() < startTime + timeOut * 1000) && (!isConditionSatisfied)) {
isConditionSatisfied = WebUI.waitForElementPresent(to, 1, failureHandling) && onCheckCondition(to);
if (onContinue != null)
onContinue(isConditionSatisfied, to);
}
if ((!isConditionSatisfied) && (failureHandling.equals(FailureHandling.STOP_ON_FAILURE))) {
KeywordUtil.markFailedAndStop("Condition for TestObject '${to.getObjectId()}' not met after ${(System.currentTimeMillis() - startTime) / 1000} seconds");
}
return isConditionSatisfied;
}
public static boolean WaitForTextFieldNonEmpty(TestObject to, int timeOut, FailureHandling failureHandling = FailureHandling.STOP_ON_FAILURE) {
return this.WaitForElementCondition({ TestObject testObj ->
return (!this.GetTextValue(testObj).isEmpty());
},
null,
to,
timeOut,
failureHandling);
}
}
public final class SMDDateUtils {
// TODO: replace with the date format that you use in your project
private static DateFormat DateFormat = new SimpleDateFormat("MM-dd-yyyy");
public static String ToDateString(Date date) {
return this.DateFormat.format(date);
}
}
Save that to two keywords: GeneralWebUIUtils and SMDDateUtils (feel free to replace the name prefix on that one :) )
Then you can just be like:
GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), todaysDate)
to update to todaysDate
and even
GeneralWebUIUtils.UpdateDateField(findTestObject('Order/dataSigned'), null)
to clear it! :)
DISCLAIMER: those utils are pulled straight from my testing codebase.
I have an issue of connecting bluetooth device through mobile and i can able to send bytes as Outputstream but i cant able to retrive print from Evolute impress printer.Please help me how to get the print
Problem:
how to check evolute printer whether its reciving data which i sent.
Main.java
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc,check;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
check = (Button)findViewById(R.id.check);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
DeviceListActivity
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
}
UnicodeFormatter:
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.printapplication"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<permission
android:name="android.permission.BLUETOOTH"
android:label="BLUETOOTH" >
</permission>
<permission android:name="android.permission.BLUETOOTH_ADMIN" >
</permission>
<uses-sdk
android:minSdkVersion="15"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".DeviceListActivity"
android:label="#string/app_name" >
</activity>
</application>
</manifest>
I get the following log during on-device debugging
Error:
*** [Play Games Plugin DLL] ERROR: Cloud load failed with status code 7
Basically the OnStateLoaded() callback function always returns the boolean success = false and I can't figure out the reason why.
All that the plugin debugging logs mention is "Cloud load failed with status code 7".
According to the android doc, 7 is a generic "developer error", see https://developer.android.com/reference/com/google/android/gms/appstate/AppStateStatusCodes.html#STATUS_DEVELOPER_ERROR
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set
to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID
Created a new project in Unity
Added the play games plugin (Assets/Import Package.../Custom
Package)
Set the application ID (Google Play Games/Android Setup...)
Switched the platform to Android (File/Build Settings...)
Set the player settings (bundle identifier and the keystore info)
Added a new script component to the camera
Saved everything and hit build and run.
Here are the contents:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
void Start () {
slot0 = new GameData(0,"waiting for login....");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.Data =" loading....";
slot0.LoadState();
}
else {
Debug.LogWarning("Authentication failed!");
}
};
// make Play Games the default social implementation
PlayGamesPlatform.Activate();
// enable debug logs
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
protected void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,100);
Rect dataRect = new Rect( 10, 150, Screen.width,100);
Rect b1Rect = new Rect(10, 400, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth,
b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
// logged in, so show the load button and the contents of the saved data.
if(GUI.Button(b1Rect, "Load")) {
slot0.LoadState();
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
// just save a string, incrementing the number on the end.
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
slot0.SaveState();
}
GUI.Label(statusRect, slot0.State);
}
// Class to handle save/load callbacks.
public class GameData : OnStateLoadedListener {
int slot;
string data;
string state;
public GameData(int slot, string data) {
this.slot = slot;
this.data = data;
this.state = "Initialized, modified";
}
public void LoadState() {
this.state += ", loading";
((PlayGamesPlatform)Social.Active).LoadState(0, this);
}
public void SaveState() {
byte[] bytes = new byte[data.Length * sizeof(char)];
System.Buffer.BlockCopy(data.ToCharArray(), 0, bytes, 0, bytes.Length);
this.state += ", saving";
((PlayGamesPlatform) Social.Active).UpdateState(slot, bytes, this);
}
public void OnStateLoaded(bool success, int slot, byte[] data) {
if (success) {
Debug.Log ("Save game slot : " + slot + " loaded: " + data);
if (data != null) {
char[] chars = new char[data.Length / sizeof(char)];
System.Buffer.BlockCopy(data, 0, chars, 0, data.Length);
this.data = new string(chars);
this.state = "loaded";
} else {
Debug.Log ("Saved data is null");
this.data = "";
this.state = "loaded, but empty";
}
} else {
// handle failure
Debug.LogWarning ("Save game slot : " + slot + " failed!: ");
this.data = "";
this.state = "loading failed!";
}
}
public byte[] OnStateConflict(int slot, byte[] local, byte[] server) {
// resolve conflict and return a byte[] representing the
// resolved state.
Debug.LogWarning("Conflict in saved data!");
state = "conflicted";
// merge or resolve using app specific logic, here
byte[] resolved = local.Length > server.Length ? local : server;
char[] chars = new char[resolved.Length / sizeof(char)];
System.Buffer.BlockCopy(resolved, 0, chars, 0, resolved.Length);
this.data = new string(chars);
return resolved;
}
public void OnStateSaved(bool success, int slot) {
Debug.Log ("Save game slot : " + slot + " success: " + success);
state = "saved";
}
public string Data {
get {
return data;
}
set {
data = value;
state += ", modified";
}
}
public int Slot {
get {
return slot;
}
}
public string State {
get {
return state;
}
}
}
}
The error code 7 is because the Cloud Save API has been deprecated and is only currently accessible to existing games that have used the API. The Unity plugin version 0.9.11 has been updated to use the SavedGames API.
I tried a quick sample and everything worked ok. Here are my steps:
Created a new game in the play console
(https://play.google.com/apps/publish)
Made sure Saved Games is set to ON
Linked an Android Application Remembering the application ID
(the number after the title) and the package ID Created a new
project in Unity
Added the play games plugin (Assets/Import
Package.../Custom Package)
Set the application ID (Google Play
Games/Android Setup...)
Switched the platform to Android (File/Build
Settings...)
Set the player settings (bundle identifier and the
keystore info)
Added a new script component to the camera Saved
everything and hit build and run.
Here is my script:
using UnityEngine;
using System.Collections;
using GooglePlayGames;
using GooglePlayGames.BasicApi;
using System;
using GooglePlayGames.BasicApi.SavedGame;
public class SaveSample : MonoBehaviour {
System.Action<bool> mAuthCallback;
GameData slot0;
bool mSaving;
private Texture2D mScreenImage;
// Use this for initialization
void Start () {
slot0 = new GameData("New game");
mAuthCallback = (bool success) => {
if (success) {
Debug.Log("Authentication was successful!");
slot0.State = "Click load or save";
}
else {
Debug.LogWarning("Authentication failed!");
}
};
PlayGamesClientConfiguration config = new PlayGamesClientConfiguration.Builder()
.EnableSavedGames()
.Build();
PlayGamesPlatform.InitializeInstance(config);
// Activate the Play Games platform. This will make it the default
// implementation of Social.Active
PlayGamesPlatform.Activate();
// enable debug logs (note: we do this because this is a sample; on your production
// app, you probably don't want this turned on by default, as it will fill the user's
// logs with debug info).
PlayGamesPlatform.DebugLogEnabled = true;
//Login explicitly for this sample, usually this would be silent
PlayGamesPlatform.Instance.Authenticate(mAuthCallback, false);
}
public void CaptureScreenshot() {
mScreenImage = new Texture2D(Screen.width, Screen.height);
mScreenImage.ReadPixels(new Rect(0, 0, Screen.width, Screen.height), 0, 0);
mScreenImage.Apply();
}
protected virtual void OnGUI() {
Screen.fullScreen = true;
int buttonHeight = Screen.height / 20;
int buttonWidth = Screen.width / 5;
GUI.skin.label.fontSize = 60;
GUI.skin.button.fontSize = 60;
Rect statusRect = new Rect(10,20,Screen.width,200);
Rect dataRect = new Rect( 10, 250, Screen.width,100);
Rect b1Rect = new Rect(10, 800, buttonWidth, buttonHeight);
Rect b2Rect = new Rect(b1Rect.x + 20 + buttonWidth, b1Rect.y, buttonWidth, buttonHeight);
if(!Social.localUser.authenticated) {
if(GUI.Button(b1Rect, "Signin")) {
Social.localUser.Authenticate(mAuthCallback);
}
}
else {
if(GUI.Button(b1Rect, "Load")) {
mSaving = false;
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Select game to load",
4,false,false,SavedGameSelected);
}
GUI.Label(dataRect, slot0.Data);
}
if(GUI.Button(b2Rect, "Save")) {
int idx = slot0.Data.IndexOf("_");
if (idx > 0) {
int val = Convert.ToInt32(slot0.Data.Substring(idx+1));
val++;
slot0.Data = "Save_" + val;
}
else {
slot0.Data = "Save_0";
}
mSaving = true;
CaptureScreenshot();
((PlayGamesPlatform)Social.Active).SavedGame.ShowSelectSavedGameUI("Save game progress",
4,true,true,SavedGameSelected);
}
GUI.Label(statusRect, slot0.State);
}
public void SavedGameSelected(SelectUIStatus status, ISavedGameMetadata game) {
if (status == SelectUIStatus.SavedGameSelected) {
string filename = game.Filename;
Debug.Log("opening saved game: " + game);
if(mSaving && (filename == null || filename.Length == 0)) {
filename = "save" + DateTime.Now.ToBinary();
}
if (mSaving) {
slot0.State = "Saving to " + filename;
}
else {
slot0.State = "Loading from " + filename;
}
//open the data.
((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(filename,
DataSource.ReadCacheOrNetwork,
ConflictResolutionStrategy.UseLongestPlaytime,
SavedGameOpened);
} else {
Debug.LogWarning("Error selecting save game: " + status);
}
}
public void SavedGameOpened(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
if( mSaving) {
slot0.State = "Opened, now writing";
byte[] pngData = (mScreenImage!=null) ?mScreenImage.EncodeToPNG():null;
Debug.Log("Saving to " + game);
byte[] data = slot0.ToBytes();
TimeSpan playedTime = slot0.TotalPlayingTime;
SavedGameMetadataUpdate.Builder builder = new
SavedGameMetadataUpdate.Builder()
.WithUpdatedPlayedTime(playedTime)
.WithUpdatedDescription("Saved Game at " + DateTime.Now);
if (pngData != null) {
Debug.Log("Save image of len " + pngData.Length);
builder = builder.WithUpdatedPngCoverImage(pngData);
}
else {
Debug.Log ("No image avail");
}
SavedGameMetadataUpdate updatedMetadata = builder.Build();
((PlayGamesPlatform)Social.Active).SavedGame.CommitUpdate(game,updatedMetadata,data,SavedGameWritten);
} else {
slot0.State = "Opened, reading...";
((PlayGamesPlatform)Social.Active).SavedGame.ReadBinaryData(game,SavedGameLoaded);
}
} else {
Debug.LogWarning("Error opening game: " + status);
}
}
public void SavedGameLoaded(SavedGameRequestStatus status, byte[] data) {
if (status == SavedGameRequestStatus.Success) {
Debug.Log("SaveGameLoaded, success=" + status);
slot0 = GameData.FromBytes(data);
} else {
Debug.LogWarning("Error reading game: " + status);
}
}
public void SavedGameWritten(SavedGameRequestStatus status, ISavedGameMetadata game) {
if(status == SavedGameRequestStatus.Success) {
Debug.Log ("Game " + game.Description + " written");
slot0.State = "Saved!";
} else {
Debug.LogWarning("Error saving game: " + status);
}
}
public class GameData {
private TimeSpan mPlayingTime;
private DateTime mLoadedTime;
string mData;
string mState;
static readonly string HEADER = "GDv1";
public GameData(string data) {
mData = data;
mState = "Initialized, modified";
mPlayingTime = new TimeSpan();
mLoadedTime = DateTime.Now;
}
public TimeSpan TotalPlayingTime {
get {
TimeSpan delta = DateTime.Now.Subtract(mLoadedTime);
return mPlayingTime.Add(delta);
}
}
public override string ToString () {
string s = HEADER + ":" + mData;
s += ":" + TotalPlayingTime.TotalMilliseconds;
return s;
}
public byte[] ToBytes() {
return System.Text.ASCIIEncoding.Default.GetBytes(ToString());
}
public static GameData FromBytes (byte[] bytes) {
return FromString(System.Text.ASCIIEncoding.Default.GetString(bytes));
}
public static GameData FromString (string s) {
GameData gd = new GameData("initializing from string");
string[] p = s.Split(new char[] { ':' });
if (!p[0].StartsWith(HEADER)) {
Debug.LogError("Failed to parse game data from: " + s);
return gd;
}
gd.mData = p[1];
double val = Double.Parse(p[2]);
gd.mPlayingTime = TimeSpan.FromMilliseconds(val>0f?val:0f);
gd.mLoadedTime = DateTime.Now;
gd.mState = "Loaded successfully";
return gd;
}
public string Data {
get {
return mData;
}
set {
mData = value;
mState += ", modified";
}
}
public string State {
get {
return mState;
}
set {
mState = value;
}
}
}
}
i am working on a requirement. what i need to do is to retreieve the last enetered date from database, increment it and then check if the day is saturday or not.
the part i am stuck at is how to check if the next day is saturday i am using primefaces 3.5 jsf2.1 apache tomcat 7.0.39
FacesContext context = FacesContext.getCurrentInstance();
Map requestMap = context.getExternalContext().getRequestParameterMap();
String value = (String) requestMap.get("id");
Integer id = Integer.parseInt(value);
SimpleDateFormat sdf= new SimpleDateFormat();
String sector=new String();
setFund(new Fund());
for(Map row:fund_grid){
Integer edit_id=(Integer.parseInt((String) row.get("fund_id")));
if(id.equals(edit_id)){
sector=(String) row.get("fund_sector_label");
mfp.setFund_id(Integer.parseInt( (String) row.get("fund_id")));
fund.setFund_id( (String) row.get("fund_id"));
setValidity_date(request_invoker.select_validity_date());
try {
Date ndate=sdf.parse((String) getValidity_date().get(0).get("validitydate"));
// Date is here retireved from database value 15-11-2013
//now incrementing for a day
Calendar c = Calendar.getInstance();
c.setTime(ndate);
c.add(Calendar.DATE, 1);
fund.setNav_entry_date(c.getTime());
//here is where i am stuck i dont know how to check whether date is of saturday or not
if(fund.getNav_entry_date().equals(Calendar.SATURDAY))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("opendialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closedialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}
any help much appreciated
Made changes to the bean and it works calendar c has the date from database and d has the curret date.
Calendar c = Calendar.getInstance();
c.setTime(ndate);
Calendar d=Calendar.getInstance();
if(d.get(Calendar.DATE)==(c.get(Calendar.DATE)))
{
//message here
FacesMessage msg = new FacesMessage("NAV Upto Date" , "NAV Upto Date");
FacesContext.getCurrentInstance().addMessage(null, msg);
break;
}
else
{
c.add(Calendar.DATE, 1);
int day=c.SATURDAY;
int week=c.get(Calendar.DAY_OF_WEEK);
if(day==(week))
{
c.add(Calendar.DATE, 2);
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
else
{
fund.setNav_entry_date(c.getTime());
mfp.getDc().setValiditydate(c.getTime());
}
RequestContext context2 = RequestContext.getCurrentInstance();
if(sector.equals("open-end")){
context2.execute("openenddialog.show();");
}
else if(sector.equals("close-end")){
context2.execute("closeenddialog.show();");
}
else if(sector.equals("pension")){
context2.execute("pensiondialog.show();");
}
}
I had created a datagridview like this
public void gridviewsetup()
{
tbl_Aplication.Columns.Add("1", "Empid");
tbl_Aplication.Columns.Add("2", "Emp no");
tbl_Aplication.Columns.Add("3", "Emp Name");
tbl_Aplication.Columns.Add("4", "Department ");
tbl_Aplication.Columns.Add("5", "Designation");
tbl_Aplication.Columns.Add("6", "Shift");
tbl_Aplication.Columns.Add("7", "Start Time");
tbl_Aplication.Columns.Add("8", "End Time");
tbl_Aplication.Columns.Add("9", "OT");
tbl_Aplication.Columns.Add("10", "Reversed Swipe Out");
tbl_Aplication.RowTemplate.Height = 18;
}
and i had populated a data table to fill the data dgridview
public void filldatagrid()
{
if (cmb_dept.Text.Trim() != "")
{
Datatable employedata = empreg.getallemployeeshiftdetails(int.Parse(cmb_dept.SelectedValue.ToString()), Program.LOCTNPK);
tbl_Aplication.Rows.Clear();
tbl_Aplication.DataSource = null;
for (int i = 0; i < employedata.Rows.Count; i++)
{
tbl_Aplication.Rows.Add();
tbl_Aplication.Rows[i].Cells[1].Value = employedata.Rows[i][0];
tbl_Aplication.Rows[i].Cells[2].Value = employedata.Rows[i][1];
tbl_Aplication.Rows[i].Cells[3].Value = employedata.Rows[i][2];
tbl_Aplication.Rows[i].Cells[4].Value = employedata.Rows[i][3];
tbl_Aplication.Rows[i].Cells[5].Value = employedata.Rows[i][4];
tbl_Aplication.Rows[i].Cells[6].Value = employedata.Rows[i][5];
tbl_Aplication.Rows[i].Cells[7].Value = employedata.Rows[i][6];
tbl_Aplication.Rows[i].Cells[8].Value = employedata.Rows[i][7];
tbl_Aplication.Rows[i].Cells[9].Value = 0;
tbl_Aplication.Rows[i].Cells[10].Value = employedata.Rows[i][7];
}
}
}
now i want to filter data in the datagrid with the designation selected in the combobox without going back to database ,I did it like this but it shows error
private void cmb_designation_SelectedIndexChanged(object sender, EventArgs e)
{
if (desgflag != 0)
{
if (cmb_dept.SelectedValue!=null )
{
// tbl_Aplication.DataSource = employedata;
((DataTable)tbl_Aplication.DataSource).DefaultView.RowFilter = " designationnName like '%" + cmb_dept.Text.Trim() + "%' ";
}
}
}
I had done it
private void cmb_department_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
if (cmb_department.Text.Trim() == "" || cmb_department.Text.Trim() == null)
{
tbl_DestinationData.DataSource = dt;
}
else
{
((DataTable)tbl_DestinationData.DataSource).DefaultView.RowFilter = " Dept like '%" + cmb_department.Text.Trim() + "%' ";
}
}
catch (Exception )
{
throw;
}
}