Using SQLite in BlackBerry - sqlite

I am new to blackberry development. I am trying to make an application where I have to save name and three checkbox results(i.e. whether boxes have checked or not). I have created a screen. But I am not able to save the data in database and I think of using SQLite.
Please help me and tell how can I proceed and I have a confusion that where I will write the coding for database i.e. In the main screen class or I have to create another separate class.
Here is the coding for mainscreen.
package medicine;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.component.EditField;
import net.rim.device.api.ui.component.SeparatorField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.CheckboxField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.UiApplication;
public class EnterSuccessScreen extends MainScreen implements FieldChangeListener{
EditField nameField;
CheckboxField medicineCheckbox1;
CheckboxField medicineCheckbox2;
CheckboxField medicineCheckbox3;
ButtonField submitButton;
public EnterSuccessScreen(){
add(new LabelField("Please enter your details:"));
add(new SeparatorField());
nameField = new EditField("Medicine Name:", "");
add(nameField);
add(new SeparatorField());
add(new SeparatorField());
add(new LabelField("Time To Take the Medicine:"));
medicineCheckbox1 = new CheckboxField(" 9 a.m.", false,Field.FIELD_LEFT);
add(medicineCheckbox1);
medicineCheckbox2 = new CheckboxField(" 12 p.m.", false,Field.FIELD_LEFT);
add(medicineCheckbox2);
medicineCheckbox3 = new CheckboxField(" 3 p.m.", false,Field.FIELD_LEFT);
add(medicineCheckbox3);
add(new SeparatorField());
submitButton = new ButtonField("Submit", ButtonField.CONSUME_CLICK);
add(submitButton);
submitButton.setChangeListener(this);
}
public void fieldChanged(Field field, int context){
if (field == submitButton) {
submit();
}
else{}
}
private void submit(){
SubmitSuccessScreen submitSuccessScreen = new SubmitSuccessScreen();
UiApplication.getUiApplication().pushScreen(submitSuccessScreen);
}
}

Blackberry gave some sample demos for your problem you check on SqliteDemo in blackberry sample demos.

Related

Populating the combobox from database

