Saving the values of a string to another class and retrieving it - java

I am currently trying to save the values of a string to another class file in JAVA called Memory.JAVA. The reason why I am doing this is because variables are not saved outside the Try - Catch Blocks. Therefore I initiate the class in the try catch block by using this code:
Memory mem = new Memory();
And then when I want to save a string, I use the following:
mem.brother1ID = "Whatever";
The reason why I am not creating it as a new String is because in the Memory class, I have already initiated this string. To test that this has been saved, I have used System.out.println to print out the result which in this case was "Whatever" but when I try to get the same result printed out in the same class, I get the result "null". Does anyone have any suggestions regarding my issue? Please feel free to comment below. Thanks!
UPDATE:
Some code posted below:
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where firstName= ? OR lastname = ?";
pst=conn.prepareStatement(sql);
pst.setString(1, searchField.getText());
pst.setString(2, searchField.getText());
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
mem.brother1ID = rs.getString("brother1ID");
mem.brother2ID = rs.getString("brother2ID");
mem.brother3ID = rs.getString("brother3ID");
mem.brother4ID = rs.getString("brother4ID");
mem.brother5ID = rs.getString("brother5ID");
mem.sister1ID = rs.getString("sister1ID");
mem.sister2ID = rs.getString("sister2ID");
mem.sister3ID = rs.getString("sister3ID");
mem.sister4ID = rs.getString("sister4ID");
mem.sister5ID = rs.getString("sister5ID");
mem.fatherID = rs.getString("fatherID");
mem.motherID = rs.getString("motherID");
System.out.println(mem.brother1ID);
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
And this is when I try to get the same results of System.out.println as before:
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
pst.setString(1, IDNO);
rs=pst.executeQuery();
if(rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String placeOfResidence = rs.getString("placeOfResidence");
String employmentStatus = rs.getString("employmentStatus");
String currentEmployer = rs.getString("currentEmployer");
String taxStatus = rs.getString("taxStatus");
String dateOfBirth = rs.getString("dateOfBirth");
String mother = rs.getString("mother");
String father = rs.getString("father");
String brother1 = rs.getString("brother1");
String brother2 = rs.getString("brother2");
String brother3 = rs.getString("brother3");
String brother4 = rs.getString("brother4");
String brother5 = rs.getString("brother5");
String sister1 = rs.getString("sister1");
String sister2 = rs.getString("sister2");
String sister3 = rs.getString("sister3");
String sister4 = rs.getString("sister4");
String sister5 = rs.getString("sister5");
System.out.println(firstName + " " + lastName);
firstNameField.setText(firstName);
lastNameField.setText(lastName);
placeOfResidenceField.setText(placeOfResidence);
employmentStatusField.setText(employmentStatus);
currentEmployerField.setText(currentEmployer);
taxStatusField.setText(taxStatus);
dateOfBirthField.setText(dateOfBirth);
motherField.setText(mother);
fatherField.setText(father);
brothersField1.setText(brother1);
brothersField2.setText(brother2);
brothersField3.setText(brother3);
brothersField4.setText(brother4);
brothersField5.setText(brother5);
sisterField1.setText(sister1);
sisterField2.setText(sister2);
sisterField3.setText(sister3);
sisterField4.setText(sister4);
sisterField5.setText(sister5);
}
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}

The reason the value brother1ID in your Memory object is null is because you're using a new instance of that object.
I strongly recommend you read up on how object instances are scoped in Java, and what it means to create a new instance, versus using an existing one.
For example, when you do this:
Memory mem = new Memory();
mem.brother1ID = "1234";
mem = new Memory();
System.out.println(mem.brother1ID);
The value printed will be null. This is because you're using a new instance of that class. If you wanted to maintain the values throughout multiple method calls, your best bet might be to save the Memory object as an instance variable of whatever class contains the methods you've shown. i.e.:
private Memory memory = new Memory();
...
private void searchFieldKeyReleased(java.awt.event.KeyEvent evt) {
// Use 'this.memory'
this.memory.brother1ID = "1234";
//(or)
System.out.println(this.memory.brother1ID);
}
private void brotherViewButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// Use 'this.memory'
}

