cannot find symbol ActionListener and try catch - try-catch

I have a problem w my applet: shortly speaking, I want to "take" the variable curreny which is taken from xml and print it when I click on the button OK. The error I get is: error: cannot find symbol curreny. The problem is not importing variable from xml, because I checked separately if it works.
Sorry for the messy code, I'm new to java. All the neccessary packages are imported in the original source, but i didnt put it here just to make the code shorter. EDIT: I deleted part of the code consisting GUI to make it shorter, as you suggested.
public class App2 extends Applet implements ActionListener {
TextField T1 = new TextField();
Label L1 = new Label();
/* GUI code here */
public void actionPerformed(ActionEvent ae)
{
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document xmlDocument = db.parse(new URL("http://www.nbp.pl/kursy/xml/LastA.xml").openStream());
xmlDocument.getDocumentElement().normalize();
XPath xPath = XPathFactory.newInstance().newXPath();
String expression = "/tabela_kursow/pozycja[3]/kurs_sredni";
// System.out.println(expression);
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
// System.out.println(nodeList.item(i).getFirstChild().getNodeValue());
String kurs_dolara = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_dolara = Double.parseDouble(kurs_dolara.replace(',', '.'));
System.out.println(d_kurs_dolara*6);
}
expression = "/tabela_kursow/pozycja[8]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_euro = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_euro = Double.parseDouble(kurs_euro.replace(',', '.'));
System.out.println(d_kurs_euro*6);
}
expression = "/tabela_kursow/pozycja[11]/kurs_sredni";
nodeList = (NodeList) xPath.compile(expression).evaluate(xmlDocument, XPathConstants.NODESET);
for (int i = 0; i < nodeList.getLength(); i++) {
String kurs_funta = nodeList.item(i).getFirstChild().getNodeValue();
double d_kurs_funta = Double.parseDouble(kurs_funta.replace(',', '.'));
System.out.println(d_kurs_funta*6);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (XPathExpressionException e) {
e.printStackTrace();
}
String wynik = String.valueOf(d_kurs_euro);
L1.setText(wynik);
repaint();
}}

Related

File.ReadLines keeps file locked after reading it and i can't write into it

