I created a small app to test out the GPS features of codenameone, but found that it never give an Available status, only Temporarily Unavailable.
For my little test app, the relevant code is the following:
private void doRetrieveLocationAction() {
try {
Location location = LocationManager.getLocationManager().getCurrentLocation();
taLocationDisplay.setText(getGPSDetails() + "\n : " + location.toString());
} catch (Exception e) {
e.printStackTrace();
taLocationDisplay.setText("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage());
ToastBar.showErrorMessage("Error retrieving location:"
+ "\n"
+ getGPSDetails()
+ "\n " + e.getMessage(), 5000);
}
}
private String getGPSDetails() {
StringBuilder sb = new StringBuilder();
sb.append("isEnabled: ").append(LocationManager.getLocationManager().isGPSEnabled());
sb.append("\nisGPSDetectionSupported: ").append(LocationManager.getLocationManager().isGPSDetectionSupported());
sb.append("\ngetStatus: ").append(LocationManager.getLocationManager().getStatus());
return sb.toString();
}
The status being Integer, is assigned the following values in the codenameone source code:
public static final int AVAILABLE = 0;
public static final int OUT_OF_SERVICE = 1;
public static final int TEMPORARILY_UNAVAILABLE = 2;
What I get when the GPS is off:
What I get Immediately after the GPS is turned on:
What I get after I waited a bit:
These results show that the Status never changes. When is the status supposed to change and how am I supposed to use that status? How do I know when the GPS can function or not?
This is being tested on Android
The GPS will be off by default unless you explicitly try to get "real" location by binding a listener to location events. So what you normally get is hybrid location and not GPS location.
Related
This exception indicates on the line of the code
CodeDomProvider = cpp.CreateCompiler();
And he says
The method or operation is not implemented
enter image description here
my code is
CppCodeProvider cpp = new CppCodeProvider();
CodeDomProvider.IsDefinedLanguage("Cpp");
CodeDomProvider.CreateProvider("cpp");
ICodeCompiler IC = cpp.CreateCompiler();
string Output = "Out.exe";
Button ButtonObject = (Button)sender;
textBox2.Text = "";
CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = Output;
CompilerResults results = IC.CompileAssemblyFromSource(parameters, textBox1.Text);
if (results.Errors.Count > 0)
{
foreach (CompilerError CompErr in results.Errors)
{
textBox2.Text = textBox2.Text +
"Line number " + CompErr.Line +
", Error Number: " + CompErr.ErrorNumber +
", '" + CompErr.ErrorText + ";" +
Environment.NewLine + Environment.NewLine;
}
}
else
{
//Successful Compile
textBox2.ForeColor = Color.Blue;
textBox2.Text = "Success!";
//If we clicked run then launch our EXE
if (ButtonObject.Text == "Run") Process.Start(Output);
}
In short, as I said in the comment, a Method or Operation Not Implemented exception normally occurs when you have a method that's been added, but no implementation has been placed in the method. This normally occurs when you generate a method using IntelliSense, and is the compilers way of telling you "Hey, you need to put something in here".
public void MyMethod()
{
throw new NotImplementedException();
}
Adding an implementation to the method or even commenting the throwing of the exception would resolve the issue here.
public void MyMethod()
{
//throw new NotImplementedException();
}
Having said that I know that the method throwing the issue isn't your code, that was more so you understand WHAT the error is telling you.
I think the way you're trying to do what you're doing may not be correct. After doing some research and looking at the MS Learn Page you'll notice that this is Obsolete and has been since .net Framework 2.0.
See a similar thread on SO about this topic: How to compile C++ Code using CppCodeProvider in C#
In my app, I create a file with a comma-separated array by writing to an OutputStream. Then I want to be able to share this by e-mail so a user can get the data. This is the code I use to create the file:
public String getLogFile(String logName) {
String path = FileSystemStorage.getInstance().getAppHomePath() + "exp " + logName + ".csv";
Set<Long> keys;
OutputStream os = null;
try {
os = FileSystemStorage.getInstance().openOutputStream(path);
Hashtable<Long, Integer> log = (Hashtable<Long, Integer>) dataStorage
.readObject(logName);
keys = log.keySet();
for (Long key : keys) {
String outString = (key + "," + log.get(key) + "\n");
System.out.println(outString);
byte[] buffer = outString.getBytes();
os.write(buffer);
}
} catch (IOException e) {
AnalyticsService.sendCrashReport(e, "Error writing log", false);
e.printStackTrace();
} finally {
try {
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return path;
}
Then, I've created a button that when pressed passes the path of the file to share. I've tried to use MIME types such as "text/plain" and "text/comma-separated-values", but that causes errors. Here is the code executed when the button is pressed.
public void exportLog(String logName) {
String path = dataBuffer.getLogFile(logName);
EmailShare email = new EmailShare();
// email.share("Here is your log.", path, "text/plain");
email.share("Here is your log.", path, "text/comma-separated-values");
}
When pressed (in the simulator). I get this stack after selecting the dummy e-mail contact to send to:
java.lang.NullPointerException
at com.codename1.impl.javase.JavaSEPort.scale(JavaSEPort.java:3483)
at com.codename1.ui.Image.scale(Image.java:963)
at com.codename1.ui.Image.scaledImpl(Image.java:933)
at com.codename1.ui.Image.scaled(Image.java:898)
at com.codename1.impl.javase.JavaSEPort$60.save(JavaSEPort.java:6693)
at com.codename1.share.ShareForm.<init>(ShareForm.java:75)
at com.codename1.share.EmailShare$1$2$1.actionPerformed(EmailShare.java:102)
at com.codename1.ui.util.EventDispatcher.fireActionSync(EventDispatcher.java:455)
at com.codename1.ui.util.EventDispatcher.fireActionEvent(EventDispatcher.java:358)
at com.codename1.ui.List.fireActionEvent(List.java:1532)
at com.codename1.ui.List.pointerReleasedImpl(List.java:2011)
at com.codename1.ui.List.pointerReleased(List.java:2021)
at com.codename1.ui.Form.pointerReleased(Form.java:2560)
at com.codename1.ui.Component.pointerReleased(Component.java:3108)
at com.codename1.ui.Display.handleEvent(Display.java:2017)
at com.codename1.ui.Display.edtLoopImpl(Display.java:1065)
at com.codename1.ui.Display.mainEDTLoop(Display.java:994)
at com.codename1.ui.RunnableWrapper.run(RunnableWrapper.java:120)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
The EmailShare class expects a path to an image file not an arbitrary file as its second argument so loading that fails.
The Message class is better suited for that indeed. You can also use the cloud send option which won't launch the native email app. E.g. the Log class includes that ability directly thru the Log.sendLog API.
It looks like the Messages class is better suited for this task, and should allow attachments, etc.
com.google.apphosting.api.ApiProxy$RequestTooLargeException: The request to API call datastore_v3.Put() was too large.
public static List<Area> readAreas(URL url) {
List<Area> areas = new ArrayList<Area>();
try {
BufferedReader br = new BufferedReader(new FileReader(new File(url.toURI())));
String row;
while ((row = br.readLine()) != null) {
if (row.contains(SEARCHED_ROW)) {
//get the part after "c"
String coord[] = (row.split("c"));
String startCoordM = ((coord[0].trim()).split(" "))[1];
String curvesCoord= coord[1];
Area area = new Area();
area.mPoint= Point.toStartPoint(Point.readPoints(startCoordM));
area.curves = Curve.readCurves (curvesCoord);
areas.add(area);
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return areas;
}
This method runs without any errors but when I log out and log in to the same page of my web application this method runs again and again without problem but then this exception is thrown. I'm using google app engine 1.8.1 with jsf2 and primefaces 3.5. This method is invoked from managed bean :
public MapMB () {
eps = EPDAO.getEPList();
populateAdvancedModel(eps);
drawPolilines();
}
void drawPolilines() {
List<Area> areas = Area.readAreas(getFacesContext().getClass().getResource("/map-inksc.svg") );
for (Area area : areas) {
List<Curve> curves = area.getCurves();
Point endPoint = area.getmPoint();
Polyline polyline = new Polyline();
polyline.setStrokeWeight(1);
polyline.setStrokeColor("#FF0000");
polyline.setStrokeOpacity(1);
for (Curve curve : curves) {
polyline.getPaths().add( new LatLng(endPoint.getY(),endPoint.getX()) );
// curve start point is the end point of previous curve (endPoint.getX(),endPoint.getY() )
double step = 0.01;
for (double t=0;t<= 1;t=t+step) {
double x = getCoordFromCurve(endPoint.getX(), endPoint.getX() + curve.getP1().getX(),endPoint.getX() + curve.getP2().getX(),endPoint.getX() + curve.getP3().getX(), t);
double y = getCoordFromCurve(endPoint.getY(), endPoint.getY() + curve.getP1().getY(),endPoint.getY() + curve.getP2().getY(),endPoint.getY() + curve.getP3().getY(), t);
polyline.getPaths().add( new LatLng(y, x) );
}
endPoint = new Point (endPoint.getX() + curve.getP3().getX(), endPoint.getY() + curve.getP3().getY());
}
advancedModel.addOverlay(polyline);
polyline = new Polyline();
}
}
When I don't read any data (don't use readAreas() above) then everything works fine. So how reading from file is connected to this error? I don't understand.
If there is some information that I didn't put here please just say. All these methods run without errors and then this exception is thrown
See the edit
Ok. So ... somehow the problem is solved. How? I'm not sure. So I had:
a.xhtml < include b.xhtml
c.xhtml < include b.xhtml
a.xhtml and c.xhtml had the same method bFilterMethod()
JSF beans:
a, b, c all ViewScoped
b had a and c as Managed Properties
a.xhtml and c.xhtml have bFilterMethod() that getsSome() data from the database and sets aProperty and cProperty(which are the same). I saw in google app engine logs that the method getsSome() runs about 20 times like infinite loop after that the exception was thrown.
Now all beans are request scoped
a.xhtml has aFilterMethod that getsSome() data
b.xhtml has bFilterMethod that getsSome() data
and a and b has c as Managed Property
Hope this helps someone but as I sad I'm not sure what is the exact error but obviously is caused by too big request from the database no matter this request contains only 3 rows (this request is invoked too many times)
EDIT
After so many years I came back to my topic accidentally. The real reason for all this is that GAE saves the session in the datastore and jsf ViewScoped beans are not removed from the session as in normal java application server. So the solution is just don't use ViewScoped beans
Javamail Auto-reply
I would truly like to auto-reply to an email using Javamail.
I already use my domain email to send a confirmation code during registration.
What I need now is when an email is sent to choices#mydomain.com I can auto-reply with a canned email based on parsing out and reading the received email. It would be nice to include the username in the reply.
Thank you for your help!
This simplest approach is to write a program that monitors your mailbox and creates and sends a reply based on every message it sees. The JavaMail download bundle includes a sample program monitor.java that will get you started. The MimeMessage.reply method will be helpful. You'll have to fill in the content of the reply message yourself. Various other JavaMail sample programs will show you how to send a message once you've created it.
And don't forget to read the JavaMail FAQ.
Nice thinking John,I had the same problem in my project, in JSP and I solved it as shown below with java class as ReadingMail
package com;import java.io.*;import java.util.*;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
public class ReadingMail {
public static void main(String args[]) throws Exception {
try{
String host = "pop.gmail.com";
String user="username";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
System.out.println("SentDate : " + message[i].getSentDate());
System.out.println("From : " + message[i].getFrom()[0]);
System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
public String Manu()
{
String email=null;
try{
String host = "pop.gmail.com";
// String user = "xyz";
// String password = "12345";
String user="username#gmail.com";
String password="password";
// Get system properties
Properties properties = System.getProperties();
// Get the default Session object.
Session session = Session.getDefaultInstance(properties, null);
// Get a Store object that implements the specified protocol.
Store store = session.getStore("pop3s");
//Connect to the current host using the specified username and password.
store.connect(host, user, password);
//Create a Folder object corresponding to the given name.
Folder folder = store.getFolder("inbox");
// Open the Folder.
folder.open(Folder.READ_ONLY);
Message[] message = folder.getMessages();
// Display message.
for (int i = 0; i < message.length; i++) {
System.out.println("------------ Message " + (i + 1) + " ------------");
// System.out.println("SentDate : " + message[i].getSentDate());
//System.out.println("From : " + message[i].getFrom()[0]);
email=message[i].getFrom()[0]==null?null:((InternetAddress) message[i].getFrom()[0]).getAddress();
System.out.println("From addrss is..........................."+email);
// System.out.println("Subject : " + message[i].getSubject());
System.out.print("Message : ");
InputStream stream = message[i].getInputStream();
while (stream.available() != 0) {
System.out.print((char) stream.read());
}
System.out.println();
}
folder.close(true);
store.close();
}
catch(Exception e)
{
System.out.println(e);
}
return email;
}
You can fetch the username from the database and provide it as message in this program.
I have an application that downloads a video file that is roughly 6mb
I am trying to run this application on a Blackberry Curve 9360, which has 32mb of "media" storage
Sometimes this application runs and is able to download the video with no problems, however other times part way thru downloading the download process fails with an IO exception that states: "There is not enough free memory on the file system to complete this action"
after it fails in this manner I can open up the BlackBerry Desktop software and check the files section and see that the device is indeed reporting that 32/32 mb are full.
If I then restart the device with alt-shift-del and open up blackberry desktop software again the used space has shrunk back down to only 5-6 / 32mb full
Sometimes at this point I am able to run my application now and have it succeed the download, but other times it again gives me the same storage full error. The only thing I can notice that seems like it might be affecting whether or not it fails is how long the download takes total (i.e. it succeeds on wifi, and on good 3g signal and fails on poorer 3g signal, but this is anecdotal at best)
I have used this exact same application on a few different blackberry devices, including a few other Curve devices with the same storage size, and never run into this problem before.
My question is: Has anyone seen a BlackBerry curve device behave in such a way that it will report an incorrect storage space that gets fixed by a reboot?
And is there anything about this download code that could be causing this behavior?
class DownloadThread extends Thread {
public void run()
{
HttpConnection httpConn = null;
InputStream is = null;
try{
httpConn = (HttpConnection)Connector.open(videoUrl + ";interface=wifi");
is = httpConn.openInputStream();
}catch(IOException e){
try{
httpConn = (HttpConnection)Connector.open(videoUrl);
is = httpConn.openInputStream();
}catch(IOException ioe){
System.out.println("891: "+e.toString());
}
}
try{
if (!videoFconn.exists())
videoFconn.create();
else{
videoFconn.delete();
videoFconn.create();
}
OutputStream os = videoFconn.openOutputStream();
lengthOfWebFile = httpConn.getLength();
total = 0;
System.out.println("##################### length of web file = " + lengthOfWebFile + " #################");
byte data[] = new byte[256];
while ((count = is.read(data)) != -1) {
total += count;
progress = (int)(total*100/lengthOfWebFile);
if(model.getValue() < progress){
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
EmbeddedMediaScreen.this.model.setValue(progress);
}
});
}
//write this chunk
os.write(data, 0, count);
Thread.yield();
}
os.flush();
os.close();
is.close();
httpConn.close();
lengthOfLocalFile = videoFconn.fileSize();
System.out.println("###################### Local Length = " + lengthOfLocalFile + "#####################");
if(lengthOfLocalFile == lengthOfWebFile){
amDownloading = false;
startVideo();
}else{
downloadVideo();
}
}catch(FileNotFoundException fnf){
}catch(IOException e){
//ScreenSaverActivity.errorDialog("975: "+e.toString());
System.out.println("980: "+e.toString());
//e.printStackTrace();
}catch(NullPointerException npe){
System.out.println("983: "+npe.toString());
} /*catch (InterruptedException e) {
// TODO Auto-generated catch block
System.out.println(e.getMessage());
}*/
}
public synchronized void postProgress(final int p){
UiApplication.getUiApplication().invokeLater(new Runnable()
{
public void run()
{
//Set the progress bar
EmbeddedMediaScreen.this.model.setValue(p);
}
});
}
}