Please look at here
try {
Memory mem = new Memory();
String sql = "select * from userInfo where id=?";
pst=conn.prepareStatement(sql);
String IDNO = mem.brother1ID;
System.out.println(IDNO);
You are creating the object of Memory and not setting any value.
then you are trying to print the brotherId which will be null, all String variables will be initialised to null, that is why you are getting 'null'. what you can do is put the printing statement out of the try catch block at he bottom , if there are any records in your database, it will print out the last records brotherId.

Related

Java REST API upon building string after get request replace null values with string vale

I am currently working on a Java application where I have an AsyncTask function get data from an API, then have a line reader and string builder create a large string, which I then pass to the postExecute function where I convert that string into a JSON object. I have tried creating a function that takes the string before post execute and replaces all null with "N/A", I have also tried checking in the String builder function but neither seem to make any changes to the null value. Here is an example of what the code looks like. I believe the error occurs when The string is converted into the JSON Object. This is a school project and I am not allowed to use external libraries.
String Builder:
BufferedReader reader = new BufferedReader(new InputStreamReader(httpClient.getInputStream()));
StringBuilder builder = new StringBuilder();
String line;
while((line = reader.readLine()) != null) {
if (line.contains(null) || line.contains(""))
line += "N/A";
else
continue;
builder.append(line + "\n");
}
replaceNull Function:
public String removeUnwantedVal(String message) {
if (message.contains("null")) {
String replacement = "N/A";
message.replaceAll(null, replacement);
}
return message;
}
Post Execute JSON Object:
protected void onPostExecute(String message) {
TextView tv = findViewById(R.id.display);
System.out.println(message);
try {
JSONObject jsonAddress = new JSONObject(message);
// DISPLAY INFORMATION
String requesterIP = jsonAddress.getString("requester-ip");
String execTime = jsonAddress.getString("execution-time");
ipInfo.setIPAndTime(requesterIP, execTime);
// GEOGRAPHY
JSONObject geo = jsonAddress.getJSONObject("geo");
String countryName = geo.getString("country-name");
String capital = geo.getString("capital");
String iso = geo.getString("country-iso-code");
String city = geo.getString("city");
double longitude = geo.getDouble("longitude");
double latitude = geo.getDouble("latitude");
location = new Location(countryName, capital, iso, city, longitude, latitude);
// CURRENCY
JSONObject currency = jsonAddress.getJSONObject("currency");
String currencyNativeName = currency.getString("native-name");
String currencyCode = currency.getString("code");
String currencyName = currency.getString("name");
String currencySymbol = currency.getString("symbol");
Currency = new Currency(currencyNativeName, currencyCode, currencyName, currencySymbol);
// ASN
JSONObject asn = jsonAddress.getJSONObject("asn");
String asnName = asn.getString("name");
String asnDomain = asn.getString("domain");
String asnOrganization = asn.getString("organization");
String asnCode = asn.getString("asn");
String asnType = asn.getString("type");
ASN = new ASN(asnName, asnDomain, asnOrganization, asnCode, asnType);
// TIMEZONE
JSONObject timezone = jsonAddress.getJSONObject("timezone");
String timezoneName = timezone.getString("microsoft-name");
String dateTime = timezone.getString("date-time");
String ianaName = timezone.getString("iana-name");
Timezone = new Timezone(timezoneName, dateTime, ianaName);
// SECURITY
JSONObject security = jsonAddress.getJSONObject("security");
boolean isCrawler = security.getBoolean("is-crawler");
boolean isProxy = security.getBoolean("is-proxy");
boolean isTor = security.getBoolean("is-tor");
Security = new Security(isCrawler, isProxy, isTor);
container = new IPContainer(ipInfo, Currency, location, Security, ASN, Timezone);
tv.setText(container.displayGeneral());
} catch (JSONException e) {
tv.setText(e.toString());
e.printStackTrace();
}
}
I have resolved the issue. When I was getting the code I thought that null values could not be displayed, this was incorrect. The problem was that I was trying to create an object out of null, sometimes the value came back as null instead of as an object. Sorry, beginner coder :)

Validation for Excel sheet using core java

