Processing can't find a callback function from a save dialog - java

For whatever reason, Processing does not seem to find the callback function after I select a file using selectOutput(). Here is the part of my code where I am trying to save a file:
void saveProjectDialog() { // Shows a save file dialog
JSONObject header = new JSONObject();
header.setString("name", proj_name);
selectOutput(getLang("SaveDialog"), "saveProject");
}
void saveProject(File selection) { // Save file dialog callback
if (selection == null) {
println("Save dialog was closed, canceled save.");
} else {
println("Saving to " + selection.getAbsolutePath());
saveJSONArray(project, selection.getAbsolutePath());
println("Construction saved!");
}
}
When I select the path, this is printed out to the console:
saveProject() could not be found
What is wrong with my code?

Using this test sketch worked:
JSONArray project = new JSONArray();
String proj_name = "test";
void saveProjectDialog() { // Shows a save file dialog
JSONObject header = new JSONObject();
header.setString("name", proj_name);
selectOutput(getLang("SaveDialog"), "saveProject");
}
void saveProject(File selection) { // Save file dialog callback
if (selection == null) {
println("Save dialog was closed, canceled save.");
} else {
println("Saving to " + selection.getAbsolutePath());
saveJSONArray(project, selection.getAbsolutePath());
println("Construction saved!");
}
}
void setup(){
saveProjectDialog();
}
String getLang(String s){
return s;
}
Double check the values proj_name and getLang() result.

Related

Execute Async Task Inside another Async Task

I am trying to call another async task inside an OnPostExecute. The 2nd task does not run at all it seems. I am unable to print anything from within to the logs.
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject json = new JSONObject(result);
JSONArray lignes = json.getJSONArray("lignes");
populatelist(lignes);
}
catch (JSONException e) {
}
}
}
The populatelist function fills an array. Inside this function, I try to call the 2nd async task to get values based on this list.
protected void populatelist(JSONArray lignes){
try {
for(int i=0;i<lignes.length(); i++) {
JSONObject jsonas = lignes.getJSONObject(i);
String fdesignation = jsonas.getString("designation");
String fqtecde = jsonas.getString("qtecde");
String fcode_produit = jsonas.getString("code");
InfoStock(fcode_produit);
items.add(new PickingListProduitItem(fdesignation,"",fqtecde, ""));
}
}
catch(Exception e){
}
}
InfoStock() is the function that is used to return additional from a web service.
protected void InfoStock(String code_produit){
String stockURL = "http://" + mSharedPreferences.getString(Constants.SERVER_IP,"")+"//rest/v2/produit/info/code/"+ code_produit + "?stock=true";
try {
if (mDownloader != null && mDownloader.getStatus() == AsyncTask.Status.RUNNING) {
mDownloader.cancel(true);
mPDialog.dismiss();
}
mPDialog = new ProgressDialog(getApplicationContext());
mDownloader = new XMLDownloader(getApplicationContext(),mPDialog);
byte[][] downloadResults = mDownloader.execute(stockURL).get();
// Read stock info.
String s = new String(downloadResults[0], StandardCharsets.UTF_8);
JSONObject resp = new JSONObject(s);
PrixStockJSONParser psj = new PrixStockJSONParser(resp);
mRepInfoStock = psj.getRepInfoStock();
mRepInfoPrix = psj.getRepInfoPrix();
} catch (Exception ex) {
}
}
I am trying to set a value in the array <> created in the OnPostExecute Method. However there is no error message and the array is not populated at all. Even if I try to print a log from the InfoStock function, it does nothing.
Any suggestions are welcome.

Data not loading after login / just after reshreshing page

