How to access files in FileSystemStorage in Browser component - codenameone

I am trying to display a pdf saved in FileSystemStorage inside the browsercomponent, but it keeping giving me this error on the console: [0813/072549.347989:INFO:CONSOLE(37)] "Not allowed to load local resource: file://home//Chapter_11.pdf#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0&view=FitH", source: https://cn1app/streams/1 (37) [0813/072551.123557:INFO:CONSOLE(0)] "Not allowed to load local resource: file://home//Chapter_11.pdf#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0&view=FitH", source: https://cn1app/streams/1 (0) . Its like there is a restriction that I need to work around. How can I go around this?
Edits... Added information below.
This is the code I am using:
Form hi;
Container loadingMsg;
public void Home(){
Form form = new Form("Display pdf", new BorderLayout());
Button showPdf = new Button("Show Pdf");
showPdf.addActionListener(l->{
show();
});
form.add(BorderLayout.CENTER, showPdf);
form.show();
}
private void show(){
hi = new Form("PDF Viewer", new BorderLayout());
Label loadingLabel = new Label("Loading PDF...");
loadingMsg = FlowLayout.encloseCenter(loadingLabel);
hi.add(BorderLayout.NORTH, loadingMsg);
String pdfUrl = "https://as.vanderbilt.edu/chemistry/Rizzo/chem220a/Chapter_11.pdf";
String fileName = FileSystemStorage.getInstance().getAppHomePath() + "Chapter_11";
if (!FileSystemStorage.getInstance().exists(fileName)) {
Util.downloadUrlToFileSystemInBackground(pdfUrl, fileName);
};
hi.addShowListener(l -> {
run1(fileName);
});
hi.show();
}
private void run1(String fileName) {
BrowserComponent browser = new BrowserComponent();
browser.setPage(getPdfViewerHtml(fileName), null);
hi.add(BorderLayout.CENTER, browser);
loadingMsg.remove();
hi.revalidate();
}
private String getPdfViewerHtml(String fileName) {
String html = "<!DOCTYPE html>\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>PDF Viewer</title>\n"
+ " <style>\n"
+ " html{\n"
+ " height: 100%;\n"
+ " padding: 0;\n"
+ " }\n"
+ " body{\n"
+ " height: 100%;\n"
+ " overflow-y: hidden;\n"
+ " position: fixed;\n"
+ " width: 100%;\n"
+ " padding: 0;\n"
+ " margin: 0;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ "\n"
+ " <div style= \"height: 100%; margin: 0;\">\n"
+ " <iframe\n"
+ " src='"+fileName+"#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0&view=FitH'\n"
+ " width=\"100%\"\n"
+ " height=\"100%\"\n"
+ " >\n"
+ " <p>This browser does not support PDF!</p>\n"
+ " </iframe>\n"
+ "\n"
+ " </div>\n"
+ "\n"
+ " </body>\n"
+ "</html>";
return html;
}
So in the method String getPdfViewerHtml(String fileName),when i replace the fileName with a URL, thing works fine. But I want it to display a file from FileSystemStorage.

