I'm still learning Ionic and programming in general. I followed a link on the internet and I was able to create the white and read the necessary data, but I am not able to insert data in the created table. Can anyone help me with this?
I follow this tutorial: ionic-sqlite
My code:
getRegiao() { // Regiões //
return new Promise<Regiao[]>((resolve, reject) => {
let sql = "SELECT NOM_REGIAO, ID " +
"FROM TB_REGIAO "
this.executeQuery(sql).then(data => {
let regioes = [];
if (data != undefined)
data.forEach(function (row) {
let regiao: Regiao = { nom_regiao: row[0], id: row[1] }
regioes.push(regiao);
});
resolve(regioes);
}).catch(error => {
console.log(error);
});
});
}
addUser() {
let sql = "INSERT INTO TB_USUARIO (EMAIL) VALUES ('BLITCRANK#HOTMAIL.COM')";
// let sql = "SELECT EMAIL FROM TB_USUARIO";
this.executeQuery(sql);
}
executeQuery(sql: string) {
let db: any;
return new Promise<any>((resolve, reject) => {
let xhr = new XMLHttpRequest();
xhr.open('GET', this.dbName, true);
xhr.responseType = 'arraybuffer';
xhr.onload = (e) => {
let uInt8Array = new Uint8Array(xhr.response);
db = new SQL.Database(uInt8Array);
let contents = db.exec(sql);
console.log(contents);
if (contents.length > 0)
resolve(contents[0].values);
else
resolve("query executada sem retorno")
};
xhr.send();
});
}
Please use this plugin , this is the plugin that I am using.
Take note in using execute sql like this db.executeSql('create table danceMoves(name VARCHAR(32))', {})
But rather use this db.executeSql('create table danceMoves(name VARCHAR(32))', [])
I dont know why instead of using object '{}' they replace it as array '[]' I think they forgot to update the documentaion
Related
I have a application which useds TFS JAVA SDK 14.0.3 .
I have a shared query on my tfs , how can i run the shared query and get the response back using TFS SDK 14.0.3
Also I could see that the query url will expire in every 90 days , so any better way to execute the shared query?
Now I have a method to run a query , i want method to run shared query also.
public void getWorkItem(TFSTeamProjectCollection tpc, Project project){
WorkItemClient workItemClient = project.getWorkItemClient();
// Define the WIQL query.
String wiqlQuery = "Select ID, Title,Assigned from WorkItems where (State = 'Active') order by Title";
// Run the query and get the results.
WorkItemCollection workItems = workItemClient.query(wiqlQuery);
System.out.println("Found " + workItems.size() + " work items.");
System.out.println();
// Write out the heading.
System.out.println("ID\tTitle");
// Output the first 20 results of the query, allowing the TFS SDK to
// page
// in data as required
final int maxToPrint = 5;
for (int i = 0; i < workItems.size(); i++) {
if (i >= maxToPrint) {
System.out.println("[...]");
break;
}
WorkItem workItem = workItems.getWorkItem(i);
System.out.println(workItem.getID() + "\t" + workItem.getTitle());
}
}
Shared query is a query which has been run and saved, so what you need should be getting a a shared query, not run a shared query. You could refer to case Access TFS Team Query from Client Object API:
///Handles nested query folders
private static Guid FindQuery(QueryFolder folder, string queryName)
{
foreach (var item in folder)
{
if (item.Name.Equals(queryName, StringComparison.InvariantCultureIgnoreCase))
{
return item.Id;
}
var itemFolder = item as QueryFolder;
if (itemFolder != null)
{
var result = FindQuery(itemFolder, queryName);
if (!result.Equals(Guid.Empty))
{
return result;
}
}
}
return Guid.Empty;
}
static void Main(string[] args)
{
var collectionUri = new Uri("http://TFS/tfs/DefaultCollection");
var server = new TfsTeamProjectCollection(collectionUri);
var workItemStore = server.GetService<WorkItemStore>();
var teamProject = workItemStore.Projects["TeamProjectName"];
var x = teamProject.QueryHierarchy;
var queryId = FindQuery(x, "QueryNameHere");
var queryDefinition = workItemStore.GetQueryDefinition(queryId);
var variables = new Dictionary<string, string>() {{"project", "TeamProjectName"}};
var result = workItemStore.Query(queryDefinition.QueryText,variables);
}
By the way, you could also check the REST API in the following link:
https://learn.microsoft.com/en-us/rest/api/vsts/wit/queries/get
I am fairly new to functional programming and reactive RxJava. I want to get id and name of a device from database and store it in a Map, I am doing it in RxJava style. I am calling a function that doesn't need to return anything
.doOnNext(t -> updateAssetNameMap())
then the function looks like;
private void updateDeviceNameMap() {
LOGGER.debug("Reading device name and id from database");
Observable<SQLConnection> jdbcConnection = createJdbcConnection();
Scheduler defaultScheduler = RxHelper.scheduler(vertx);
Observable<JsonArray> res = jdbcConnection //need to return JsonArray
.flatMap(connection -> just(connection)
.flatMap(j -> runQuery(connection, "SELECT name,id FROM device")
.observeOn(defaultScheduler)
.doOnNext(m -> LOGGER.info("size: " + m.size()))
.flatMap(job -> { LOGGER.info(">>" + job.getJsonArray(0));
//or if I can extract JsonArray items here,
//I can update my Map here too.
return just(job.getJsonArray(0));
}
)
.doOnError(e -> { LOGGER.error("failed to connect to db", e);
connection.close(); })
.doOnCompleted(connection::close)
.onErrorReturn(e -> null));
//System.out.println("" + res.map(d -> LOGGER.info(d.toString())));
//get the JsonArray and update the deviceNameMap
The connection to DB is made successfully and query is also done correctly.
I can convert any Object to Observable by Observable.from(ObjectName), but can't to the opposite. An appropriate mapping needs to be done after .flatMap(job -> just(job.getJsonArray(0)) but I have no clue how. After running the Verticle, I even cannot see anything logged from line .flatMap(job -> { LOGGER.info(">>" + job.getJsonArray(0));.
Am I missing something ?
You must subscribe to your Observable<JsonArray> otherwise nothing happens.
I have created an ajax call in jquery to my server, the trouble I'm facing now is that my response is printing ? even though the correct integer value is written into the output stream. Ajax function is given below.
$dntb.on('click', 'button', function(event) {
var i = $(this).closest('tr').index(); //have to get the row where the button is clicked
var sditmId = $("#sditm").val();
var sdhedId = $("#sdhed").val();
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = ""+response;
$("#stk").val(stk);
});
});
This function is called on click of an issue button in my table shown below
The server code is given below
int stk = null;
switch (userPath) {
case "/getstock":
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId")); //value to write into the output stream.
break;
case "/temp":
//er = opo.checkCatUniqueForEdit(request.getParameter("catName"), request.getParameter("catId"));
break;
}
System.out.println(stk); //Printing correctly
response.setContentType("text/html");
response.getWriter().write(stk);
Code to get the value
public int getStockData(String sditm, String sdhed) {
int stk = 0;
try {
String query = "Select stk.Stk_instk from tbstk stk inner join tbsditm itm on itm.Sditm_prdid=stk.Stk_prdid where itm.Sditm_sdhed=" + sdhed + " and itm.Sditm_id=" + sditm;
Statement stmt = dcon.con.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
stk = rs.getInt("Stk_instk");
}
} catch (SQLException ex) {
Logger.getLogger(Op_OrdConf.class.getName()).log(Level.SEVERE, null, ex);
}
return stk;
}
The ajax call happens successfully but when I alert the response I'm getting and I'm getting the value correctly in the server but in the client side it is ?. Please help me solve this
Not sure but seems that you are missing a comma here:
stk = opo.getStockData(request.getParameter("sditmId"), request.getParameter("sdhedId"));
//----------------------------------------------------^-----i think this is missing.
As per your comment i would suggest you to explicitly set the dataType to html:
$.get('getstock', {
sditmId: sditmId,
sdhedId: sdhedId
}, function(response) {
alert(response);
var stk = "" + response;
$("#stk").val(stk);
},"html"); //<----------add the dataType here.
I converted the int value returning from the function as given below to String, it seems to be some conflict between the content type and the value written into the output stream
stk = opo.getStockData(request.getParameter("sditmId") request.getParameter("sdhedId"));
I have the unenviable task of editing a 2000 line javascript file inorder to maintain and add some new feature to a web app written in JSP, Json-RPC, jQuery and Java. I do not possess any deeper knowledge of jQuery and Json-RPC except basic Javascript knowledge and the original developer is not there anymore.
There is a JS function which accepts a few params, and calls a Json-RPC and here I am getting the error
arg 1 could not unmarshal
Can someone please tell me what this error means?
Here is my code
function distributeQuantityNew(pReportId, pDecimalPlaces, pRun) {
try {
alert('distributeQuantityNew: ' + pReportId + ', ' + pDecimalPlaces + ', ' + pRun);
var fieldValue = $("#distribution_quantity_" + pReportId).val();
if (fieldValue.length == 0) {
showErrorDialog(resourceBundleMap["error.no.distribution.quantity"]);
return;
} else {
$("#distribution_quantity_" + pReportId).val("");
}
var affectedRowIds = [];
var rows = $("#tableBody_" + pReportId + " tr:visible").has("input[type=text]").filter(function(index) {
var voucherType = this.cells[getVoucherColumnIndex()].innerHTML;
if ((voucherType == 'TRANSFER_CS') || (voucherType == 'PAYOUT_CS') || (voucherType == 'SOURCE_BON') || (voucherType == 'PAYOUT_BON')) {
return false;
}
affectedRowIds.push(parseInt(this.id.split("_")[3]));
return true;
}
);
var affectedReportRows = $.extend(true, {}, foreignReportMap[pReportId]);
$.each(affectedReportRows.map, function(i, row) {
if ($.inArray(row.partnerReportBillNr, affectedRowIds) == -1) {
delete affectedReportRows.map["row_" + row.partnerReportBillNr];
}
});
var report = getLoadedReportByRunId(pReportId);
var productType = report.partnerProductType;
SessionManager.extend();
var resultRows = jsonrpc.foreignReportObject.distributeQuantity(affectedReportRows, fieldValue, pDecimalPlaces, pRun);
alert('back after RPC');
$.each(resultRows.map, function(i, row) {
foreignReportMap[pReportId].map["row_" + row.partnerReportBillNr] = row;
updateForeignReportRow(row, true, productType);
});
updateSummaryRow(pReportId);
toggleApproveAllLink(pReportId);
sortForeignReportTable(pReportId, true);
} catch (e) {
handleError("Failed to distribute quantity: ", e);
}
}
I have peppered it with alerts so that I know whether RPC call was succesful, but I get the error arg 1 could not unmarshal before that from the catch block. Thanks for any hints
OK, got it solved. The first parameter to the remote function is expecting a list of Map<String, SomeBO>. SomeBO is a bean with several BigDecimals. I had another JS function which had set the values passed into the Map. This function was setting a BigNumber where I had a setter of String only. I wish the error I had gotten back from JSON unmarshaller was a bit more descriptive...Below is the code where I added .toString() to solve the issue
foreignReportMap[pReportId].map["row_" + pRowId].clientQuantity = clientQuantity.toString();
foreignReportMap[pReportId].map["row_" + pRowId].totalClientQuantity = totalClientQuantity.toString();
I am using Parse for my app. I want to query a table with column that set to be a pointer to other table. Here is the query:
ParseQuery query = new ParseQuery("CategoryAttribute");
query.whereEqualTo("categoryId", categoryId);
query.findInBackground(new FindCallback() {
#Override
public void done(List<ParseObject> categoryAttributes, ParseException e) {
if (e == null) {
for (int i = 0; i < categoryAttributes.size(); i++){
String atributeCategoryId = categoryAttributes.get(i).getString("categoryId");
String attributeKey = categoryAttributes.get(i).getString("attributeKey");
String attributeValue = categoryAttributes.get(i).getString("attributeValue");
setCategoryAtributeRow(atributeCategoryId, attributeKey, attributeValue);
}
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
So the categoryId column is a pointer to other table. Other columns work fine.
I tried to scan the API and the guides but couldn't find needed solution. Help would be much appreciated!
Here is the solution to this one:
First you need to create a ParseObject from the type of your table:
ParseObject sale = ParseObject.createParseObject("Sale");
Then you need to get the ParseObject from the result:
sale = result.getParseObject(pointer_field);
Now you can pull from sale any field that it has just as you would do it normally, for example:
sale.getString("some_field")
Note:
When you are doing your query you must to include the pointer field if you want to be able to extract the data from it after the query will be returned. The result:
query.include("pointer_field")
Hope it helps
#Akshat Agarwal, here is a example in JavaScript:
var parseObj = Parse.Object.extend('parseObj');
new Parse.Query(parseObj)
.include('pointerField')
.find(function (data) {
data.get('pointerField').get('fieldName');
});
For iOS
PFQuery *parseQuery = [PFQuery queryWithClassName:#"MyClass"];
[parseQuery whereKey:#"categoryId" equalTo:categoryId];
[parseQuery includeKey:#"pinter_field"];
[parseQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
//
}];