I got an simple login on my page. After logging in I'm displaying data from a server, that is just shown after refreshing the page once.
Before I am getting an Error 500:
GET http://localhost:8080/getDesktop 500
angular.js:14800 Possibly unhandled rejection: ...
My AngularJS code is the following:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope, $http, $window, $timeout){
//Username
$scope.user = "";
//Desktop
$scope.storage = [];
//Get username
$http.get("/loggeduser", {transformResponse: function(response){
return JSON.stringify(response);
}
}).then(function(response) {
$scope.user = response.data.substring(1, response.data.length-1);
});
//Show Desktop
$http.get("/getDesktop").then(function(response){
for(var i = 0; i<response.data.length; i++){
$scope.storage[i] = {name: response.data[i]};
}
return;
});
});
Backend:
//Returns Desktop
#GetMapping("/getDesktop")
public ArrayList<String> getDesktop() throws Exception {
ArrayList<String> itemNames = new ArrayList<>();
if(kdxF.getUser() != null) {
itemNames = kdxF.showDesktop();
// Just a function to return the Elements in an ArrayList if Strings
// If user is logged in
}else {
throw new Exception("Not logged in!");
}
return itemNames;
}
And I get the message "Not logged in"
Okay, I solved it with a kinda ugly solution, but it works.
I'm constantly checking if the user is null, then loading the data.
//Returns Desktop
#GetMapping("/getDesktop")
public ArrayList<String> getDesktop() throws Exception {
ArrayList<String> itemNames = new ArrayList<>();
int kill = 0;
while(kdxF.getUser() == null) { // FIXME
if(kill == 500) {
break;
}else {
Thread.sleep(5);
kill++;
}
}
itemNames = kdxF.showDesktop();
return itemNames;
}
If you get a better suggestion please tell me. :)

Java, passing values between classes