The code below should support the local embed tag correctly:
private Container loadingMsg;
public void start() {
if (current != null) {
current.show();
return;
}
home();
}
public void home() {
Form form = new Form("Display pdf", new BorderLayout());
Button showPdf = new Button("Show Pdf");
showPdf.addActionListener(l -> {
showPdf.setText("Dowloading PDF...");
showPdf.setEnabled(false);
form.revalidate();
show();
});
form.add(BorderLayout.CENTER, showPdf);
form.show();
}
private void show() {
String root = getAppHomePath() + "httpdocs/";
mkdir(root);
hi = new Form("PDF Viewer", new BorderLayout());
Label loadingLabel = new Label("Loading PDF...");
loadingMsg = FlowLayout.encloseCenter(loadingLabel);
hi.add(BorderLayout.NORTH, loadingMsg);
String pdfUrl = "https://as.vanderbilt.edu/chemistry/Rizzo/chem220a/Chapter_11.pdf";
String fileName = root + "/Chapter_11.pdf";
if (!FileSystemStorage.getInstance().exists(fileName)) {
Util.downloadUrlToFile(pdfUrl, fileName, false);
try {
run1(docRoot, "Chapter_11.pdf");
} catch (IOException ex) {
Log.e(ex);
}
} else {
try {
run1(docRoot, fileName);
} catch (IOException ex) {
Log.e(ex);
}
}
hi.show();
}
private void run1(String docRoot, String fileName) throws IOException {
BrowserComponent browser = new BrowserComponent();
String localUrl = fileName;
String htmlPage = getPdfViewerHtml(localUrl);
File indexHtml = new File(docRoot, "index.html");
writeStringToFile(indexHtml, htmlPage);
browser.setURL(docRoot + "/index.html");
hi.add(BorderLayout.CENTER, browser);
loadingMsg.remove();
hi.revalidate();
}
private String getPdfViewerHtml(String fileName) {
String html = "<!DOCTYPE html>\n"
+ "<html>\n"
+ " <head>\n"
+ " <title>PDF Viewer</title>\n"
+ " <style>\n"
+ " html{\n"
+ " height: 100%;\n"
+ " padding: 0;\n"
+ " }\n"
+ " body{\n"
+ " height: 100%;\n"
+ " overflow-y: hidden;\n"
+ " position: fixed;\n"
+ " width: 100%;\n"
+ " padding: 0;\n"
+ " margin: 0;\n"
+ " }\n"
+ " </style>\n"
+ " </head>\n"
+ " <body>\n"
+ "\n"
+ " <div style= \"height: 100%; margin: 0;\">\n"
+ " <iframe\n"
+ " src='" + fileName + "#toolbar=0&navpanes=0&scrollbar=0&statusbar=0&messages=0&scrollbar=0&view=FitH'\n"
+ " width=\"100%\"\n"
+ " height=\"100%\"\n"
+ " >\n"
+ " <p>This browser does not support PDF!</p>\n"
+ " </iframe>\n"
+ "\n"
+ " </div>\n"
+ "\n"
+ " </body>\n"
+ "</html>";
return html;
}
private void writeStringToFile(File file, String content) throws IOException {
FileSystemStorage fs = FileSystemStorage.getInstance();
try (OutputStream os = fs.openOutputStream(file.getAbsolutePath())) {
Util.copy(new ByteArrayInputStream(content.getBytes("UTF-8")), os);
}
}
}

Related

Sqlite The database file is locked database is locked

