Hi Guys First of all I must say thanks to all of you guys for helping me :). I was a silent member before this query and benefited a lot from other members question.
But now I'm stuck in my code. See I'm developing a software that will help EVENT MANAGEMENT. I have done all that basics of creating and saving events in the database - i'm using sqlite db.
I'm stuck for code of pop-up and alarm when event time is started.
I saved date as String in db which is in this format "26-04-2015".
I saved time as String in db which is in this format "17:00:00".
What I've tried uptil now is this - I was comparing current time with that on db but failed to make it work)
Any suggestion or help will be highly appreciated.
private void checkAlarm() {
new Thread() {
Calendar cal = new GregorianCalendar();
int hour = cal.get(Calendar.HOUR);
int min = cal.get(Calendar.MINUTE);
int sec = cal.get(Calendar.SECOND);
String time = hour + ":" + min + ":" + sec;
String[] data = connect.readData1("Select e_sdate, e_stime,e_title from tbl_event order by e_sdate ASC limit 1", "e_stime", "e_title");
String sTime = data[0];
String title = data[1];
public void run() {
while (true) {
try {
Thread.sleep(1000);
System.out.println("time from db : " + sTime);
System.out.println("time current : " + time);
} catch (Exception e) {
}
if (time.equals("sTime")) {
try {
TrayIcon icon = new TrayIcon(getIconImage(), "Event Management System", createPopupMenu());
playSound();
icon.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, "This event has been started now.");
}
});
SystemTray.getSystemTray().add(icon);
Thread.sleep(3000);
icon.displayMessage("Event : " +title, "Event Time : " +sTime, TrayIcon.MessageType.INFO);
} catch (Exception e) {
System.out.println("Tray Icon Error : " +e);
}
}
}
}
}.start();
}
Related
My hashmap has String type as key and ArrayList type as value, example {"v1"=[1.1,1.2,1.3], "v2"=[2.1,2.2,2.3,2.4]} where "v1" and "v2" are keys. There are more than 40 keys (previously unknown size) and each key has a ArrayList which may not be uniform in size (size >200).
I want to write this hashmap data in the following format in a .csv file in my Android phone.
v1 v2
1.1 2.1
1.2 2.2
1.3 2.3
Until now, my Hashmap had fixed key/array size and I used the following code snippet to dump the data:
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
File folder = new File(Environment.getExternalStorageDirectory() + "/santobedi" + hour + "-" + minute + "-" + second);
String csv = folder.getAbsolutePath() + "/data.csv";
try {
file_writer = new FileWriter(csv, true);
if (isReady == false) {
String s = "v1, v2,\n";
file_writer.append(s);
isReady = true; // The columns heads are set
}
} catch (IOException e) {
e.printStackTrace();
}
Later, I'd append (row-wise) the values on a loop checking the Boolean value isReady. Now, the size of the key is not fixed, so I cannot set the column heads as before. I searched for a possible solution, this question is almost similar to my situation. However, it is not related to memory location inside the Android phone and the accepted answer is still not solving my problem.
Any help, please!
I solved my problem with the following approach:
public FileWriter file_writer;
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
File folder = new File(Environment.getExternalStorageDirectory() + "/Santobedi" + hour + "-" + minute + "-" + second);
folder.mkdir();
String csv = folder.getAbsolutePath() + "/data.csv";
try { file_writer = new FileWriter(csv, true);
} catch (IOException e) {
e.printStackTrace();
}
Later, a writeToCSV method is used to append data in the file_writer as follows:
public void writeToCsv() throws IOException {
for(Map.Entry<String , ArrayList<Float>>IwantItasColumn:myHashMap.entrySet())
{
String s = "";
for(int i =0; i<IwantItasColumn.getValue().size();i++)
{
s = s+ ","+ String.valueOf(IwantItasColumn.getValue().get(i));
}
s = AccessPointId.getKey() + "," + s + "\n";
file_writer.append(s);
}
try {
file_writer.close();
} catch (IOException e) {
e.printStackTrace();
}}
The above code snippet appends the data row-wise in the data.csv file (disregard to the size of the hashmap, size of keys, size of ArrayList). For example:
v1 1.1 1.2 1.3
v2 2.1 2.2 2.3
A simple row to column transformation in Excel gives me the required result.
i try with this, but it is some times not working correctly..i used a while loop for loop the code. can i add some listner for this? any one can give me the correct answer for this? in need to get responce real time
while (true) {
msgList = new ArrayList<InboundMessage>();
Service.getInstance().readMessages(msgList, InboundMessage.MessageClasses.ALL);
for (InboundMessage im : msgList) {
if (last < im.getMemIndex()) {
ResultSet rs = DB.getConnection().createStatement().executeQuery("Select * From codes where code='" + im.getText() + "'");
if (rs.next()) {
ResultSet rs2 = DB.getConnection().createStatement().executeQuery("Select * From sms_log where code='" + im.getText() + "' AND tel_no='" + im.getOriginator() + "'");
if (rs2.next()) {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code is Already Sent... Thank You!.");
System.out.println("The Code is Already Sent... Thank You!.");
} else {
System.out.println("The Code Verified... Thank You!.");
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "The Code Verified... Thank You!.");
DB.getConnection().createStatement().execute("INSERT INTO sms_log (tel_no,code,status) values('" + im.getOriginator() + "','" + im.getText() + "',1)");
}
} else {
if (m == null) {
m = new SMSClient(1);
}
m.sendMessage(im.getOriginator(), "Invalid Code... Thank You!.");
System.out.println("Invalid Code... Thank You!.");
}
}
}
Thread.sleep(10000);
System.out.println("start");
}
I think IInboundMessageNotification is the interface you are looking for
public class InboundNotification implements IInboundMessageNotification {
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
//add you logic for received messages here
}
}
Add notification class to smsLib service
Service.getInstance().setInboundMessageNotification(new InboundNotification())
From now on, process() method will be called every time your modem receives a message.
As far as I remember, smslib (version 3.5.x) does not delete received messages so it needs to be done manually
#Override
public void process(AGateway aGateway, Message.MessageTypes messageTypes, InboundMessage inboundMessage) {
try {
aGateway.deleteMessage(inboundMessage);
} catch (TimeoutException | GatewayException | InterruptedException | IOException e) {
e.printStackTrace();
}
// your logic here
}
otherwise you will keep receiving not deleted messages every time you receive a new one.
Hope you will find this useful.
I'm not sure how the start and end date work with the whole find appointments. I am getting all the rooms for a public group, then getting the rooms for the group, then getting the appointments within a date range.
But the ranges act weird, I know there are appointments on 12-19 to 12-16, but if I set the start date range to 2013-10-10 and the end date to 2013-12-28, I get nothing.
If I set the end date to 2014-01-28, I get tons of stuff that is in the range previously mentioned. Why is that?
ExchangeService service = new ExchangeService();
ExchangeCredentials credentials = new WebCredentials( "username", "pw");
service.setCredentials( credentials );
service.setUrl( new URI("my mail url") );
Folder inbox = Folder.bind(service, WellKnownFolderName.Inbox);
System.out.println("messages: " + inbox.getTotalCount());
CalendarFolder cf = CalendarFolder.bind(service, WellKnownFolderName.Calendar);
//Get all new appts?
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("YYYY-mm-dd");
Date startDate1 = formatter.parse("2013-11-25");
Date endDate1 = formatter.parse("2014-01-28 ");
EmailAddressCollection myRoomLists = service.getRoomLists();
for (EmailAddress item : myRoomLists)
{
System.out.println("Room Email========"+ item.toString());
NameResolutionCollection nameResolutions = service.resolveName(
item.getName(),
ResolveNameSearchLocation.DirectoryOnly,
true);
for (NameResolution nameResolution : nameResolutions)
{
ExpandGroupResults groupResults;
//System.out.println(nameResolution.getMailbox().getAddress());
try {
groupResults = service.expandGroup(nameResolution.getMailbox().getAddress());
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
groupResults=null;
System.out.println("NO INFO FOR "+nameResolution.getMailbox().getAddress());
}
if (groupResults!=null){
for (EmailAddress member : groupResults.getMembers())
{
if (member.getAddress().indexOf("rm.Cary")>-1){
System.out.println(member.getName() + " <" + member.getAddress() + ">");
FolderId folderid = new FolderId(WellKnownFolderName.Calendar, new Mailbox(member.getAddress()));
try {
FindItemsResults<Appointment> aps = service.findAppointments(folderid, new CalendarView(startDate1,endDate1));
for (Item items : aps.getItems())
{
Appointment appt = (Appointment)items;
System.out.println("SUBJECT===== " + appt.getSubject());
System.out.println("Location======== " + appt.getLocation());
System.out.println("Start Time========" + appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Email Address========"+ appt.getOrganizer().getAddress());
System.out.println("Last Modified Time========"+appt.getLastModifiedTime());
System.out.println("Start time========"+appt.getStart());
System.out.println("End Time========"+appt.getEnd());
System.out.println("Is recurring========"+appt.getIsRecurring());
System.out.println("Duration========"+appt.getDuration().toString());
System.out.println("Organizer========"+appt.getOrganizer());
System.out.println("Required Attendees========"+appt.getRequiredAttendees().getCount());
System.out.println("Optional Attendees========"+appt.getOptionalAttendees().getCount());
System.out.println("");
}
} catch (microsoft.exchange.webservices.data.ServiceResponseException e){
System.out.println(e.getMessage());
}
}
}
}
}
}
System.out.println("End");
Change it to:
java.text.SimpleDateFormat formatter= new java.text.SimpleDateFormat("yyyy-MM-dd");
I am making a ping program using Java sockets. One bug in my program is that sometimes it will not connect and will just sit there for ever. So I am trying to add a timeout (after twenty seconds) and the ping will fail. But I have no idea how to.
Here is part of my ping program:
boolean result = false;
long before1 = System.nanoTime();
out.println(new byte[64]);
System.out.println("(1) Sent 64 bytes of data to " + address
+ "...");
try {
if ((in.readLine()) != null) {
int size = in.readLine().toString().getBytes().length;
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Recieved reply from " + address
+ " (" + size + " bytes), time = " + s
+ " seconds...");
result = true;
} else if ((in.readLine()) == null) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.out.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...");
result = false;
}
} catch (IOException exc) {
long after = System.nanoTime();
long s = ((after - before1) / 1000000L) / 1000;
System.err.println("(1) Failed to recieve reply from "
+ address + ", time = " + s + " seconds...\nReason: "
+ exc);
result = false;
}
But I would like to measure time elapsed any where in my code, instead of:
long time = System.nanoTime();
If one part of my code is stuck doing something it will time out after 20 seconds.
Any suggestions on how to measure if twenty seconds has passed at the start of a try/catch block or anywhere else in my code so it doesn't get stuck during the ping?
As "jsn" and "jahory" said you need to do this with threads. Here's 2 useful links, you can check them ;)
How to implement timeout using threads
Adding a thread timeout to methods in Java
You can use Future and FutureTask:
ExecutorService pingExecutor = ... // executor service to run the ping in other thread
void showPing(final String target) throws InterruptedException {
Future<String> ping = executor.submit(new Callable<String>() {
public String call() {
String pingResult = ... // do your Ping stuff
return pingResult;
}});
System.out.println("Pinging..."); // do other things while searching
try {
System.out.println(future.get(20, TimeUnit.SECONDS)); // use future, waits 20 seconds for the task to complete
} catch (ExecutionException ex) {
} catch (TimeoutException tex) {
// Ping timed out
}
}
You can find some hints here: How do I call some blocking method with a timeout in Java?
Future interface looks like a good solution to your problem. Remember, however, that depending on what your task is doing, you probably would be not able to really cancel it. Additional info:
tutorial (see, in particular, Non-blocking algorithms section)
Sorry for my bad english.
I'm implementing Java TimerTask when creating an Android application. The code isn't to complicated. When it hit the interval, it will send an SMS & email.
I have some option with the sending SMS / email interval. 5 minutes, 15 minutes, 30 minutes, 1 hour, and 2 hour.
I tried using 5 minutes, and 15 minutes (I converted it into milis), no trouble occurred. It send sms and email every 5 / 15 minutes exactly. And I prove that i have no problem using timertask.
But, when I changed it to 30 minutes or more. my application cannot send sms / email. It looked like that the timer didn't work correctly.
Does it have any interval limitation on using Timer Task ??
this is my code snippet.
private void activateNotificationByInterval(int notificationInterval) {
timerNotificationByInterval = new Timer();
timerNotificationByInterval.schedule(new TimerTask() {
#Override
public void run() {
// TODO Auto-generated method stub
// coba
// if (oldLatitude != childLatitude
// && oldLongitude != childLongitude) {
if ((enableSMS == true)) {
sendSMS();
}
if ((enableEmail == true)) {
GMailSender email = new GMailSender(sender, senderPassword);
try {
email.sendMail(emailSubject + childsName, SMSMessage
+ " " + childlLocation + "\nLatitude: "
+ childLatitude + "\nLongitude: "
+ childLongitude, sender, destination);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
mpv.changeLastLocation(childLatitude, childLongitude);
// buat method untuk menangkap lokasi pertama
oldLatitude = childLatitude;
oldLongitude = childLongitude;
// } else {
// System.out.println("Lokasi Lama Berpengaruh");
// }
}
}, 0, notificationInterval);
}
*notes : notificationInterval on milis (*60000)
can you tell me how to solved it ? thank you.
Use AlarmManager and there is a link here:
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html