I have built core java code to read excel data and push into database. And it works fine. Now I want to add some validatation checks to the excel sheet. I am not able to do that. Consider I have some columns which are SettleDate,TradeDate, TradeID, IFStatus, IFVersion, IFDate, IFTime. I want to do below vlidation rules.
Settle should not be more thatn TradeDate.
TradID should be 14 letteres.
IFStatus, IFVersion, IFDate, IFTime should be blank
Below is my code........
try {
Class forName = Class.forName("com.sybase.jdbc2.jdbc.SybDriver");
Connection con = null;
con = DriverManager.getConnection("jdbc:sybase:Tds:tkbgssvt1:4105", "kauai_rwu", "rwu_kauai");
System.out.println("Database connected to Sybase..");
con.setAutoCommit(false);
PreparedStatement pstm = null;
FileInputStream input = new FileInputStream(
"C:\\Users\\suresnar\\Desktop\\Mizu_FGloss\\Kauai_IN_Table_test.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(input);
XSSFSheet sheet = workbook.getSheetAt(0);
Row row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = (Row) sheet.getRow(i);
DataFormatter formatter = new DataFormatter();
String TradeAction = formatter.formatCellValue(row.getCell(0));
String TradeID = formatter.formatCellValue(row.getCell(1));
String Version = formatter.formatCellValue(row.getCell(2));
String TradeType = formatter.formatCellValue(row.getCell(3));
String Book = formatter.formatCellValue(row.getCell(4));
String Direction = row.getCell(5).getStringCellValue();
String SafekeepFlag = row.getCell(6).getStringCellValue();
String OurSettlePlace = formatter.formatCellValue(row.getCell(7));
String OurSettleDepot = row.getCell(8).getStringCellValue();
String TheirSettlePlace = row.getCell(9).getStringCellValue();
String TheirSettleDepot = row.getCell(10).getStringCellValue();
String BrokerCode = row.getCell(11).getStringCellValue();
String CustomerCode = formatter.formatCellValue(row.getCell(12));
String ProductCode = formatter.formatCellValue(row.getCell(13));
String TradeDate = formatter.formatCellValue(row.getCell(14));
String TradeTime = formatter.formatCellValue(row.getCell(15));
String CreditPerson = row.getCell(16).getStringCellValue();
String Quantity = formatter.formatCellValue(row.getCell(17));
String Factor = formatter.formatCellValue(row.getCell(18));
String ActualQuantity = formatter.formatCellValue(row.getCell(19));
String SettleDate = formatter.formatCellValue(row.getCell(20));
String Price = formatter.formatCellValue(row.getCell(21));
String TradeCcy = row.getCell(22).getStringCellValue();
String TradeValue = formatter.formatCellValue(row.getCell(23));
String AccDays = formatter.formatCellValue(row.getCell(24));
String TradeAICcy = formatter.formatCellValue(row.getCell(25));
String TradeAI = formatter.formatCellValue(row.getCell(26));
String SettleAmt = formatter.formatCellValue(row.getCell(27));
String RateCalc = formatter.formatCellValue(row.getCell(28));
String FxRate = formatter.formatCellValue(row.getCell(29));
String SettleCcy = formatter.formatCellValue(row.getCell(30));
String SettleAmtInFX = formatter.formatCellValue(row.getCell(31));
String Memo1 = row.getCell(32).getStringCellValue();
String Memo2 = row.getCell(33).getStringCellValue();
String Memo3 = row.getCell(34).getStringCellValue();
String Memo4 = row.getCell(35).getStringCellValue();
String Memo5 = row.getCell(36).getStringCellValue();
String Remark1 = row.getCell(37).getStringCellValue();
String Remark2 = row.getCell(38).getStringCellValue();
String SelfStBrCode = formatter.formatCellValue(row.getCell(39));
String SelfStBrSubCode = formatter.formatCellValue(row.getCell(40));
String CustStBrCode = formatter.formatCellValue(row.getCell(41));
String CustStClCode = formatter.formatCellValue(row.getCell(42));
String CustStSubCode = formatter.formatCellValue(row.getCell(43));
String DiscretionFlg = formatter.formatCellValue(row.getCell(44));
String InputTime = formatter.formatCellValue(row.getCell(45));
String UpdateTime = formatter.formatCellValue(row.getCell(46));
String IFStatus = formatter.formatCellValue(row.getCell(47));
String IFVersion = formatter.formatCellValue(row.getCell(48));
String IFDate = formatter.formatCellValue(row.getCell(49));
String IFTime = formatter.formatCellValue(row.getCell(50));
String AzIFStatus = formatter.formatCellValue(row.getCell(51));
String AzIFVersion = formatter.formatCellValue(row.getCell(52));
String AzIFTime = formatter.formatCellValue(row.getCell(53));
String AzCKTime = formatter.formatCellValue(row.getCell(54));
String sql = "INSERT INTO FB_KAUAI_IN (\"my query\")";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Imported rows " + i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
// Handle errors for Class.forName
e.printStackTrace();
}
Can anyone help me please?
your help is much appriciated...
Thanks,
Suresh N
I guess there's a couple of different ways to do this:
if you really own the Excel file and you create it. You can create your own formula to "validate" the cells you want.
you can create different classes for each type you want to validate and each "cell" will have it's own class/validation
you can manually create validation and apply for each field you want to validate (directly in java, per "String" you get from the
excel file).
since you (really) should change the SQL query to Hibernate for example, after that you can use hibernate validators (before inserting into db).

How to debug a JOption error message in Java?

I am doing a school management system project, everything is good except when I try to click the save button it returns the JOption error message that phone must be integer although it is already. I must say I have a similar form for teacher registration and that one works. How can it be?
private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {
try{
int day = Integer.valueOf((String)jComboBoxDay.getSelectedItem());
int month = Integer.valueOf((String)jComboBoxMonth.getSelectedItem());
int year = Integer.valueOf((String)jComboBoxYear.getSelectedItem());
String birthDate = ""+day+month+year;
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
String address = jTextFieldAddress.getText();
String email = jTextFieldEmail.getText();
int phoneNumber = Integer.parseInt((jTextFieldPhoneNumber).getText());
String gender = (String)jComboBoxGender.getSelectedItem();
String religion = jTextFieldReligion.getText();
String contactTeacher =jTextFieldContactTeacher.getText();
int contactPhoneNumber = Integer.parseInt((jTextFieldContactPhoneNumber).getText());
int momID = Integer.parseInt((jTextFieldMotherID).getText());
int fatherID = Integer.parseInt((jTextFieldFatherID).getText());
Reset();
Students student = new Students(birthDate,firstName,lastName,address, email,phoneNumber,gender,religion,contactTeacher,contactPhoneNumber,momID,fatherID);
studentsControl.createStudents(student);
loadTable();
}
catch (NumberFormatException exception)
{
JOptionPane.showMessageDialog(null,"Phone must be an integer ","Error",JOptionPane.ERROR_MESSAGE);
jTextFieldPhoneNumber.setText("");
}
}
You're getting the month description from jComboBoxMonth object.
Try getting the index instead by calling getSelectedItem method and adding 1.

usertype value showing null in android

Hi In This code I am getting response by using json for that created one map in that I mention key and value.Now That value storing in one variable for that I wrote like this
String usertype = usertypeMap.get(user_type[i]);
But The usertype showing null can any one please help me where I did mistake.
java
String username1 = usname.getText().toString();
String password = pword.getText().toString();
queryString = "username=" + username1 + "&password="
+ password ;
String user_type1 = DatabaseUtility.executeQueryPhp("usertype",queryString);
System.out.print(user_type1);
try
{
JSONArray JA = new JSONArray(user_type1);
username = new String[JA.length()];
user_type = new String[JA.length()];
for(int i=0;i<JA.length();i++)
{
username[i] = JA.getJSONObject(i).getString("username");
user_type[i] = JA.getJSONObject(i).getString("user_type");
usertypeMap.put(username[i],user_type[i]);
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
e.printStackTrace();
}
String usertype = usertypeMap.get(user_type[i]);
try{
queryString = "username=" + username1 + "&password="
+ password +"&user_type="+usertype;
final String data = DatabaseUtility.executeQueryPhp("login",queryString);
You are getting value from the value
Map is(KEY,VALUE). In your code, key is username[i] value is user_type[i]. But you getting the value like this
String usertype = usertypeMap.get(user_type[i]);
try using like this
String usertype = usertypeMap.get(username[i]);

I am not able to read the records with null date field in MySQL using java?

here is the code
private ResultSet rsResult;
try
{
rsResult = DBProcess.statement.executeQuery("SELECT * FROM patients");
}//end try
catch (SQLException ex)
{
out.println("<I>exception</I><br>");
Logger.getLogger(cUserLogin.class.getName()).log(Level.SEVERE, null, ex);
}//end catch
while (rsResult.next())
{
BigDecimal bdPatientID = rsResult.getBigDecimal("patient_id");
String strFirstname = rsResult.getString("first_name");
String strLastname = rsResult.getString("last_name");
String strMiddlename = rsResult.getString("middle_name");
String strGeneder = rsResult.getString("gender");
String strMeritalStatus = rsResult.getString("marital_status");
BigDecimal bdPhoneNo = rsResult.getBigDecimal("phone_no");
String strAddress = rsResult.getString("address");
String strDOB = rsResult.getDate("birth_dt").toString();
String strDOE = rsResult.getDate("dt_of_exam").toString();
}
i am not able to read records that are present after a recode which holds the null DATE field what can i do to get raid of this....
If rsResult.getDate("birth_dt") returns null, than calling toString() would cause a NullPointerException
You could rewrite this as:
String strDOB = rsResult.getDate("birth_dt") == null ? "" : rsResult.getDate("birth_dt").toString();

Categories

Resources