I constantly write an error, the database is locked. I just can not understand why this is happening.
db_login.cs
private db_controller _dbctrl = new db_controller();
public SqliteDataReader dataread;
private string query;
//this two inputField,
public void LoginToGo()
{
login = _login.captionText.text;
pass = _pass.text.ToString();
query = "SELECT id from users where users = '" + login + "' AND pass = '" + pass + "'";
try
{
dataread = _dbctrl.ExecuteReader(query);
if(dataread.HasRows & dataread != null)
{
while (dataread.Read())
{
VerifyAdmin();
_dbctrl.Disconnect();
}
}
else
{
errortxt.text = "Неверный логин или пароль, пожалуйста повторите!";
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void VerifyAdmin() //Who are you, admin or user
{
login = _login.captionText.text;
query_access = "SELECT root from users where users = '" + login + "'";
try
{
dataread = _dbctrl.ExecuteReader(query_access);
while (dataread.Read())
{
if(dataread[0].ToString() == "0" || dataread[0].ToString() == null)
{
MainMenu();
}
else
{
AdminMenu();
}
}
}
catch (Exception ex) { errortxt.text = ex.ToString(); }
}
public void AdminMenu()
{
JOIN.SetActive(false);
ADMIN.SetActive(true);
}
public void MainMenu()
{
JOIN.SetActive(false);
MAIN.SetActive(true);
}
db_controller.cs
public SqliteConnection con_db;
public SqliteCommand cmd_db;
public SqliteDataReader rdr_db;
public void connections()
{
try
{
if(Application.platform != RuntimePlatform.Android)
{
path = Application.dataPath + "/StreamingAssets/db.bytes"; // Путь для Windows
}
else
{
path = Application.persistentDataPath + "/db.bytes"; // Путь для Android
if(!File.Exists(path))
{
WWW load = new WWW("jar:file://" + Application.dataPath + "!/assets/" + "db.bytes");
while (!load.isDone) { }
File.WriteAllBytes(path, load.bytes);
}
}
con_db = new SqliteConnection("URI=file:" + path);
con_db.Open();
if (con_db.State == ConnectionState.Open)
{
debugText.text = path.ToString() + " - is connected";
Debug.Log(path.ToString());
}
}
catch (Exception ex)
{
debugText.text = ex.ToString();
}
}
//Тут я создаю метод отключения
public void Disconnect()
{
con_db.Close();
}
public SqliteDataReader ExecuteReader(string query)
{
connections();
try
{
cmd_db = new SqliteCommand(query, con_db);
rdr_db = cmd_db.ExecuteReader();
return rdr_db;
}
catch (Exception ex) { debugText.text = ex.ToString(); return null; }
}
//Тут я записываю данные. Заодно решил проверить закрыто ли соединение.
public void SetDB()
{
if (con_db.State == ConnectionState.Open)
{
Debug.Log("open");
}
else
{
Debug.Log("close!");
}
//The connection is closed. But I can not complete the request cmd_db.ExecuteNonQuery();
connections();
try
{
brand = AutoName.captionText.text;
model = AutoModel.captionText.text;
years = OldAuto.captionText.text;
number = GosNumber.text.ToString();
nusers = UserName.text.ToString();
dbirthday = DBirthday.captionText.text;
mbirthday = MBirthday.captionText.text;
ybirthday = YBirthday.captionText.text;
mobile = Mobile.text.ToString();
cmd_db = new SqliteCommand("INSERT INTO clients(brand,model,years,number,nusers,dbirthday,mbirthday,ybirthday,mobile,groupmodel) values('" + brand + "', '" + model + "','" + years + "','" + number + "','" + nusers + "','" + dbirthday + "','" + mbirthday + "','" + ybirthday + "','" + mobile + "','" +groupmodel+ "')" , con_db);
cmd_db.ExecuteNonQuery(); //Swears, says that the base is locked. And why? I just read the data and the connection was closed.
}
catch (Exception ex) { debugText.text = ex.ToString(); }
Disconnect();
}
the documentation says:
This error code occurs when you try to do two incompatible things with the database at the same time from the same connection to the database.
But the connection with the base is closed.
Maybe I'm missing something, or not doing the right thing. I ask for help to clarify this issue.

Add header and footer to XPS print output

XpsDocument is loaded from disk
Create a FixedDocumentSequence via XpsDocument.GetFixedDocumentSequence Method ()
Display the via a DocumentViewer
Would like to add to add header and footer to print
I don't need to add the header and footer back to the XPS document - only to the print output
I tried implementing DocumentPaginator but cannot get the sizing or placement to work
NOT the same as this footer to FlowDocument
I use the solution there for FlowDocuments just fine
Convert XAML Flow Document to XPS with Style
On the FixedDocumentSequence the sizing comes from document (I guess)
For example could mix landscape and portrait
I cannot figure out how to hook into the sizing and make room for a header and footer
I can stamp a header on it but it is over the top of the page
And landscape pages are cut off
Cannot assign a PageSize when it comes from a FixedDocumentSequence
As stated in the link it is a suggested pages size
DocumentPage.Size is read only
Even if I create DocumentPage of the Size I want when the page is loaded using DocumentPaginator.GetPage then the Size is overwritten
Even worse the DocumentPaginator does not seem to be properly aware of the Size as it does not deal with mixed landscape and portrait properly. Landscape is printed portrait and just runs off the page.
some one asked me to post code
there also might be a just plain better approach
see footer to FlowDocument for how to use it
this is where it breaks
// this gets the page size from GetPage - ignores size above
public class DocumentPaginatorWrapperXPS : DocumentPaginator
{
System.Windows.Size m_PageSize;
System.Windows.Size m_Margin;
DocumentPaginator m_Paginator;
FixedDocumentSequence fixedDocumentSequence;
Typeface m_Typeface;
private string printHeader;
private int? sID;
private string docID;
public DocumentPaginatorWrapperXPS(FixedDocumentSequence FixedDocumentSequence, System.Windows.Size margin, string PrintHeader, int? SID, string DOCID)
{
//m_PageSize = pageSize;
//m_PageSize = new Size(800, 600);
fixedDocumentSequence = FixedDocumentSequence;
m_Margin = margin;
m_Paginator = fixedDocumentSequence.DocumentPaginator;
//m_Paginator.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
// //m_PageSize.Height - margin.Width * 2);
printHeader = PrintHeader;
sID = SID;
docID = DOCID;
}
Rect Move(Rect rect)
{
if (rect.IsEmpty)
{
return rect;
}
else
{
return new Rect(rect.Left + m_Margin.Width, rect.Top + m_Margin.Height,
rect.Width, rect.Height);
}
}
private Size sizeXPS;
public override DocumentPage GetPage(int pageNumber)
{
System.Windows.Documents.DocumentPage page = m_Paginator.GetPage(pageNumber);
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
m_Paginator.PageSize = new System.Windows.Size(page.Size.Width/2 - m_Margin.Width * 2, page.Size.Height/2 - m_Margin.Height * 2);
page = m_Paginator.GetPage(pageNumber); // this get the page size from GetPage - ignores size above
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
DynamicDocumentPaginator paginatorPage = fixedDocumentSequence.DocumentPaginator as DynamicDocumentPaginator;
paginatorPage.PageSize = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
sizeXPS = new System.Windows.Size(page.Size.Width / 2 - m_Margin.Width * 2, page.Size.Height / 2 - m_Margin.Height * 2);
page = paginatorPage.GetPage(pageNumber); // still does not change the page size
Debug.WriteLine(page.Size.Width + " " + page.Size.Height);
//page.PageSize = new System.Windows.Size(m_PageSize.Width - margin.Width * 2,
//m_PageSize.Height - margin.Width * 2);
//page.Size = new System.Windows.Size(page.Size.Width - m_Margin.Width * 2, page.Size.Height - m_Margin.Height * 2);
//page.Size.Width = page.Size.Width - m_Margin.Width * 2;
// Create a wrapper visual for transformation and add extras
ContainerVisual newpage = new ContainerVisual();
DrawingVisual title = new DrawingVisual();
using (DrawingContext ctx = title.RenderOpen())
{
if (m_Typeface == null)
{
m_Typeface = new Typeface("Segoe UI Symbol"); //Ariel
}
//FormattedText text = new FormattedText("Attorney eyes only \uE18B \u1F440 Page " + (pageNumber + 1),
// System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// m_Typeface, 14, System.Windows.Media.Brushes.Black);
string pageS = "m_PageSize.Width " + m_PageSize.Width + " m_Margin.Width " + m_Margin.Width + " m_PageSize.Height " + m_PageSize.Height + " m_Margin.Height " + m_Margin.Height + Environment.NewLine +
"page.Size.Width " + page.Size.Width + " page.Size.Height " + page.Size.Height;
FormattedText header = new FormattedText("\u1F440 " + printHeader + Environment.NewLine + pageS,
System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
m_Typeface, 14, System.Windows.Media.Brushes.Black);
ctx.DrawText(header, new System.Windows.Point(96 / 2, -96 / 4)); // 1/4 inch above page content
//text = new FormattedText(pageS, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
// m_Typeface, 14, System.Windows.Media.Brushes.Black);
string goGabe = string.Empty;
if (sID != null)
{
goGabe += Environment.NewLine + "Gabriel Docs™ sysDocID: " + sID;
if (!string.IsNullOrEmpty(docID))
goGabe += " docID: " + docID;
}
goGabe += Environment.NewLine + "Page: " + (pageNumber + 1) + " Date: " + DateTime.Now.ToString() + " User: " + App.StaticGabeLib.CurUserP.UserID;
FormattedText footer = new FormattedText(goGabe
, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight,
m_Typeface, 14, System.Windows.Media.Brushes.Black);
ctx.DrawText(footer, new System.Windows.Point(96 / 2, page.Size.Height - m_Margin.Height));
//ctx.DrawText(footer, new System.Windows.Point(96 / 2, m_Paginator.PageSize.Height - m_Margin.Height));
}
DrawingVisual background = new DrawingVisual();
using (DrawingContext ctx = background.RenderOpen())
{
ctx.DrawRectangle(new SolidColorBrush(System.Windows.Media.Color.FromRgb(240, 240, 240)), null, page.ContentBox);
}
newpage.Children.Add(background); // Scale down page and center
ContainerVisual smallerPage = new ContainerVisual();
smallerPage.Children.Add(page.Visual);
smallerPage.Transform = new MatrixTransform(0.8, 0, 0, 0.8, 0.1 * page.ContentBox.Width, 0.1 * page.ContentBox.Height);
newpage.Children.Add(smallerPage);
newpage.Children.Add(title);
newpage.Transform = new TranslateTransform(m_Margin.Width, m_Margin.Height);
return new DocumentPage(newpage, m_PageSize, Move(page.BleedBox), Move(page.ContentBox));
}
public override bool IsPageCountValid
{
get
{
return m_Paginator.IsPageCountValid;
}
}
public override int PageCount
{
get
{
return m_Paginator.PageCount;
}
}
public override System.Windows.Size PageSize
{
get
{
Debug.WriteLine("PageSize " + sizeXPS.Width + " " + sizeXPS.Height);
return sizeXPS; // this is not called
//m_Paginator.PageSize;
}
set
{
sizeXPS = value;
// m_Paginator.PageSize = value;
}
}
public override IDocumentPaginatorSource Source
{
get
{
return m_Paginator.Source;
}
}
}

Android Wear File does not appear

I created a file to read the sensors of my Android Wear. I can tell it is working because my storage is being filled up, but I can't see the folder of the readings. Can you help me out finding out what is wrong with the code?
public class Logging extends Activity implements SensorEventListener {
DecimalFormat df =new DecimalFormat("##.##");
Boolean flag=true;
FileOutputStream outputStream;
TextView displayReading1;
TextView displayReading2;
TextView displayReading3;
TextView displayReading4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final File Project=getDir("Project", Context.MODE_PRIVATE);
if(!Project.exists())
Project.mkdir();
File fileWithinProject=new File (Project+"/","Project.txt");
if(!fileWithinProject.exists())
try {
fileWithinProject.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
// final File file=new File (dirPath,"Project.txt");
/* File file = new File(dirPath, "Project.txt");
try {
if (!file.exists())
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}*/
setContentView(R.layout.activity_logging);
Button start=(Button)findViewById(R.id.StartButton);
Button stop=(Button)findViewById(R.id.StopButton);
//BUTTON START
start.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=true;
Toast.makeText(getApplicationContext(),"Start Recording Readings",Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), ("File in: "+ Project), Toast.LENGTH_LONG).show();
}
}); {
}
//BUTTON STOP
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
flag=false;
Toast.makeText(getApplicationContext(),"Done recording readings",Toast.LENGTH_SHORT).show();
}
});{
}
SensorManager sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
Sensor rotSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
Sensor gravitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);
Sensor gyroSensor = sensorManager.getDefaultSensor((Sensor.TYPE_GYROSCOPE));
sensorManager.registerListener(this, accSensor, 100000000);
sensorManager.registerListener(this, rotSensor, 100000000);
sensorManager.registerListener(this, gravitySensor, 100000000);
sensorManager.registerListener(this, gyroSensor, 100000000);
displayReading1 = (TextView) findViewById(R.id.acc_sensor);
displayReading2 = (TextView) findViewById(R.id.rotational_sensor);
displayReading3 = (TextView) findViewById(R.id.gravity_sensor);
displayReading4 = (TextView) findViewById(R.id.gyro_sensor);
displayReading1.setTextSize(14f);
displayReading2.setTextSize(14f);
displayReading3.setTextSize(14f);
displayReading4.setTextSize(14f);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_logging, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSensorChanged (SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
displayReading1.setText("Accelerometer (m/s2): " +"\nX"+" " +df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X11=event.values[0];
float X12=event.values[1];
float X13=event.values[2];
if( flag) {
try {
// Toast.makeText(getApplicationContext(), ("current location newFile.getAbsolutePath()), Toast.LENGTH_LONG).show();
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(((df.format(X11) + df.format(X12) + df.format(X13)
)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR)
displayReading2.setText("Rotational Vector: " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X21=event.values[0];
float X22=event.values[1];
float X23=event.values[2];
if( flag) {
try {
outputStream=openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Rotational Vector : " +"\nX"+" " +df.format(X21) + "\nY"+" " + df.format(X22) + "\nZ"+" " + df.format(X23)).getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}}
if (event.sensor.getType() == Sensor.TYPE_GRAVITY)
displayReading3.setText("Gravity (m/s2): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
if (event.sensor.getType() == Sensor.TYPE_GYROSCOPE)
displayReading4.setText("Gyroscope (rad/s): " + "\nX"+" " + df.format(event.values[0]) + "\nY"+" " + df.format(event.values[1]) + "\nZ"+" " + df.format(event.values[2]));
float X31=event.values[0];
float X32=event.values[1];
float X33=event.values[2];
if( flag) {
try {
outputStream = openFileOutput("Project.txt", Context.MODE_PRIVATE);
outputStream.write(("Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33)
).getBytes());
//Toast.makeText(getApplicationContext(), "Gyroscope (rad/s): " + "\nX" + " " + df.format(X31) + "\nY" + " " + df.format(X32) + "\nZ" + " " + df.format(X33), Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException f) {
System.out.println("Exception");
}
}
if (!flag){
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}

How to get alert when a message in delivered in window form application?

private void buttonSend_Click(object sender, EventArgs e)
{
InsertChatDetails();
//textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
textBoxChat.Text += textBoxMessage.Text + Environment.NewLine;
textBoxMessage.Text = "";
}
public void InsertChatDetails() //Inserting Values
{
try
{
CommonCS CommonSample1 = new CommonCS();
BusinessCS BFSample1 = new BusinessCS();
CommonSample1.Id = "1";
CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "-->" + Program.UserName + Environment.NewLine;
//CommonSample1.FromUser = textBoxChat.Text += System.DateTime.Now.ToLongTimeString() + "" + System.Environment.GetEnvironmentVariable("Computername") + Environment.NewLine;
CommonSample1.ToUser = "";
CommonSample1.MessageText = textBoxMessage.Text;
CommonSample1.SentOn = DateTime.Now;
CommonSample1.StatusReport = 0;
BFSample1.InsertChatDetails(CommonSample1);
}
catch (Exception)
{
}
}
Not sure from your code what you are trying to do, but if its synchronous you can trace it after SendMessageToWinMachine() ,else you can use CallBack Method for asynchronus call.

SQLServerException Invalid column name

I have a problem that doesn't appear always, but it do it most of the times. In my huge java forecast class I have some ResultSets, and when I execute the routine I get:
com.microsoft.sqlserver.jdbc.SQLServerException: El nombre de columna DistanciaMision no es vßlido.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:170)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.findColumn(SQLServerResultSet.java:626)
at com.microsoft.sqlserver.jdbc.SQLServerResultSet.getString(SQLServerResultSet.java:2301)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.etaMSR(Forecast.java:1109)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.phase2(Forecast.java:662)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.setData(Forecast.java:166)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.main(Forecast.java:81)
at es.csic.iiia.udt.itim.iInformation.WebData.Forecast.execute(Forecast.java:71)
at org.quartz.core.JobRunShell.run(JobRunShell.java:199)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:546)
The column exists, so I don't know what is the problem...
The code line is this one:
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
The same problem appears on other columns but it usually crash here.
Thank you!
Edit: ok, this is the whole method:
private static void etaMSR() throws Exception, SQLException {
/**
*
* Calculem ETAN MSR - Mision - Seguimiento - Restricciones conductor
*
*
**/
System.out
.print("Get data from iTIM forecast&forecastAUX DDBB ....... ");
myStatement = MSSQLServerAccess.connection();
// Distancia mision, ruta, hora mision anterior, hora
rs = getTable("SELECT dbo.WebForecast.IdConductor, dbo.WebForecast.IdMision, dbo.WebForecast.IdMisionAnterior, dbo.WebForecast.DistanciaMision, "
+ " WebForecast_1.HoraIniMis AS himanterior, dbo.WebForecast.HoraFiMis AS hfmactual, WebForecast_1.Ciudad AS CiudadOrigen,"
+ " dbo.WebForecast.Ciudad AS CiudadDestino, dbo.Distancias.Ruta, dbo.WebForecast.HoraDistancia AS HoraDistancia"
+ " FROM dbo.WebForecast AS WebForecast_1 INNER JOIN"
+ " dbo.Distancias ON WebForecast_1.Ciudad = dbo.Distancias.Origen RIGHT OUTER JOIN"
+ " dbo.WebForecast ON WebForecast_1.IdMision = dbo.WebForecast.IdMisionAnterior AND dbo.Distancias.Destino = dbo.WebForecast.Ciudad"
+ " WHERE (dbo.WebForecast.IdConductor <> '') AND (CONVERT(datetime, '"
+ df.format(fechaDia)
+ "') <= dbo.WebForecast.HoraFiMis) "
+ " AND WebForecast_1.HoraIniMis <= CONVERT(datetime, '"
+ df.format(fechaDia) + "') ");
System.out.println("[ok]");
while (rs.next() && (rs.getString("IdConductor") != "") && org.apache.commons.lang.StringUtils.isNumeric(rs.getString("IdConductor"))) {
int initialodometer = 0;
String start = null;
if (rs.getString("HoraDistancia") != null) {
start = rs.getString("HoraDistancia");
}
if (rs.getString("himanterior") != null) {
start = rs.getString("himanterior");
}
if (start != null) {
ResultSet myrs = null;
Timestamp tobjetivo = rs.getTimestamp("himanterior");
long boundtime = 7200000; // 3600000 = 60m = 1h
Timestamp tini = (Timestamp) rs.getTimestamp("himanterior")
.clone();
Timestamp tfin = (Timestamp) rs.getTimestamp("himanterior")
.clone();
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
int contador = 0;
long bestdiff = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') " + "AND CONVERT(datetime, '"
+ df.format(tfin) + "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor")) + "')");
int j = 0;
while (!myrs.next() && (j < 20)) {
// En caso de no encontrar en las 2h antes y despues nada:
tini.setTime(tini.getTime() - boundtime);
tfin.setTime(tfin.getTime() + boundtime);
myrs.close();
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT DISTINCT Odometer, DT "
+ "FROM DriverEvents "
+ "WHERE (DT BETWEEN CONVERT(datetime, '"
+ df.format(tini) + "') "
+ "AND CONVERT(datetime, '" + df.format(tfin)
+ "')) " + "AND (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "')");
j++;
}
if (myrs.next()) {
initialodometer = myrs.getInt("Odometer");
bestdiff = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
contador++;
while (myrs.next()) {
long pretendiente = Math.abs(tobjetivo.getTime()
- myrs.getTimestamp("DT").getTime());
if (pretendiente <= bestdiff) {
bestdiff = pretendiente;
initialodometer = myrs.getInt("Odometer");
}
contador++;
}
}
myrs.close();
}
// Get Odometer distance at the moment
if (!rs.getString("IdConductor").isEmpty() && !rs.getString("IdConductor").equals("") ) {
ResultSet myrs = null;
int myodometer = 0;
myStatement = MSSQLServerAccess.connection();
myrs = getTable("SELECT MAX(DT) AS DT, MAX(Odometer) AS Odometer"
+ " FROM dbo.DriverEvents"
+ " WHERE (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "')) ");
if (myrs.next()) {
myodometer = myrs.getInt("Odometer");
if (initialodometer == 0)
initialodometer = myodometer;
Float distancia_restante = (float) ( Integer.parseInt(rs.getString("DistanciaMision")) - (myodometer - initialodometer));
if (distancia_restante < 0)
distancia_restante = (float) 0;
Timestamp ETAN = null;
Calendar cal = Calendar.getInstance();
if (rs.getTimestamp("himanterior") != null && rs.getTimestamp("himanterior").toString() != "") {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
if (cal.after(Calendar.getInstance())) {
cal.setTimeInMillis(rs.getTimestamp("himanterior")
.getTime());
}
if (cal.before(Calendar.getInstance())) {
cal = Calendar.getInstance();
}
} else {
if (rs.getTimestamp("HoraDistancia") != null)
cal.setTimeInMillis(rs
.getTimestamp("HoraDistancia").getTime());
}
myStatement = MSSQLServerAccess.connection();
rs2 = getTable("SELECT TOP (100) PERCENT CardId, DT"
+ " FROM dbo.DriverEvents"
+ " GROUP BY CardId, DT"
+ " HAVING (CardId = '"
+ Integer.parseInt(rs.getString("IdConductor"))
+ "') AND (DT > CONVERT(datetime, '"
+ df.format(fechaDatos) + "'))");
if (rs2.next()) {
ETAN = getETAN(rs, distancia_restante, cal);
} else {
ETAN = getETA(rs, distancia_restante, cal, 1);
Statement myStatement2 = MSSQLServerAccess.connection();
myStatement2.executeUpdate("UPDATE WebForecast "
+ "SET ETAmsr = '" + df.format(ETAN)
+ "', KmsDiff = '" + distancia_restante.intValue()
+ "' " + "WHERE IdMision = '"
+ rs.getString("IdMision") + "'");
} else {
}
}
}
rs.close();
}
And the statement, maybe i'm doing something wrong?:
private static Statement conStatement(Properties properties){
String driverName = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; // Load the JDBC driver
String dbURL = "jdbc:sqlserver://"
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbserverIP")
+ ";DatabaseName="
+ properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.ddbbName")
+ ";SelectMethod=Cursor;"; // Connect to a server and database
String userName = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userName");
String userPwd = properties.getProperty("qualcomm.action.JDBC.MSSQLServerAccess.userPwd");
Connection dbConn;
try {
Class.forName(driverName);
dbConn = DriverManager.getConnection(dbURL, userName, userPwd);
//log.info("Connection Successful!");
Statement myst = dbConn.createStatement();
return myst;
} catch (Exception e) {
log.error(e);
System.out.println(e);
return null;
}
}
Thanks guys :) Could be something wrong with the statement?
remember that Java is case-sensitive and so can be your table on SQL depending on the way you created them, actually depending on the collation on your DB. If your database is created with a Case Sensitive collation then all object names will be Case Sensitive.
try to check the exact columns name of the column on SQL and access it using [] and the exact case

Resources