How to get and set a JComboBox? - java

What I have attached below is a copy/paste of my attempt to get and set a series of JComboBox's. hName and hAddress are dealing with a JTextField, so those are working fine, but for some reason I can get from my combo box's, but I can't set to them and including a call to initialiseDatabase() will cause the program to fail.
infoHolder is a resultset and dbstatement is a statement. The database is connecting fine, and the table inside of it is prepared and accessible, it's just the setting of the combobox's that's the issue.
Any help appreciated, and apologies if I'm missing something fundamental in the code below above.
public void initialiseDatabase()
{
try
{
infoHolder = dBStatement.executeQuery("SELECT * FROM House");
infoHolder.next();
hName = infoHolder.getString("Name");
hAddress = infoHolder.getString("Address");
numRooms = infoHolder.getInt("numRooms");
Type = infoHolder.getString("Type");
charge = infoHolder.getString("roomCharge");
Access = infoHolder.getString("dAccess");
Info = infoHolder.getString("oInfo");
houseText.setText(" " +hName);
addressText.setText(" " +hAddress);
roomNumber.setSelectedItem(" " +numRooms);
roomType.setSelectedItem(" " +Type);
chargeRoom.setSelectedItem(" " +charge);
access.setSelectedItem(" " +Access);
oInfo.setText(" " +Info);
current2 = 1;
infoHolder.close();
}
catch(SQLException e8) {JOptionPane.showMessageDialog(this, "Database failed to initialise!", "Message Dialog", JOptionPane.INFORMATION_MESSAGE);;}
}

Related

bitcoinJ get transaction value

I downloaded a lot of blockchain data using https://bitcoin.org, I took some file and I try to analyse it with bitcoinj library.
I would like to get information from every transaction:
-who send bitcoins,
-how much,
-who receive bitcoins.
I use:
<dependency>
<groupId>org.bitcoinj</groupId>
<artifactId>bitcoinj-core</artifactId>
<version>0.15.10</version>
</dependency>
I have a code:
NetworkParameters np = new MainNetParams();
Context.getOrCreate(MainNetParams.get());
BlockFileLoader loader = new BlockFileLoader(np,List.of(new File("test/resources/blk00450.dat")));
for (Block block : loader) {
for (Transaction tx : block.getTransactions()) {
System.out.println("Transaction ID" + tx.getTxId().toString());
for (TransactionInput ti : tx.getInputs()) {
// how to get wallet addresses of inputs?
}
// this code works for 99% of transactions but for some throws exceptions
for (TransactionOutput to : tx.getOutputs()) {
// sometimes this line throws: org.bitcoinj.script.ScriptException: Cannot cast this script to an address
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
System.out.println("out value:" + to.getValue().toString());
}
}
}
Can you share some snippet that will work for all transactions in the blockchain?
There are at least two type of transaction, P2PKH and P2SH.
Your code would work well with P2PKH, but wouldn not work with P2SH.
You can change the line from:
System.out.println("out address:" + to.getScriptPubKey().getToAddress(np));
to:
System.out.println("out address:" + to.getAddressFromP2PKHScript(np)!=null?to.getAddressFromP2PKHScript(np):to.getAddressFromP2SH(np));
The API of Bitcoin says the methods getAddressFromP2PKHScript() and getAddressFromP2SH() are deprecated, and I have not find suitable method.
However, P2SH means "Pay to Script Hash", which means it could contain two or more public keys to support multi-signature. Moreover, getAddressFromP2SH() returns only one address, perhaps this is the reason why it is deprecated.
I also wrote a convinient method to check the inputs and outputs of a block:
private void printCoinValueInOut(Block block) {
Coin blockInputSum = Coin.ZERO;
Coin blockOutputSum = Coin.ZERO;
System.out.println("--------------------Block["+block.getHashAsString()+"]------"+block.getPrevBlockHash()+"------------------------");
for(Transaction tx : block.getTransactions()) {
Coin txInputSum = tx.getOutputSum();
Coin txOutputSum = tx.getOutputSum();
blockInputSum = blockInputSum.add(txInputSum);
blockOutputSum = blockOutputSum.add(txOutputSum);
System.out.println("Tx["+tx.getTxId()+"]:\t" + txInputSum + "(satoshi) IN, " + txOutputSum + "(satoshi) OUT.");
}
System.out.println("Block total:\t" + blockInputSum + "(satoshi) IN, " + blockOutputSum + "(satoshi) OUT. \n");
}

JT400 ProgramCall's run() method is not returning any result