I want to build a ComboBox that is populated with data from database but it's not working.The Scene Builder is fine i made the fxid:comboBoxx and onAction:fillComboBox2 and its running,but i dont have any data,just blank.I dont know where is the problem,i tried everything i know.
public class FXMLController implements Initializable {
#FXML
private ComboBox comboBoxx;
final ObservableList options = FXCollections.observableArrayList();
public void initialize(URL url, ResourceBundle rb) {
}
public void fillComboBox2() {
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;integratedSecurity=true;";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select artikulli from product_table";
PreparedStatement statement = con.prepareStatement(query);
ResultSet set = statement.executeQuery();
while(set.next()){
options.add(set.getString("artikulli"));
}
statement .close();
set.close();
} catch(ClassNotFoundException | SQLException ex) {
Logger.getLogger(JavaFXExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
There are a couple of things to address here. First of all, you are never actually telling your ComboBox where to find the data it's meant to display.
This is done using the comboBoxx.setItems() method. This is easy to do within the controller's initialize() method.
Also, you stated that you set the onAction property of the ComboBox to your fillComboBox2() method. This is not correct. Doing so will cause the fillComboBox2() method to be called every time you click on the dropdown for the ComboBox.
Instead, you should fill the ComboBox when loading the scene. So, remove the onAction definition from your FXML document.
Lastly, it would be a good idea to change that method entirely. In my updated code below, you'll see that I've changed it to a private method that returns a List<String>. We can use that List to populate the ComboBox.
Now, when the scene is being loaded, the comboBoxx.setItems() method is called, and the List<String> from the getData() method is used to populate it.
The code below also has some comments to help explain the flow.
THE CODE
import javafx.collections.FXCollections;
import javafx.fxml.FXML;
import javafx.scene.control.ComboBox;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FXMLController {
// If you ComboBox is going to display Strings, you should define that datatype here
#FXML
private ComboBox<String> comboBoxx;
#FXML
private void initialize() {
// Within this initialize method, you can initialize the data for the ComboBox. I have changed the
// method from fillComboBox2() to getData(), which returns a List of Strings.
// We need to set the ComboBox to use that list.
comboBoxx.setItems(FXCollections.observableArrayList(getData()));
}
/**
* Here we will define the method that builds the List used by the ComboBox
*/
private List<String> getData() {
String connectionUrl = "jdbc:sqlserver://localhost:1433;" + "databaseName=TestDB;integratedSecurity=true;";
// Define the data you will be returning, in this case, a List of Strings for the ComboBox
List<String> options = new ArrayList<>();
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection con = DriverManager.getConnection(connectionUrl);
String query = "select artikulli from product_table";
PreparedStatement statement = con.prepareStatement(query);
ResultSet set = statement.executeQuery();
while (set.next()) {
options.add(set.getString("artikulli"));
}
statement.close();
set.close();
// Return the List
return options;
} catch (ClassNotFoundException | SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
}

jxbrowser -- jquery.AreYouSure .. warning message always in English...

i trying to use jquery.AreYouSure into JxBrowser(5.2 and/or next version).
jquery.AreYouSure works... but the warning pop up windows is always in english...
This behaviour is wrong and differ from chrome/firox/ie.... these show message in the current language...
this is a demo url
http://www.papercut.com/products/free-software/are-you-sure/demo/are-you-sure-demo.html
By default, JxBrowser displays dialogs configured with English language. At the same time, JxBrowser API provides functionality that allows modifying default behavior and display your own dialogs with required language. To change the language you need to register your own DialogHandler where you can display your own dialog. For example:
import com.teamdev.jxbrowser.chromium.Browser;
import com.teamdev.jxbrowser.chromium.CloseStatus;
import com.teamdev.jxbrowser.chromium.UnloadDialogParams;
import com.teamdev.jxbrowser.chromium.swing.BrowserView;
import com.teamdev.jxbrowser.chromium.swing.DefaultDialogHandler;
import javax.swing.*;
import java.awt.*;
/**
* The sample demonstrates how to catch onbeforeunload dialog.
*/
public class BeforeUnloadSample {
public static void main(String[] args) {
Browser browser = new Browser();
final BrowserView view = new BrowserView(browser);
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.add(view, BorderLayout.CENTER);
frame.setSize(700, 500);
frame.setVisible(true);
browser.setDialogHandler(new DefaultDialogHandler(view) {
#Override
public CloseStatus onBeforeUnload(UnloadDialogParams params) {
String title = "Confirm Navigation";
String message = params.getMessage();
int returnValue = JOptionPane.showConfirmDialog(view, message, title, JOptionPane.OK_CANCEL_OPTION);
if (returnValue == JOptionPane.OK_OPTION) {
return CloseStatus.OK;
} else {
return CloseStatus.CANCEL;
}
}
});
browser.loadHTML("<html><body onbeforeunload='return myFunction()'>" +
"<a href='http://www.google.com'>Click here to leave</a>" +
"<script>function myFunction() { return 'Leave this web page?'; }" +
"</script></body></html>");
}
}

Alert in JAVA FX

I want to display an alert when a file already exists when trying to create the file with same name . I have not completed the code fully. I want to retrieve the button value Yes/No from the UI .
Code:
This is how the controller is coded.
package application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.TreeMap;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class WarningController implements Initializable {
#FXML
public Button yes;
#FXML
public Button no;
public static String type;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
// TODO Auto-generated method stub
}
public String confirmSelection(ActionEvent event)throws IOException{
Button button = (Button) event.getSource();
type = button.getText();
if(type.equals("Yes")){
Stage stage = (Stage) yes.getScene().getWindow();
stage.close();
//System.out.println("Yes");
return type;
}
else{
//System.out.println("No");
Stage stage1 = (Stage) no.getScene().getWindow();
stage1.close();
return type;
}
}
/********************************************************************************/
public void writesheet(String[][] result,String ComboValue,String[] heading) throws IOException{
//Create blank workbook
XSSFWorkbook workbook = new XSSFWorkbook();
//Create a blank sheet
XSSFSheet spreadsheet = workbook.createSheet( " Employee Info ");
//Create row object
XSSFRow row;
String[][] towrite=result;
int rows=towrite.length;
//int cols=towrite[0].length;
// System.out.println(rows +" "+ cols);
Map < String, Object[] > empinfo = new TreeMap < String, Object[] >();
empinfo.put("0", heading);
for(int i=1;i<=rows;i++){
empinfo.put( Integer.toString(i),towrite[i-1]);
}
//Iterate over data and write to sheet
Set < String > keyid = empinfo.keySet();
int rowid = 0;
for (String key : keyid)
{
row = spreadsheet.createRow(rowid++);
Object [] objectArr = empinfo.get(key);
int cellid = 0;
for (Object obj : objectArr)
{
Cell cell = row.createCell(cellid++);
//cell.setCellValue((String)obj);
cell.setCellValue(obj.toString());
}
}
//Write the workbook in file system
File f=new File(("C:\\"+ComboValue+".xlsx"));
if(f.exists()){
Stage primaryStage=new Stage();
Parent root=FXMLLoader.load(getClass().getResource("/application/Warning.fxml"));
Scene scene = new Scene(root,350,150);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
primaryStage.setScene(scene);
primaryStage.show();
System.out.println(type);
}
FileOutputStream out = new FileOutputStream(f);
workbook.write(out);
out.close();
System.out.println(ComboValue+" "+"Excel document written successfully" );
workbook.close();
}
}
I want to use button value(stored in String type) in writesheet function. Now it is returning NULL.
Please suggest if there is any other way to show warning.I am using two fxml files and this is the second excel file.
[1]: http://i.stack.imgur.com/ZK6UC.jpg
Simply use the Alert class. It provides functionality for most yes/no dialogs that you ever need.
Alert alert = new Alert(AlertType.WARNING,
"File already exists. Do you want to override?",
ButtonType.YES, ButtonType.NO);
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
Also here is a good tutorial.
I usually make a method, and call it if certain conditions are not met.
Ex:
if(condition)
alert();
public void alert(){ //alert box
Alert alert = new Alert(AlertType.WARNING,"", ButtonType.YES, ButtonType.NO); //new alert object
alert.setTitle("Warning!"); //warning box title
alert.setHeaderText("WARNING!!!");// Header
alert.setContentText("File already exists. Overwrite?"); //Discription of warning
alert.getDialogPane().setPrefSize(200, 100); //sets size of alert box
Optional<ButtonType> result = alert.showAndWait();
if (result.get() == ButtonType.YES){
// ... user chose YES
} else {
// ... user chose NO or closed the dialog
}
}
I grabbed some code from Jhonny007, credit to him.

String with numbers and letters to double javafx

Hi I am trying to read a the numbers from a text field that shows a price e.g. £3.00, and convert the value of the price to a double. Is there a way to do
Double value;
value = Double.parseDouble(textField.getText());
But it won't let me do that because of the £ sign. Is there a way to strip the pound sign then read the digits.
Thanks
There is some TextFormatter and change filter handling logic built into the JavaFX TextField API, you could make use of that.
import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.util.StringConverter;
import java.text.DecimalFormat;
import java.text.ParseException;
class CurrencyFormatter extends TextFormatter<Double> {
private static final double DEFAULT_VALUE = 5.00d;
private static final String CURRENCY_SYMBOL = "\u00A3"; // british pound
private static final DecimalFormat strictZeroDecimalFormat
= new DecimalFormat(CURRENCY_SYMBOL + "###,##0.00");
CurrencyFormatter() {
super(
// string converter converts between a string and a value property.
new StringConverter<Double>() {
#Override
public String toString(Double value) {
return strictZeroDecimalFormat.format(value);
}
#Override
public Double fromString(String string) {
try {
return strictZeroDecimalFormat.parse(string).doubleValue();
} catch (ParseException e) {
return Double.NaN;
}
}
},
DEFAULT_VALUE,
// change filter rejects text input if it cannot be parsed.
change -> {
try {
strictZeroDecimalFormat.parse(change.getControlNewText());
return change;
} catch (ParseException e) {
return null;
}
}
);
}
}
public class FormattedTextField extends Application {
public static void main(String[] args) { launch(args); }
#Override
public void start(final Stage stage) {
TextField textField = new TextField();
textField.setTextFormatter(new CurrencyFormatter());
Label text = new Label();
text.textProperty().bind(
Bindings.concat(
"Text: ",
textField.textProperty()
)
);
Label value = new Label();
value.textProperty().bind(
Bindings.concat(
"Value: ",
textField.getTextFormatter().valueProperty().asString()
)
);
VBox layout = new VBox(
10,
textField,
text,
value,
new Button("Apply")
);
layout.setPadding(new Insets(10));
stage.setScene(new Scene(layout));
stage.show();
}
}
The exact rules for DecimalFormat and the filter could get a little tricky if you are very particular about user experience (e.g. can the user enter the currency symbol? what happens if the user does not enter a currency symbol? are empty values permitted? etc.) The above example offers a compromise between a reasonable user experience and a (relatively) easy to program solution. For an actual production level application, you might wish to tweak the logic and behavior a bit more to fit your particular application.
Note, the apply button doesn't actually need to do anything to apply the change. Changes are applied when the user changes focus away from the text field (as long as they pass the change filter). So if the user clicks on the apply button, it gains, focus, the text field loses focus and the change is applied if applicable.
The above example treats the currency values as doubles (to match with the question), but those serious about currency may wish to look to BigDecimal.
For a simpler solution using similar concepts, see also:
Java 8 U40 TextFormatter (JavaFX) to restrict user input only for decimal number

importing error with import javax.imageio.ImageIO;

I am new to Java and are trying to display an image. I got code on the net but when trying it I get an error with the importing of " import javax.imageio.ImageIO;" The error message reads "javax.imageio.ImageIO" is either a misplace package name or a non-existing entity.
I have seen this on many samples but it does not work with me.
Is there any advice
mport java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
public class Showmap extends Panel
{
BufferedImage img;
public Showmap ()
{
try
{
image = ImageIO.read (new File ("KNP.jpg"));
}
/*
catch (IOException e)
{
BufferedImage image;
public ShowImage() {
try {
System.out.println("Enter image name\n");
BufferedReader bf=new BufferedReader(new
InputStreamReader(System.in));
String imageName=bf.readLine();
File input = new File(imageName);
image = ImageIO.read(input);
}*/
catch (IOException e)
{
System.out.println ("Error:" + e.getMessage ());
}
}
public void paint (Graphics g)
{
g.drawImage (image, 0, 0, null);
}
static public void main (String args []) throws
Exception
{
JFrame frame = new JFrame ("Display image");
Panel panel = new Showmap ();
frame.getContentPane ().add (panel);
frame.setSize (500, 500);
frame.setVisible (true);
}
}
Thanks
Ivan
In your Project select:
Right Click on "JRE System Libary"
Select Properties
On Execution Enviroment select "J2SE-1.5(jre8)" or later; you should use the latest version of jre8
I was programming with "Ready to Program" and tried many options with out success. When I copied the same code to "JCreator" and run it fro there it was working fine. Seems "import javax.imageio.ImageIO;" is not working with "Ready to Program".

Resources