Hello I have a Barchart in JavaFx, the Data Show just fine when is directly loaded in the initialize method, but When I Load a MouseEvent, the Date label does not show correctly. I Put here a minimized example.
this is my code in IncidentesController
#FXML private ComboBox<String> solicitudindc;
#FXML private JFXButton generarind;
#FXML private BarChart <String,Integer> indicadorsoporte;
#FXML private CategoryAxis fechas;
#FXML private NumberAxis cantidades;
public void generaindicador() {
String Bd="jdbc:sqlserver://DESKTOP-
8PJDQNJ:1433;databaseName=QUORA";
String Usuario="myuser";
String Pass="mypass";
String Query= "SELECT FECHA_EJECUTADA , COUNT(PRIORIDAD) AS CANTIDAD FROM RINCIDENTES WHERE PRIORIDAD='ALTA' GROUP BY FECHA_EJECUTADA ORDER BY FECHA_EJECUTADA ASC";
String Query2= "SELECT FECHA_EJECUTADA , COUNT(PRIORIDAD) AS CANTIDAD FROM RINCIDENTES WHERE PRIORIDAD='MEDIA' GROUP BY FECHA_EJECUTADA ORDER BY FECHA_EJECUTADA ASC";
XYChart.Series<String,Integer> DatosPrioridad = new Series<String,Integer> ();
XYChart.Series<String,Integer> DatosPrioridad2 = new Series<String,Integer> ();
Connection Conexiontabla = null;
try {
............conection code...........
while (rs.next()) {
String y=rs.getString("FECHA_EJECUTADA");
int a=rs.getInt("CANTIDAD");
DatosPrioridad.getData().add(new XYChart.Data<>(y,a) );
}
indicadorsoporte.getData().add(DatosPrioridad);
DatosPrioridad.setName("PRIORIDAD ALTA");
}catch(SQLException e) {
e.printStackTrace();
}
try {
............conection code...........
while (rss.next()) {
String x=rss.getString("FECHA_EJECUTADA");
int z=rss.getInt("CANTIDAD");
DatosPrioridad2.getData().add(new XYChart.Data<>(x,z) );
}
indicadorsoporte.getData().add(DatosPrioridad2);
DatosPrioridad2.setName("PRIORIDAD MEDIA");
fechas.setLabel("Fechas");
cantidades.setLabel("Cantidades");
}catch(SQLException e) {
e.printStackTrace();
}
}
If the Combobox have the value "REPORTE DE INCIDENTES" I load the barchart like this:
public void generaincidentes() {
generarind.setOnMouseClicked(e->{
if(solicitudindc.getSelectionModel().getSelectedItem().toString().equals("REPORTE DE INCIDENTES")) {
generaindicador();
}
});
}
this are the images:
when i load directly in the initialize method:
when I select the option in the combobox to load the Barchart:
any guidance?
This work for me!:
#SuppressWarnings("unchecked")
public ObservableList<XYChart.Series<String, Integer>>
getdatosbarchart() {
String Bd="jdbc:sqlserver://DESKTOP-8PJDQNJ:1433;databaseName=QUORA";
String Usuario="sa";
String Pass="milkas87";
String Query= "SELECT FECHA_EJECUTADA , COUNT(PRIORIDAD) AS CANTIDAD FROM RINCIDENTES WHERE PRIORIDAD='ALTA' GROUP BY FECHA_EJECUTADA ORDER BY FECHA_EJECUTADA ASC";
String Query2= "SELECT FECHA_EJECUTADA , COUNT(PRIORIDAD) AS CANTIDAD FROM RINCIDENTES WHERE PRIORIDAD='MEDIA' GROUP BY FECHA_EJECUTADA ORDER BY FECHA_EJECUTADA ASC";
ObservableList<XYChart.Series<String, Integer>> data =FXCollections.observableArrayList();
Series<String, Integer> as = new Series<>();
Series<String, Integer> bs = new Series<>();
Connection Conexiontabla = null;
try {
Conexiontabla=DriverManager.getConnection(Bd, Usuario, Pass);
PreparedStatement ps =Conexiontabla.prepareStatement(Query);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String y=rs.getString("FECHA_EJECUTADA");
int a=rs.getInt("CANTIDAD");
as.getData().add(new XYChart.Data<>(y,a) );
}
as.setName("PRIORIDAD ALTA");
}catch(SQLException e) {
e.printStackTrace();
}
try {
Conexiontabla=DriverManager.getConnection(Bd, Usuario, Pass);
PreparedStatement pd =Conexiontabla.prepareStatement(Query2);
ResultSet rss = pd.executeQuery();
while (rss.next()) {
String y=rss.getString("FECHA_EJECUTADA");
int a=rss.getInt("CANTIDAD");
bs.getData().add(new XYChart.Data<>(y,a) );
}
bs.setName("PRIORIDAD MEDIA");
fechas.setLabel("Fechas");
cantidades.setLabel("Cantidades");
}catch(SQLException e) {
e.printStackTrace();
}
data.addAll(as,bs);
return data;
}
public BarChart<String, Integer>crearbarchart() {
indicadorsoporte.setData(getdatosbarchart());
indicadorsoporte.setTitle("Soportes realizados en el Mes");
return indicadorsoporte;
}
Related
I'm asking for your help.
I'm developing an application in JavaFX who "scan" Mp3 files to get ID3tag.
Here is my problem. I did a foreach loop of a list for every .mp3 found but I'd like to increment a label which inform the progression of the list.
Here is my code
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
this.labelUpdate.setText(this.current++ + " of " + " size");
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
}
Actually, when the loop progress my window interface is completely freeze.
And only when the loop is finished, the label updated.
Someone can explain why ?
I already thank you for your answers.
EDIT :
Here is my fully code
public class LaunchOption extends Pane {
private final HBox launchAndSend = new HBox();
private final HBox browseAndField = new HBox();
private final HBox jsonAndAdvance = new HBox();
private ArrayList<DataSong> lsWithData = new ArrayList<>();
private String sendJson;
private File selectedDirectory;
private User user;
private int currentData;
private final ProgressIndicator pi = new ProgressIndicator(0);
private final VBox containerElement = new VBox();
private final TextArea displayJson = new TextArea();
private final TextField pathDir = new TextField();
private final TextField nbrOfData = new TextField();
private final Button btnScan = new Button();
private final Button btnSend = new Button();
private final Button btnCheckJson = new Button();
private final Button btnDirectoryBrowser = new Button();
private final Label nbMp3 = new Label();
public Label listAdvance = new Label();
private final Stage home;
public LaunchOption(Stage home){
this.home = home;
configureBtnCheckJson();
configureBtnScan();
configureBtnSend();
configureLabelMp3();
configureBtnDirectoryBrowser();
configureTextAreaDisplayJson();
configureTextFieldPathDir();
configureTextFieldNbDataMp3();
configureHBoxlaunchSend();
configureHBoxBrowseAndField();
configureHBoxJsonAndAdvance();
configureContainer();
this.getChildren().addAll(containerElement,launchAndSend);
}
private void configureLabelMp3()
{
nbMp3.setText("MP3");
}
private void configureBtnScan(){
btnScan.setText("Scan");
btnScan.setOnAction(event->{
ArrayList<String> Mp3FileData;
Mp3FileData = mapFilesMp3(selectedDirectory.getAbsolutePath());
System.out.println("ListSize = " + Mp3FileData.size());
nbrOfData.setText(String.valueOf(Mp3FileData.size()));
try {
lsWithData = checkMp3File(Mp3FileData, selectedDirectory.getAbsolutePath());
} catch (UnsupportedTagException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidDataException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(MusiScanMp3agic.class.getName()).log(Level.SEVERE, null, ex);
}
pi.setProgress(1);
});
}
private void configureBtnDirectoryBrowser(){
btnDirectoryBrowser.setText("Browse ...");
btnDirectoryBrowser.getStyleClass().add("round-red");
btnDirectoryBrowser.setOnAction(event-> {
DirectoryChooser dc = new DirectoryChooser();
selectedDirectory = dc.showDialog(home);
pi.setProgress(0.35);
if(selectedDirectory == null)
{
pathDir.setText("No directory selected");
}
else
{
pathDir.setText(selectedDirectory.getAbsolutePath());
String Text = pathDir.getText();
System.out.println(Text.toString());
}
});
}
private static String regexMp3()
{
return "^.*\\.(mp3)$";
}
private ArrayList mapFilesMp3(String sDir){
ArrayList<String> ls = new ArrayList<>();
printFnames(sDir,ls);
return ls;
}
private static void printFnames(String sDir, ArrayList<String> ls)
{
File[] faFiles = new File(sDir).listFiles();
for(File file : faFiles)
{
if(file.getName().matches(regexMp3()))
{
// System.out.println(file.getAbsolutePath());
ls.add(file.getAbsolutePath());
}
if(file.isDirectory())
{
printFnames(file.getAbsolutePath(), ls);
}
}
}
private ArrayList checkMp3File(ArrayList<String> lsMp3file, String sDir) throws UnsupportedTagException, InvalidDataException, IOException
{
this.currentData = 1;
int size = lsMp3file.size();
ArrayList<DataSong> lsds = new ArrayList<>();
for(String mp3file : lsMp3file)
{
System.out.println(this.currentData++);
DataSong ds = new DataSong();
Mp3File mp3 = new Mp3File(mp3file);
ds.setLenghtOfMp3inSec(mp3.getLengthInSeconds());
ds.setBitRateOfMp3(mp3.getBitrate());
ds.setSampleRate(mp3.getSampleRate());
ds.setVbrOrCbr(mp3.isVbr());
if(mp3 != null){
ds.setAbsoluteLocation(mp3.getFilename());
ds.setLocation(removeSDir(mp3.getFilename(), sDir));
if(mp3.hasId3v2Tag())
{
ID3v2 id3v2Tag = mp3.getId3v2Tag();
if(!(id3v2Tag.getArtist() == null))
{
ds.setArtist(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getAlbum() == null))
{
ds.setAlbum((id3v2Tag.getAlbum()));
}
if(!(id3v2Tag.getTitle() == null))
{
ds.setTitle(id3v2Tag.getTitle());
}
if(!(id3v2Tag.getTrack() == null))
{
ds.setTrackOnAlbum(id3v2Tag.getTrack());
}
if(!(id3v2Tag.getYear() == null) && !(id3v2Tag.getYear().isEmpty()))
{
ds.setYearReleased(id3v2Tag.getYear());
}
if(!(id3v2Tag.getGenreDescription() == null))
{
ds.setGenre(id3v2Tag.getGenreDescription());
}
if(!(id3v2Tag.getComposer() == null))
{
ds.setComposer(id3v2Tag.getComposer());
}
if(!(id3v2Tag.getPublisher() == null))
{
ds.setPublisher(id3v2Tag.getPublisher());
}
if(!(id3v2Tag.getOriginalArtist() == null))
{
ds.setOriginArtist(id3v2Tag.getOriginalArtist());
}
if(!(id3v2Tag.getAlbumArtist() == null))
{
ds.setAlbumArtString(id3v2Tag.getAlbumArtist());
}
if(!(id3v2Tag.getCopyright() == null))
{
ds.setCopyright(id3v2Tag.getCopyright());
}
if(!(id3v2Tag.getUrl() == null))
{
ds.setUrl(id3v2Tag.getUrl());
}
}
}
lsds.add(ds);
}
return lsds;
}
I presume that what I should do is to make my checkMp3File method into a Task method which will do a background thread ?
There is not enough code to be sure but I think you are probably calling your method on the JavaFX application thread which then blocks your UI.
You should read the documentation about concurrency in JavaFX.
https://docs.oracle.com/javase/8/javafx/interoperability-tutorial/concurrency.htm
Some assistance with sorting this error message would be gratefully appropriated. The error message is triggered when clicking on the submit button after populating the page.
AddNewProduct
public partial class AddNewProduct : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GetCategories();
}
}
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName";
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (UploadProductPhoto.PostedFile != null)
{
SaveProductPhoto();
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue),
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
k.AddProduct();
ClearText();
Response.Redirect("~/Admin/AdminFillerPage.aspx");
}
}
private void ClearText()
{
txtProductName.Text = string.Empty;
txtProductDescription.Text = string.Empty;
txtProductPrice.Text = string.Empty;
txtProductStock.Text = string.Empty;
UploadProductPhoto = null;
}
private void SaveProductPhoto()
{
if (UploadProductPhoto.PostedFile != null)
{
string fileName = UploadProductPhoto.PostedFile.FileName.ToString();
string fileExtension = System.IO.Path.GetExtension(UploadProductPhoto.FileName);
//check file name legnth
if (fileName.Length > 96)
{
//Alert.Show("image name should not exceed 96 characters !");
}
//check filetype
else if (fileExtension != ".jpeg" && fileExtension != ".jpg" && fileExtension != ".png" && fileExtension != ".bmp")
{
//Alert.Show("Only jpeg,jpg,bmp & png imags are allowed!");
}
//check file size
else if (UploadProductPhoto.PostedFile.ContentLength > 4000000)
{
//Alert.Show("image size should not be greater than 4MB !");
}
//Save images into Images folder
else
{
UploadProductPhoto.SaveAs(System.IO.Path.Combine(Server.MapPath("~/ProductImages/"), fileName));
}
}
}
Shopping Cart
public class ShoppingCart
{
//Declaring Variables
public int CategoryID;
public string CategoryName;
public string ProductName;
public string ProductDescription;
public string ProductPrice;
public string ProductStock;
public string ProductImageUrl;
public void AddCategory()
{
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataAccess.AddParamater("#CategoryName", CategoryName, System.Data.SqlDbType.VarChar, 200);
DataTable dt = DataAccess.ExecuteDTByProcedure("mj350.AddCategory", parameters);
}
public void AddProduct()
{
SqlParameter[] parameters = new SqlParameter[6];
//Passing all the parameters that needed to be saved into the database
parameters[0] = DataLayer.DataAccess.AddParamater("#ProductName", ProductName, System.Data.SqlDbType.VarChar, 500);
parameters[1] = DataLayer.DataAccess.AddParamater("#CategoryID", CategoryID, System.Data.SqlDbType.Int, 100);
parameters[2] = DataLayer.DataAccess.AddParamater("#ProductDescription", ProductDescription, System.Data.SqlDbType.VarChar, 800);
parameters[3] = DataLayer.DataAccess.AddParamater("#ProductPrice", ProductPrice, System.Data.SqlDbType.VarChar, 500);
parameters[4] = DataLayer.DataAccess.AddParamater("#ProductStock", ProductStock, System.Data.SqlDbType.VarChar, 500);
parameters[5] = DataLayer.DataAccess.AddParamater("#ProductImage", ProductImageUrl, System.Data.SqlDbType.VarChar, 500);
//Executes the saved procedure that is saved in the database
DataTable dt = DataLayer.DataAccess.ExecuteDTByProcedure("mj350.AddProduct", parameters);
}
Stored Procedure - Add Product
CREATE PROCEDURE [AddProduct]
(
#ProductName varchar(500),
#CategoryID int,
#ProductDescription varchar(800),
#ProductPrice varchar(500),
#ProductStock varchar(500),
#ProductImage varchar(500)
)
AS
BEGIN
BEGIN TRY
INSERT INTO Product VALUES
(
#ProductName,
#CategoryID,
#ProductDescription,
#ProductPrice,
#ProductStock,
#ProductImage
)
END TRY
BEGIN CATCH
-- INSERT INTO dbo.ErrorLog
--VALUES(ERROR_MESSAGE(),'sp_GetAllData')
PRINT( 'Error occured' )
END CATCH
END
Stored Procedure - Get Categories
CREATE PROCEDURE [mj350].[ListCategories]
AS
BEGIN
BEGIN TRY
SELECT * FROM Category
END TRY
BEGIN CATCH
-- INSRET INTO dbo.ErrorLog
-- VALYES(ERROR_MESSAGE(), 'SP_GetAllData')
PRINT( 'Data Insert Error - Please review' )
END CATCH
END
Sorry if it's a silly mistake - coding skills not the best. All help gratefully received.
Thanks
Jack
Example of data form is populated with &
Where error message is triggered in code
You have this error because of the following code
private void GetCategories()
{
ShoppingCart k = new ShoppingCart();
DataTable dt = k.GetCategories();
if (dt.Rows.Count > 0)
{
ddlProductCategory.DataValueField = "CategoryID";
ddlProductCategory.DataValueField = "CategoryName"; // Here you overwrite the DataValueField.
ddlProductCategory.DataSource = dt;
ddlProductCategory.DataBind();
}
}
You overwrite the DataValueField with CategoryName property name. Then when you submit your form you are executing the following code :
ShoppingCart k = new ShoppingCart()
{
ProductName = txtProductName.Text,
CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue), // Here SelectedValue is in incorrect format.
ProductDescription = txtProductDescription.Text,
ProductPrice = txtProductPrice.Text,
ProductStock = txtProductStock.Text,
ProductImageUrl = string.Format("/ProductImages/{0}", UploadProductPhoto.FileName)
};
The exception is thrown because of this line CategoryID = Convert.ToInt32(ddlProductCategory.SelectedValue). The posted Selected value is not in correct format because you bind the value of your dropdown list with the name of the category.
To solve this you must replace this line ddlProductCategory.DataValueField = "CategoryName"; in your GetCategories by this line ddlProductCategory.DataTextField = "CategoryName";
I'd like to re-use a dialog class for data manipulation. The data will be retrieved from database. It depends on which table the class retrieve the data from, the size of the table columns is not fixed, so I can't declare column variables. After users update data, I would like to convert the input data using setResultConverter but do not know how to refer to the variable, since the program generates TextFields dynamically. Please help. Here is the the code.
public class AddDialog {
private Dialog<DBtable> dialog = new Dialog<DBtable>();
private ButtonType saveBtn;
//database variables
private Connection connect; // = null;
private String dbTblName;
//gridpane content variables
private GridPane contentPane = new GridPane();
private HashMap<String, TextField> fieldMap =
new HashMap<String, TextField>();
private ArrayList<String> dataList = new ArrayList<String>();
public AddDialog (String title, String header, String dbTable) {
this.dbTblName = dbTable;
dialog.setTitle(title);
dialog.setHeaderText(header);
saveBtn = new ButtonType("Save", ButtonData.OK_DONE);
dialog.getDialogPane().getButtonTypes().addAll(saveBtn,
ButtonType.CANCEL);
dialog.getDialogPane().setContent(getLayout(dbTable));
Optional<DBtable> result = dialog.showAndWait();
result.ifPresent(data -> {
System.out.println(" data="+data+" 0="+data.getID()+
" 1="+data.getField1());
});
} // constructor ends
public GridPane getLayout(String dbTable) {
String sql = "select column_name, description ";
sql += "from syscolumn_description ";
sql += "where table_name = \'" + dbTable + "\'";
String fieldLabel, fieldCol;
ResultSet ds = null;
// retrieve meta data from database
connect = DBConnect.getConnect(connect);
try {
Statement labelStmnt = connect.createStatement();
ds = labelStmnt.executeQuery(sql);
int row = 0;
while (ds.next()) {
row += 2;
//label....column=0 row=row+2;
fieldLabel = ds.getString("DESCRIPTION");
contentPane.add(new Text(fieldLabel), 0, row);
//textField...column=1 row=row+2;
contentPane.add(new TextField(), 1, row);
fieldCol = ds.getString("COLUMN_NAME");
fieldMap.put(fieldCol, new TextField());
} // while result set loop ends
} catch (Exception e) {
e.printStackTrace();
} finally {
try {if(ds != null) ds.close();} catch (Exception e) {};
}
// convert result
dialog.setResultConverter(dialogButton -> {
if (dialogButton == saveBtn) {
int i=0;
for (Map.Entry<String, TextField> e : fieldMap.entrySet()) {
dataList.add(e.getValue().getText());
i++;
System.out.println("col="+e.getKey()+
" data="+e.getValue().getText());
} // map loop end
return new DBtable(dataList, i);
}
return null;
});
return contentPane;
} //getLayout ends
} // AddDialog ends
I have a error regarding database as shown below:
E/CursorWindow(386): Bad request for field slot 0,-1. numRows = 1, numColumns = 63
here's my piece of code:
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "contactsManager";
// Contacts table name
private static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_IMAGE = "image";
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_IMAGE + " BLOB,"
+ KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE,contact.getImageId());
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Methods getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,KEY_IMAGE,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Methods contact = new Methods(Integer.parseInt(cursor.getString(cursor.getColumnIndex(KEY_ID))),
cursor.getBlob(cursor.getColumnIndex(KEY_IMAGE)),cursor.getString(cursor.getColumnIndex(KEY_NAME)), cursor.getString(cursor.getColumnIndex(KEY_PH_NO)));
// return contact
cursor.close();
return contact;
}
// Getting All Contacts
public List<Methods> getAllContacts() {
List<Methods> contactList = new ArrayList<Methods>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Methods contact = new Methods();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setImageId(cursor.getBlob(1));
contact.setName(cursor.getString(2));
contact.setPhoneNumber(cursor.getString(3));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
// return contact list
return contactList;
}
/*// Updating single contact
public int updateContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}*/
// Deleting single contact
public void deleteContact(Methods contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
Log.v("deleteContact", "Deleted row is: "+String.valueOf(contact.getID()));
}
void deleteAll(Methods contact)
{
SQLiteDatabase db= this.getWritableDatabase();
db.delete(TABLE_CONTACTS, null, null);
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
It would help to have more information here (a stack trace perhaps?). However it seems you're not providing an "id" when adding a contact. Consider making this column auto incrementing instead.
Last, if this is an Android question, your primary key column should be auto incrementing and should be called "_id", else make sure that this is given as a column name in any cursor returned from a query. Also check that your database has a table called "android_metadata" too.
I'm trying to save my game configuration indatabase, I used a tutorial in this page: page.
I make this class called configuracion:
public class Configuraciones extends SQLiteOpenHelper {
static final String table_name = "configuraciones";
static final String cod_config = "id";
static final String nom_config = "nombre";
static final String val_config = "valor";
public Configuraciones(Context context) {
super(context, "bdd_cuarenta", null, 1);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_TABLE = "CREATE TABLE " + table_name + "("
+ cod_config + " INTEGER PRIMARY KEY," + nom_config + " TEXT,"
+ val_config + " TEXT" + ");";
// ESTABLISH NEW DATABASE TABLES IF THEY DON'T ALREADY EXIST IN THE DATABASE
db.execSQL(CREATE_TABLE);
//Ingresa las configuraciones por primera vez
ingresaTablas(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int vieja, int nueva) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + table_name);
onCreate(db);
}
public String consultaConfiguracion(String nombre){
SQLiteDatabase myDB = getReadableDatabase();
String[] mySearch = new String[]{nombre};
Cursor myCursor = myDB.rawQuery("SELECT "+ val_config +" FROM "+ table_name +" WHERE "+ nom_config +"='?'",mySearch);
myCursor.moveToFirst();
int index = myCursor.getColumnIndex(val_config);
String myAnswer = myCursor.getString(index);
myCursor.close();
return myAnswer;
}
public int actualizaConfig(String nombre, String nuevaConfig)
{
SQLiteDatabase myDB = getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(val_config, nuevaConfig);
int numRowsAffected = myDB.update(table_name, cv, nom_config+"='?'", new String []{String.valueOf(nombre)});
return numRowsAffected;
}
But when i call one of the methods, for example actualizaConfig, I got the error:
java.lang.IllegalStateException: getDatabase called recursively
In my game activity I called normaly the object like this:
private BoundCamera camera;
private Configuraciones configs;
#Override
public Engine onCreateEngine(EngineOptions pEngineOptions)
{
return new LimitedFPSEngine(pEngineOptions, 60);
}
public EngineOptions onCreateEngineOptions()
{
camera = new BoundCamera(0, 0, 800, 480);
configs = new Configuraciones(this);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), this.camera);
engineOptions.getAudioOptions().setNeedsMusic(true).setNeedsSound(true);
engineOptions.setWakeLockOptions(WakeLockOptions.SCREEN_ON);
return engineOptions;
}
And in GameScene, i call the method like this:
resourcesManager.config.actualizaConfig("diseno_carta", "9");
I dont know why is the problem... :(