I am new to JT400. I am trying to invoke a test program in AS400 through JT400. Here is my code
public class TestRpg {
public static void main(String[] args){
try{
AS400 sys=new AS400("mydomain","username","password");
String number="asdf <= Return value from Java Input";
String lnsts="";
String amount="";
String lnofcd="";
AS400Text txt80 = new AS400Text(80);
AS400Text txt50 = new AS400Text(50);
ProgramParameter[] parmList = new ProgramParameter[4];
parmList[0] = new ProgramParameter( txt80.toBytes(number),80);
parmList[1] = new ProgramParameter( txt50.toBytes(lnsts),50);
parmList[2] = new ProgramParameter( txt80.toBytes(amount),80);
parmList[3] = new ProgramParameter( txt50.toBytes(lnofcd),50);
ProgramCall pgm = new ProgramCall(sys,"/QSYS.LIB/mylib.LIB/testrpg.PGM",parmList);
if (pgm.run()!=true) {
System.out.println("executed");
}else{
System.out.println("Output Data 0: " + (String)txt80.toObject( parmList[0].getOutputData() ) );
System.out.println("Output Data 1: " + (String)txt50.toObject( parmList[1].getOutputData() ) );
System.out.println("Output Data 2: " + (String)txt80.toObject( parmList[2].getOutputData() ) );
System.out.println("Output Data 3: " + (String)txt50.toObject( parmList[3].getOutputData() ) );
sys.disconnectService(AS400.COMMAND);
}
AS400Message[] messageList = pgm.getMessageList();
System.out.println(messageList.length);
for (int i=0; i < messageList.length; i++)
{
System.out.print ( messageList[i].getID() );
System.out.print ( ": " );
System.out.println( messageList[i].getText() );
}
sys.disconnectService(AS400.COMMAND);
}catch(Exception e) {
System.out.println(e.toString());
}
}
}
I had debug the code it's not giving any response after executing
pgm.run(). It is not even showing any exception. Programme is just holding at pgm.run() and not returning any thing.
As per the comments I got, I want to include the scenario I am trying to work on. In AS400 when we execute the testrpg.pgm program, it displays a screen with four input fields and some function keys to perform operations. My intention is to invoke f2 function key of that program from JT400. Is the approach I am following is the right way? Please suggest me
All program calls happen in batch so your program is most likely in MSGW on the server. Find it with wrkactjob and investigate the message it is waiting for, and give the appropriate action.
This is typically due to incorrectly formed parameters.
This is a common misunderstanding, so just for clarification for other readers:
Calling a Cobol/RPG program from Java is batch, just the same as calling the Cobol/RPG program from a Cobol/RPG/CL.
How to begin: Create a program which you can call from CL:
... declare and fill MYFIELD1, MYFIELD2 ...
CALL PGM(MYPGM) PARM(&MYFIELD1 &MYFIELD2)
...
If this works, it will also work from Java using jt400, if you:
call the right AS400 using correct credentials
call the right program in the right library
use the right number and lentgh of parameters
In case of crash as described (waiting forever), DSPMSG QSYSOPR will show an open message, like "MCH0801 = wrong number of parameters". D=Dump will create a spoolfile where you see which incoming parameters are filled with which content, or you see "undefined".

phonegap displaying text in native textbox