For some reason File.ReadLines keeps the file that im reading locked, and when i am trying to write text into it using a streamWriter, i get an error that it is being used by another process. If i don't read it first, writing into it works fine. Here is my code:
IEnumerable<String> lines;
private void loadCfg()
{
lines = File.ReadLines(Application.StartupPath + #"\server.cfg");
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}
Well you should read all the lines using StreamReader class that way your file will be properly closed I altered the way you are reading lines to read all lines using StreamReader try the following version
List<string> lines = new List<string>()
private void loadCfg()
{
string temp = null;
StreamReader rd = new StreamReader(Application.StartupPath + #"\server.cfg");
temp = rd.ReadLine();
while(temp != null)
{
lines.Add(temp);
temp = rd.ReadLine();
}
rd.Close();
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}
I have not tested the code but I am sure it will solve your problem

LinqToSql query : deal with null values

Here's a Linq-to-SQL query to check in a SQL Server view if 2 values are present: an integer (LOT) and a string (ART_CODE).
But sometimes those values are null in the view. In that case I get an exception showing up on screen.
How can I modify this code to deal with null values?
private void ValidProdPlusLotBtn_Click(object sender, RoutedEventArgs e)
{
int lot = Convert.ToInt32(NumLotTxtBox.Text);
string artCode = ArtCodeLB.Content.ToString();
try
{
#region Qte Restant à produire
DataClasses1DataContext dc2 = new DataClasses1DataContext();
var reste = from r in dc.Vw_MajPoids_Restant
where r.LOT == lot && r.ART_CODE == artCode
select new
{
r.PnetRestant,
r.NbuRestant
};
LotRestantTB.Text = reste.First().PnetRestant.ToString();
NbuRestantTB.Text = reste.First().NbuRestant.ToString();
#endregion
}
catch (Exception ex)
{
StackTrace st = new StackTrace();
Messages.ErrorMessages($"{st.GetFrame(1).GetMethod().Name}\n\n{ex.ToString()}");
}
}
I've found this which is working perfectly :
private void ValidProdPlusLotBtn_Click(object sender, RoutedEventArgs e)
{
int lot = Convert.ToInt32(NumLotTxtBox.Text);
string artCode = ArtCodeLB.Content.ToString();
try
{
#region Qte Restant à produire
DataClasses1DataContext dc2 = new DataClasses1DataContext();
var reste = from r in dc.Vw_MajPoids_Restant
where r.LOT == lot && r.ART_CODE == artCode
select new
{
r.PnetRestant,
r.NbuRestant
};
if(!reste.Any())
{
// Do nothing
}
else
{
LotRestantTB.Text = reste.First().PnetRestant.ToString();
NbuRestantTB.Text = reste.First().NbuRestant.ToString();
}
#endregion
}
catch (Exception ex)
{
StackTrace st = new StackTrace();
Messages.ErrorMessages($"{st.GetFrame(1).GetMethod().Name}\n\n{ex.ToString()}");
}
}
If it can help someone else...

want to fetch the data from excel file

Data drven framework, where the values are changing for every case
public static void main(String[] args) throws BiffException, IOException {
Sheet s;
WebDriver driver = new FirefoxDriver();
FileInputStream fi = new FileInputStream("D:\\Nikhil\\FGX\\DataDriven.xlsx");
Workbook W = Workbook.getWorkbook(fi);
s = W.getSheet(0);
for(int row = 0;row <= s.getRows();row++)
{
String Username = s.getCell(0,row).getContents();
System.out.println("Username" +Username);
driver.get("http://********");
driver.findElement(By.xpath("//*[#id='LoginName']")).sendKeys(Username);
String password= s.getCell(1, row).getContents();
System.out.println("Password "+password);
driver.findElement(By.xpath("//*[#id='Password']")).sendKeys(password);
driver.findElement(By.xpath("html/body/form/div/div/div/div/fieldset/button")).click();
}
There are several reasons to get the BiffException look at Biff exception in Java.
Make sure you point the correct file, sheet, cell etc. You need to fetch and iterate the excel data. I may not answered directly to your answer, but the below code might help you,
List getData() { **Fetch the data
String path = "filepath";
List dataList = new ArrayList();
FileInputStream fis = null;
try {
fis = new FileInputStream(new File(path));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet("TestData");
java.util.Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
XSSFRow row = ((XSSFRow) rows.next());
// int r=row.getRowNum();
java.util.Iterator cells = row.cellIterator();
int i = 0;
String[] testData= new String[3];
while (cells.hasNext()) {
XSSFCell cell = (XSSFCell) cells.next();
String value = cell.getStringCellValue();
if (!value.equals(null)) {
testData [i] = value;
i++;
}
}
dataList.add(testData);
}
}
catch (Exception e) {
e.printStackTrace();
}
return dataList;
}
public Object[][] data() { **Store the data in desired format
#SuppressWarnings("rawtypes")
List dataList= getData();
Object a[][]=new Object[dataList.size()][2];
for(int i=1;i<dataList.size();i++){
String[] test=(String[]) dataList.get(i);
String username = test[0];
String password=test[1];
a[i][0]=username;
a[i][1]=password;
}
return a;

SHA-1 not giving the same answer

I'm trying to implement SHA-1 on Android with the following code
String name = "potato";
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getBytes("iso-8859-1"), 0 , name.getBytes( "iso-8859-1").length );
Bytes[] sha1hash = md.digest();
textview.setText(sha1hash.toString());
but when i run this code twice, it gives me different hash codes to "potato". As far as i know they should give me the same answer every time i run the program, anyone have any idea what problem could it be?
You can use this Code for getting SHA-1 value.
public class sha1Calculate {
public static void main(String[] args)throws Exception
{
File file = new File("D:\\Android Links.txt");
String outputTxt= "";
String hashcode = null;
try {
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = data;
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for( byte b : bytes )
{
sb.append( String.format("%02X", b) );
}
System.out.println("Digest(in hex format):: " + sb.toString());
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try this Link for any Help.
http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/

Application crashes when trying to dispose an image

I'm creating an app with two pictureBoxes, where images load from a array and randomly change on every timer tick. I'm facing a problem of sometimes not loading the image, leaving the pictureBox with a little red cross. I read I should dispose the previous image before loading the new one (I'm a C# newbie), but I can't get it working without crashing the app on the first tick. Would you please help me out?
private void timer_Tick(object sender, EventArgs e)
{
index1 = rand.Next(0, pics.Length - 1);
index2 = rand.Next(0, pics.Length - 1);
pcb1.ImageLocation = pics[index1];
pcb2.ImageLocation = pics[index2];
}
try
{
pcb1.Image.Dispose();
pcb2.Image.Dispose();
index1 = rand.Next(0, pics.Length - 1);
index2 = rand.Next(0, pics.Length - 1);
pcb1.ImageLocation = pics[index1];
pcb2.ImageLocation = pics[index2];
}
catch (Exception)
{
throw;
}
- tells me System.ArgumentException
A possible solution:
try
{
private void timer_Tick(object sender, EventArgs e)
{
index1 = rand.Next(0, pics.Length);
if (File.Exists(pics[index1]))
{
Image img1 = Image.FromFile(pics[index1]);
pcb1.Image = img1;
}
index2 = rand.Next(0, pics.Length);
if (File.Exists(pics[index2]))
{
Image img2 = Image.FromFile(pics[index2]);
pcb2.Image = img2;
}
}
}
catch (OutOfMemoryException oomEx)
{
MessageBox.Show("Not a valid image.");
}
catch (Exception ex)
{
//all others...respond appropriately
}

Resources