Ok so I'm a noob at Java and this just got me.
I have a button that calls a class in which some background code runs to check if the tape drive is online, offline or busy.
Button Code:
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
Then I have my separate class file btnRunBackup.
public class btnRunBackup{
public void checkStatus(){
/*
Here I simply create a tempfile and run some
linux commands via getRuntime and print the
output to the tempfile
Then I call my second method passing the
absolute file path of the tempfile
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
Here I use BufferedReader to go through the
tempfile and look for as series of 3
different strings.
I use a if else if statement for flow control
depending on what string was found.
string 1 will call a new Jframe
if string 2, 3 or none of them are found the
is where I am stuck at
}
}
I want to return a String value back to btnRunBckActionPerformed().
The reason is lblRunBck will initially show no text at all but for instance the user clicks on the button and the resource happens to be busy then i want to run lblRunBck.setText(param); on lblRunBck while refusing the user permission to continue
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String text;
btnRunBackup runBackupObject = new btnRunBackup();
runBackupObject.checkStatus();
lblRunBck.setText("Errors go here");
}
here is my btnRunBackup class
public class btnRunBackup {
private String s;
public void checkStatus() {
String s, path = null;
Process p;
try{//try1
//create a temp file named tempfilexxx.tmp
File temp = File.createTempFile("tempfile", ".tmp");
//get file path
path = temp.getAbsolutePath();
System.out.println("checkStatus: " + path);
//write to tempfilexxx.tmp
BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
try{// try2
//set p = to the content of ls home
p = Runtime.getRuntime().exec("ls /home | grep ariel");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
//write content of p to tempfilexxx.tmp line by line
while ((s = br.readLine()) != null)
bw.write(s + "\n");
//close BufferedReader
br.close();
}catch (Exception e){} //END OF try2
//close BufferedWriter
bw.close();
/*
Now that we ran the 'mt -f /dev/nst0 status command under home we
will filter for one of the following strings
(for testing we will use ls -la /home and filter for ariel)
We will do this by calling the checkStatus method
*/
this.statusControl(path);
}catch(IOException e){
e.printStackTrace();
}// END OF try1
}// END OF listDir
//throws FileNotFoundException for bufferedReader if file not found
public void statusControl(String param) throws FileNotFoundException, IOException{
/*
On production code there will be 4 possible conditions:
1. ONLINE - ready to write (currently we will use ariel)
2. DR_OPEN - no tape available
3. /dev/nst0: Device or resource busy - resource bussy
4. If other than stated above give error 1000
*/
System.out.println("statusControl: " + param);
String ONLINE = "arielvz",
OPEN = "DR_OPEN",
BUSSY = "Device or resource busy",
sCurrentLine;
//Scan file line by line for one of the above options
BufferedReader br = new BufferedReader(new FileReader(param));
while ((sCurrentLine = br.readLine()) != null){
//Tape is online and ready for writing
if (sCurrentLine.contains(ONLINE)){
System.out.println("found ariel");
}
//There is no tape in the tape drive
else if (sCurrentLine.contains(OPEN)){
//lblRunBck should tell the user to put a tape in the drive
System.out.println("No tap in tape drive");
}
else if (sCurrentLine.contains(BUSSY)){
//lblRunBck should notify user that the resource is in use
System.out.println("Device or resource bussy");
}
else{
//Something unexpected happend
System.out.println("Error 1001: Please notify Administrator");
}
}
}//END OF statusControl
public String returnHandler(String param){
return param;
}
}
Maby This will make it more clear
If you want checkStatus to return a status, then do not make it returning nothing (a void function)
public class btnRunBackup {
private String s;
public void checkStatus() {
but make it returning error as a String like:
public class btnRunBackup {
private String s;
public String checkStatus() {
String error = null; // by default no error
... do whatever you need to find out the error
....
error = "error is: xxx ";
return error; // return null (no error ) or what you found
}
change you logic in you calling code to display what error have been returned by checkStatus
private void btnRunBckActionPerformed(java.awt.event.ActionEvent evt)
{
// TODO add your handling code here:
String error;
btnRunBackup runBackupObject = new btnRunBackup();
error = runBackupObject.checkStatus();
lblRunBck.setText(error == null ? "No error" : error);
}

NFC tag and php

I am new to NFC tags and am interested on how it work. I have bought a NFC tag and am able to write studentid to the tag. Now my problem is how to pass the student id to a php web service and check if this student has paid his/her meals before thy can proceed to the cafeteria when thy scan their student cards through my application.
Kindly anyone assist me on how i can do this. below is what i have done.
//reading the tag
private String readText(NdefRecord record) throws UnsupportedEncodingException {
byte[] payload = record.getPayload();
// Get the Text Encoding
String textEncoding = ((payload[0] & 128) == 0) ? "UTF-8" : "UTF-16";
// Get the Language Code
int languageCodeLength = payload[0] & 0063;
// Get the Text
return new String(payload, languageCodeLength + 1, payload.length - languageCodeLength - 1, textEncoding);
}
#Override
protected void onPostExecute(String result) {
if (result != null) {
//show the student id in a textedit
mTextView.setText(result);
//pass variable to the server and get contents. I want to pass the student id to the method
getstudentinfo(result);
}
}
void getstudentinfo(String studID) {
//get connection to the server using http request
httpclient=new DefaultHttpClient();
httppost= new HttpPost("http://myip/getStudentBl.php?studID="+ studID);
try{
response = getThreadSafeClient().execute(httppost);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost, responseHandler);
//checking the response and info the user
runOnUiThread(new Runnable() {
public void run() {
dialog.dismiss();
}
});
//if the user is found
if(response.equalsIgnoreCase("Student Found")){
runOnUiThread(new Runnable() {
public void run() {
//Toast.makeText(MainActivity.this,"Saved Successfull", Toast.LENGTH_SHORT).show();
stdBalance.setText("Student Balance " + response);
}
});
//show the dashboard screen
startActivity(new Intent(MainActivity.this, MainActivity.class));
}else if(response.equalsIgnoreCase("No Record")){
//show error results
showAlert();
}
//end try catch
}catch(Exception e){
dialog.dismiss();
System.out.println("Exception : " + e.getMessage());
}
}
From my understanding, with android readers at a minimum, if the tag holds an URL, it will automatically load the browser and go to the URL (no asking if you want to open the app nor if you want to go to the URL). You should be able to just put the student_id as a query string and use it in a page.
Looks here to have an exemple of an NDEF implementation : Github repo
In the main activity you will have to modify the
#Override
public void ndefDataRead(String ndefData) {
demoTextView.setText(ndefData);
}
to call your getstudentinfo(String studID) methods and it might work

Windows application with Auto-complete using tab of unix machine files and directories

Unix / Linux support auto-complete of files and directories when pressing "tab".
I need to create this ability in my windows application. I have a text field for user input of file name, which I want to respond to a "tab" press like it will do when we're in a unix console:
If there is one option - Auto-complete.
Some options - show a list of the options.
No options - nada.
For my SSH connection to my unix machine I use the ch.ethz.ssh API.
Is there a way to do so?
First you want to have a text field without focus cycling, and tab suppression:
jTextField1.setFocusCycleRoot(true);
jTextField1.setFocusTraversalKeysEnabled(false);
Then a data model for the files (here local directory, but SSH is likewise):
private File dir = new File("C:/Work");
private String typedPrefix = null;
private List<String> filesWithPrefix = new ArrayList<>();
Then a key pressed handling for the TAB:
Consume the event.
Get the prefix upto the caret for searching file names.
If you merely need to restrict already found file names, so do, otherwise physical search them.
Look for the longest common prefix in the file names. Display that.
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
System.out.println("KeyPressed " + evt);
if (evt.getKeyCode() == KeyEvent.VK_TAB) {
evt.consume();
int caretPos = jTextField1.getCaretPosition();
try {
final String newPrefix = jTextField1.getText(0, caretPos);
System.out.println("newPrefix: " + newPrefix);
if (!newPrefix.isEmpty()) {
if (typedPrefix == null || !newPrefix.startsWith(typedPrefix)) {
// Must physically reload possible values:
String[] fileNames = dir.list(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith(newPrefix);
}
});
filesWithPrefix.clear();
Collections.addAll(filesWithPrefix, fileNames);
typedPrefix = newPrefix;
} else {
// Can reduce prior selection:
for (ListIterator<String> it = filesWithPrefix.listIterator(); it.hasNext(); ) {
String fileName = it.next();
if (!fileName.startsWith(newPrefix)) {
it.remove();
}
}
typedPrefix = newPrefix;
}
System.out.println("filesWithPrefix: " +filesWithPrefix);
if (!filesWithPrefix.isEmpty()) {
// Find longest common prefix:
String longestCommonPrefix = null;
for (String fileName : filesWithPrefix) {
if (longestCommonPrefix == null) {
longestCommonPrefix = fileName;
} else {
while (!fileName.startsWith(longestCommonPrefix)) {
longestCommonPrefix = longestCommonPrefix.substring(0, longestCommonPrefix.length() - 1);
}
}
}
if (longestCommonPrefix.length() > typedPrefix.length()) {
jTextField1.setText(longestCommonPrefix);
jTextField1.setCaretPosition(longestCommonPrefix.length());
typedPrefix = longestCommonPrefix;
}
if (filesWithPrefix.size() > 1) {
// Show popup:
;;;
} else if (filesWithPrefix.size() == 1) {
// File selected:
System.beep();
}
}
}
} catch (BadLocationException ex) {
Logger.getLogger(TabsJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
What is missing is the display of the ambiguous file names. Popup menu would be nice, wouldn't it?
Popup:
// Show popup:
JPopupMenu popup = new JPopupMenu();
for (String fileName : filesWithPrefix) {
popup.add(new AbstractAction(fileName) {
#Override
public void actionPerformed(ActionEvent e) {
jTextField1.setText(e.getActionCommand());
}
});
}
Point pt = jTextField1.getCaret().getMagicCaretPosition();
popup.show(jTextField1, pt.x, pt.y + 5);

Categories