I'm making an android app which uses bluetooth using phonegap and I'm having issues handling code because it get's called every 100ms.
I want to try if the issue occurs because my phonegap javascript code is to long causing delays.
To try this I want to dispaly the received message using a native textbox.
Is this possible? and How would I do this?
Thanks
Martijn
PS: I've tried using Toast but since I want to change the displayed value every 100ms this doesn't work.
Code
upon receiving a message this is the order the code is processed
bytes = mmInStream.read(buffer);
s_message = new String(buffer, 0, bytes);
String[] strArray = s_message.split(",");
mHandleReceivedThread = new HandleReceivedThread(strArray);
mHandleReceivedThread.start();
In the HandleReceivedThread:
if(strArrayReceived[0].startsWith("Pressure"))
{
if(strArrayReceived[1].contains("Pressure"))
{
double Pressure = Double.parseDouble(strArrayReceived[1].replace("Pressure", ""));
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
Log.e(TAG, "Message fail: " + strArrayReceived[1] );
}
else
{
double Pressure = Double.parseDouble(strArrayReceived[1]
double PressureResult = Pressure/10;
String PressureValue = String.valueOf(PressureResult);
webView.sendJavascript("PressureValue = " + Pressure + ";");
webView.sendJavascript("document.getElementById('Pressure').innerHTML = " + PressureValue + ";");
}
}
this is basically what happens.
And this happens every 100ms , and for some reason the displaying of the Value has lag and sometimes the received message (which should be "Pressure,1500" , or a different value) is Pressure,1500Pressure , causing errors (which I've managed to fix). but this still isn't optimal.
The message is send correctly and if I use a simple chat app they are received correctly.
if there is anything else I should supply , just ask ;-)

Apache Commons - NNTP - "Article To List" - AWT

I am currently using Apache Commons Net to develop my own NNTP reader. Using the tutorial available I was able to use some of their code to allow me to get articles back.
The Code I am using from NNTP Section -
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
I need to take the articles and turn them into a List type so I can send them to AWT using something like this -
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
My Entire code Base for this section is -
public void GetThreadList(String Search) throws SocketException, IOException {
String hostname = USE_NET_HOST;
String newsgroup = Search;
NNTPClient client = new NNTPClient();
client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
client.connect(hostname);
client.authenticate(USER_NAME, PASS_WORD);
if(!client.authenticate(USER_NAME, PASS_WORD)) {
System.out.println("Authentication failed for user " + USER_NAME + "!");
System.exit(1);
}
String fmt[] = client.listOverviewFmt();
if (fmt != null) {
System.out.println("LIST OVERVIEW.FMT:");
for(String s : fmt) {
System.out.println(s);
}
} else {
System.out.println("Failed to get OVERVIEW.FMT");
}
NewsgroupInfo group = new NewsgroupInfo();
client.selectNewsgroup(newsgroup, group);
long lowArticleNumber = group.getFirstArticleLong();
long highArticleNumber = lowArticleNumber + 5000;
System.out.println("Retrieving articles between [" + lowArticleNumber + "] and [" + highArticleNumber + "]");
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
System.out.println("Building message thread tree...");
Threader threader = new Threader();
Article root = (Article)threader.thread(articles);
Article.printThread(root, 0);
try {
if (client.isConnected()) {
client.disconnect();
}
}
catch (IOException e) {
System.err.println("Error disconnecting from server.");
e.printStackTrace();
}
}
and -
public void CreateFrame() throws SocketException, IOException {
// Make a new program view
Frame f = new Frame("NNTP Reader");
// Pick my layout
f.setLayout(new GridLayout());
// Set the size
f.setSize(H_SIZE, V_SIZE);
// Make it resizable
f.setResizable(true);
//Create the menubar
f.setMenuBar(CreateMenu());
// Create the lists
UseNetController b = new UseNetController(NEWS_SERVER_CREDS);
String dog = "*";
List x = (List) b.GetGroupList(dog);
f.add(CreateList(x));
//f.add(CreateList(y));
// Add Listeners
f = CreateListeners(f);
// Show the program
f.setVisible(true);
}
I just want to take my list of returned news articles and send them to the display in AWT. Can any one explain to me how to turn those Articles into a list?
Welcome to the DIY newsreader club. I'm not sure if you are trying to get a list of newsgroups on the server, or articles.You have already have your Articles in an Iterable Collection. Iterate through it appending what you want in the list from each article. You probably aren't going to want to display the whole article body in a list view. More likely the message id, subject, author or date (or combination as a string). For example for a List of just subjects:
...
Iterable<Article> articles = client.iterateArticleInfo(lowArticleNumber, highArticleNumber);
Iterator<Article> it = articles.iterator();
while(it.hasNext()) {
Article thisone = it.next();
MyList.add(thisone.getSubject());
//MyList should have been declared up there somewhere ^^^ and
//your GetThreadList method must include List in the declaration
}
return MyList;
...
My strategy has been to retrieve the articles via an iterator in to an SQLite database with the body, subject, references etc. stored in fields. Then you can create a list sorted just how you want, with a link by primary key to retrieve what you need for individual articles as you display them. Another strategy would be an array of message_ids or article numbers and fetch each one individually from the news server as required. Have fun - particularly when you are coding for Android and want to display a list of threaded messages in the correct sequence with suitable indents and markers ;). In fact, you can learn a lot by looking at the open source Groundhog newsreader project (to which I am eternally grateful).
http://bazaar.launchpad.net/~juanjux/groundhog/trunk/files/head:/GroundhogReader/src/com/almarsoft/GroundhogReader

Intent.getIntExtra() behaviour changes on a virtual device and on a real device

I have the below code and on my computer via Eclipse virtual device it works fine. But when installed on a real life phone it always reverts to the else statement.
This activity does not always get passed a value and if it is not I want a random record to appear. Thank you for any help or advice and time taken to read.
searchId = getIntent().getIntExtra("EMPLOYEE_ID", 0);
if(searchId > 0){
Query="SELECT * FROM " + DB_TABLE +" ORDER BY RANDOM() LIMIT 1";
Log.v("STANDARD RANDOM", "Was run");
}
else{
Query ="SELECT * FROM " + DB_TABLE +" WHERE _id=" + searchId + "";
Log.v("FROM SEARCH PAGE", "Was run");
}
Not sure if this fixes your problem. But according to the documentation, your code is not correct:
The name must include a package prefix, for example the app com.android.contacts would use names like "com.android.contacts.ShowAll".
Taken from Intent.putExtra.
You are using "EMPLOYEE_ID", without a package prefix, but you must include one!

Categories