' Exception in Application start method, java.lang.reflect.InvocationTargetException ' while reading and displaying from database - database

I am attempting to read values from MySQL database and display it in a table in JavaFX. I use netbeans IDE. When I run my code I got the exception mentioned in the title. I will post code below:
public class ViewSubject extends Application {
private final TableView<Subject> table = new TableView<>();
private final ObservableList<Subject> data
= FXCollections.observableArrayList();
final HBox hb = new HBox();
private Connection connect = null;
private Statement statement = null;
private final PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws ClassNotFoundException, SQLException {
Scene scene = new Scene(new Group());
stage.setTitle("Add Subject");
stage.setWidth(650);
stage.setHeight(550);
stage.setResizable(false);
final Label label = new Label("Subject Details");
label.setFont(new Font("Calibri", 20));
TableColumn sub = new TableColumn("Subject Name");
sub.setMinWidth(350);
sub.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subName"));
sub.setCellFactory(TextFieldTableCell.forTableColumn());
sub.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubName(t.getNewValue());
}
}
);
TableColumn code = new TableColumn("Subject Code");
code.setMinWidth(130);
code.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subCode"));
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
TableColumn rev = new TableColumn("Revision");
rev.setMinWidth(130);
rev.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subRev"));
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(sub, code, rev);
final VBox vbox = new VBox();
vbox.setSpacing(10);
vbox.setPadding(new Insets(20, 20, 20, 20));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from subject");
writeResultSet(resultSet);
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
String subname = resultSet.getString("subname");
String code = resultSet.getString("subcode");
String rev = resultSet.getString("subrev");
data.add(new Subject(subname, code, rev));
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
}
}
}
There is one more class in the package -
public class Subject {
private final SimpleStringProperty sub;
private final SimpleStringProperty code;
private final SimpleStringProperty rev;
Subject(String subName, String subCode, String subRev) {
this.sub = new SimpleStringProperty(subName);
this.code = new SimpleStringProperty(subCode);
this.rev = new SimpleStringProperty(subRev);
}
public String getSubName() {
return sub.get();
}
public void setSubName(String subName) {
sub.set(subName);
}
public String getSubCode() {
return code.get();
}
public void setSubCode(String subCode) {
code.set(subCode);
}
public String getSubRev() {
return rev.get();
}
public void setSubRev(String subRev) {
rev.set(subRev);
}
}
This is the exception details:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at viewsubject.ViewSubject.read(ViewSubject.java:119)
at viewsubject.ViewSubject.start(ViewSubject.java:113)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
When the code is ran, a window appears for a fraction of a second and then suddenly closes due to the occurrence of this exception. Why this exception occurs ? How can remove this exception?

You don't have the MySQL JDBC driver on your classpath.
Perform the Vogella tutorial on Java and JDBC with MySQL. Do the whole tutorial step by step, running code each step of the way. As part of the Vogella tutorial, it tells you how to setup 3rd party libraries (like the MySQL JDBC library) in Eclipse.
When posting code, try to post code which matches the stack trace. The StackTrace reports an error at viewsubject.ViewSubject.read(ViewSubject.java:119) but there is no such read function in your ViewSubject class.

Related

Can't read properties file on device farm :- src/test/resources/Properties/Android_Or.properties -error

Please let me know how to read properties file in device farm, since following code is not working. I have looked into various solutions but still device farm is not able to recognize properties file, although this code works fine locally
public abstract class AndroidCapabilities {
// protected static AppiumDriver<MobileElement> driver;
public static ExtentHtmlReporter reporter;
public static ExtentReports extent;
public static ExtentTest logger1;
// #Parameters("browser")
// #BeforeSuite
// public void setUp() throws MalformedURLException {
public static AndroidDriver<MobileElement> driver;
public abstract String getName();
#BeforeTest
public abstract void setUpPage();
#BeforeSuite
public void setUpAppium() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
// capabilities.setCapability("device", "Android");
// capabilities.setCapability("platformName", "Android");
// capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
URL url = new URL(URL_STRING);
// Use a empty DesiredCapabilities object
driver = new AndroidDriver<MobileElement>(url, capabilities);
// Use a higher value if your mobile elements take time to show up
driver.manage().timeouts().implicitlyWait(35, TimeUnit.SECONDS);
}
public static Properties properties;
static {
properties = new Properties();
FileInputStream fis;
InputStream input;
try {
// fis = new FileInputStream(System.getProperty("user.dir") +
// "//src//test//resources//Properties//Android_OR.properties");
fis = (FileInputStream) Thread.currentThread().getContextClassLoader()
.getResourceAsStream("//Properties//Android_OR.properties");
System.out.println(properties.getProperty("url"));
properties.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
}
#BeforeTest
public void createReport() {
reporter = new ExtentHtmlReporter("./extent.html");
extent = new ExtentReports();
extent.attachReporter(reporter);
}
#AfterTest
public void flush() throws IOException {
extent.flush();
// reporter.setAppendExisting(true);
}
#AfterSuite
public void closeApplication() {
driver.quit();
Reporter.log("===Session End===", true);
}
}
Faced the same issue. Instead of using System.getProperty, try this:
// pass fileName as "Android_OR.properties"
public Properties loadProperty(String fileName) {
Properties prop = new Properties();
try (InputStream input = Base.class.getClassLoader().getResourceAsStream(filePath)) {
if (input == null) {
System.out.println("Sorry, unable to find config.properties");
return prop;
}
// load a properties file from class path, inside static method
prop.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
return prop;
}

Null pointer exception for Extent Report

It wouldbe silly question but would be great help it you can help me out.
I tried implementing extent report for multple test cases, but report are not getting generated .
Code:
public class SampleTc1
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase1()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
public class SampleTc2
{
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
static void testcase2()
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
driver.get("https://www.google.co.in");
logger.log(LogStatus.PASS, "This step is passed");
driver.close();
}
}
Main Class:
public class Maindriver {
static WebDriver driver;
static ExtentReports report;
static ExtentTest logger;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
report=new ExtentReports("./Report/ExtentReport/ExecutionResult.html", true);
logger=report.startTest("TC1", "Testc Case1");
SampleTc1.testcase1();
report.endTest(logger);
logger=report.startTest("TC2", "Testc Case2");
SampleTc2.testcase2();
report.endTest(logger);
report.flush();
}
}
After running no reports are getting generated and it is showing null ponter exception:
Exception in thread "main" java.lang.NullPointerException
at SmokeTest.SampleTc1.testcase1(SampleTc1.java:24)
at SmokeTest.Maindriver.main(Maindriver.java:22)
Above exception I am getting.
Thanks in advance.
If you are using testng for running selenium suite, you can implement extent reports as a listener.
Like,
public class ExtentReporterNG implements IReporter
{
public ExtentReports extent;
private void buildTestNodes(IResultMap testMap, LogStatus status)
{
ExtentTest test;
if (testMap.size() > 0)
{
for (ITestResult result : testMap.getAllResults())
{
//test = extent.startTest(result.getInstance().getClass().getSimpleName(),result.getMethod().getMethodName());
test = extent.startTest(result.getMethod().getMethodName().toUpperCase(),result.getInstance().getClass().getSimpleName().toUpperCase());
test.assignCategory(result.getInstance().getClass().getSimpleName().toUpperCase());
test.setStartedTime(getTime(result.getStartMillis()));
for (String group : result.getMethod().getGroups())
test.assignCategory(group);
String message = "Test " + status.toString().toLowerCase() + "ed";
if (result.getThrowable() != null)
message = result.getThrowable().getMessage();
test.setEndedTime(getTime(result.getEndMillis()));
test.log(status, message);
extent.endTest(test);
}
}
}
private Date getTime(long millis)
{
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(millis);
return calendar.getTime();
}
#Override
public void generateReport(List<XmlSuite> xmlsuite, List<ISuite> suites,String file)
{
final String filePath=GlobalSettings.getProperty(GlobalSettings.EXTENTFILE);
extent = new ExtentReports(filePath, true,DisplayOrder.NEWEST_FIRST,NetworkMode.OFFLINE );
extent.loadConfig(new File("./config/extentConfig.xml"));
for (ISuite suite : suites)
{
Map<String, ISuiteResult> result = suite.getResults();
for (ISuiteResult r : result.values())
{
ITestContext context = r.getTestContext();
buildTestNodes(context.getPassedTests(), LogStatus.PASS);
buildTestNodes(context.getFailedTests(), LogStatus.FAIL);
buildTestNodes(context.getSkippedTests(), LogStatus.SKIP);
buildTestNodes(context.getFailedConfigurations(),LogStatus.FAIL);
buildTestNodes(context.getSkippedConfigurations(),LogStatus.SKIP);
}
}
extent.flush();
extent.close();
}}
It is not well organized, hard to say what/where is the problem ...
You can check here a selenium webdriver testng tutorial I used it when I started and it is a good starting point!
You have to change your ExtentReports as static in the base class. I got this idea from Mukesh Otwani, Selenium automation trainer for Learn-Automation.
I created separate class for extent report, hence avoided NULL pointer exception

Why ' Exception in Application start method, java.lang.reflect.InvocationTargetException ' occurs? [duplicate]

I am attempting to read values from MySQL database and display it in a table in JavaFX. I use netbeans IDE. When I run my code I got the exception mentioned in the title. I will post code below:
public class ViewSubject extends Application {
private final TableView<Subject> table = new TableView<>();
private final ObservableList<Subject> data
= FXCollections.observableArrayList();
final HBox hb = new HBox();
private Connection connect = null;
private Statement statement = null;
private final PreparedStatement preparedStatement = null;
private ResultSet resultSet = null;
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage stage) throws ClassNotFoundException, SQLException {
Scene scene = new Scene(new Group());
stage.setTitle("Add Subject");
stage.setWidth(650);
stage.setHeight(550);
stage.setResizable(false);
final Label label = new Label("Subject Details");
label.setFont(new Font("Calibri", 20));
TableColumn sub = new TableColumn("Subject Name");
sub.setMinWidth(350);
sub.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subName"));
sub.setCellFactory(TextFieldTableCell.forTableColumn());
sub.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubName(t.getNewValue());
}
}
);
TableColumn code = new TableColumn("Subject Code");
code.setMinWidth(130);
code.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subCode"));
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setCellFactory(TextFieldTableCell.forTableColumn());
code.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
TableColumn rev = new TableColumn("Revision");
rev.setMinWidth(130);
rev.setCellValueFactory(
new PropertyValueFactory<Subject, String>("subRev"));
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setCellFactory(TextFieldTableCell.forTableColumn());
rev.setOnEditCommit(
new EventHandler<TableColumn.CellEditEvent<Subject, String>>() {
#Override
public void handle(TableColumn.CellEditEvent<Subject, String> t) {
((Subject) t.getTableView().getItems().get(
t.getTablePosition().getRow())).setSubCode(t.getNewValue());
}
}
);
table.setItems(data);
table.getColumns().addAll(sub, code, rev);
final VBox vbox = new VBox();
vbox.setSpacing(10);
vbox.setPadding(new Insets(20, 20, 20, 20));
vbox.getChildren().addAll(label, table);
((Group) scene.getRoot()).getChildren().addAll(vbox);
stage.setScene(scene);
stage.show();
try {
Class.forName("com.mysql.jdbc.Driver");
connect = DriverManager
.getConnection("jdbc:mysql://localhost:3306/project?"
+ "user=root&password=virus");
statement = connect.createStatement();
resultSet = statement
.executeQuery("select * from subject");
writeResultSet(resultSet);
} catch (ClassNotFoundException | SQLException e) {
throw e;
} finally {
close();
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
while (resultSet.next()) {
String subname = resultSet.getString("subname");
String code = resultSet.getString("subcode");
String rev = resultSet.getString("subrev");
data.add(new Subject(subname, code, rev));
}
}
private void close() {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connect != null) {
connect.close();
}
} catch (SQLException e) {
}
}
}
There is one more class in the package -
public class Subject {
private final SimpleStringProperty sub;
private final SimpleStringProperty code;
private final SimpleStringProperty rev;
Subject(String subName, String subCode, String subRev) {
this.sub = new SimpleStringProperty(subName);
this.code = new SimpleStringProperty(subCode);
this.rev = new SimpleStringProperty(subRev);
}
public String getSubName() {
return sub.get();
}
public void setSubName(String subName) {
sub.set(subName);
}
public String getSubCode() {
return code.get();
}
public void setSubCode(String subCode) {
code.set(subCode);
}
public String getSubRev() {
return rev.get();
}
public void setSubRev(String subRev) {
rev.set(subRev);
}
}
This is the exception details:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:190)
at viewsubject.ViewSubject.read(ViewSubject.java:119)
at viewsubject.ViewSubject.start(ViewSubject.java:113)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
... 1 more
When the code is ran, a window appears for a fraction of a second and then suddenly closes due to the occurrence of this exception. Why this exception occurs ? How can remove this exception?
You don't have the MySQL JDBC driver on your classpath.
Perform the Vogella tutorial on Java and JDBC with MySQL. Do the whole tutorial step by step, running code each step of the way. As part of the Vogella tutorial, it tells you how to setup 3rd party libraries (like the MySQL JDBC library) in Eclipse.
When posting code, try to post code which matches the stack trace. The StackTrace reports an error at viewsubject.ViewSubject.read(ViewSubject.java:119) but there is no such read function in your ViewSubject class.

Java JLabel setText Method Not Working

I've been trying to figure out what the problem is, but i cannot figure it out. I call a method from a class using w.setCandyAmountLabelText(numberofcandies); However it does not work. I am trying to change the text of a jlabel which is in another class. Here is the error and code.
error
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at CandyWindow.setCandyAmountLabelText(CandyWindow.java:111)
at Counter$1.actionPerformed(Counter.java:32)
at javax.swing.Timer.fireActionPerformed(Unknown Source)
at javax.swing.Timer$DoPostEvent.run(Unknown Source)
at java.awt.event.InvocationEvent.dispatch(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$200(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.awt.EventQueue$3.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
mainclass
public class CandyMain {
public static void main(String[] args) {
CandyWindow window = new CandyWindow("Candy Box");
window.init();
}
CandyWindow Class
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CandyWindow extends JFrame {
public JPanel mainpanel;
public JLabel candyamountlabel;
public JButton eatcandies;
public JLabel candieseaten;
public boolean candiesmorethan10 = false;
public JButton throwcandies;
Counter counter;
CandyWindow(String title) {
super(title);
this.setVisible(true);
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}
CandyWindow() {
}
public void init() {
counter = new Counter();
// initialized label
candyamountlabel = new JLabel("You Have 0 Candies!");
eatcandies = new JButton("Eat All The Candies!");
candieseaten = new JLabel("You Have Eaten 0 Candies!");
throwcandies = new JButton("Throw Candies On Ground!");
//sets visibilty to false
candieseaten.setVisible(false);
throwcandies.setVisible(false);
// add action listener
eatcandies.addActionListener(eatcandieslistener);
// makes panel
mainpanel = new JPanel();
// adds label to panel
mainpanel.add(candyamountlabel);
mainpanel.add(eatcandies);
mainpanel.add(candieseaten);
mainpanel.add(throwcandies);
// adds panel to jframe
this.add(mainpanel);
this.setSize(1600, 850);
counter.startTimer();
}
ActionListener eatcandieslistener = new ActionListener(){
#Override
public void actionPerformed(ActionEvent e) {
counter.setCandiesEaten(counter.getNumberOfCandies() + counter.getCandiesEaten());
counter.eatcandies();
candyamountlabel.setText("You Have 0 Candies!");
candieseaten.setText("You Have Eaten " + counter.getCandiesEaten() + " Candies!");
candieseaten.setVisible(true);
}
};
public void setThrowCandiesVisible(int y){
if(y == 1){
candiesmorethan10 = true;
}
if(candiesmorethan10){
throwcandies.setVisible(true);
throwcandies.repaint();
}
}
public void setCandyAmountLabelText(long g){
candyamountlabel.setText("You Have " + g + " Candies!");
candyamountlabel.repaint();
}
}
Counter class
import java.awt.event.*;
import javax.swing.*;
public class Counter {
long numberofcandies = 0;
long candiespersecond = 0;
long candieseaten = 0;
CandyWindow w = new CandyWindow();
void startTimer() {
Timer t = new Timer(1000, timercount);
t.setRepeats(true);
t.start();
}
ActionListener timercount = new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
// setscandiespersecond to one
setCandiesPerSecond(1);
//increases candies
numberofcandies = candiespersecond + numberofcandies;
//changes numberofcandieslabel
w.setCandyAmountLabelText(numberofcandies);
//if candies are more than 10 set throw on ground visible
int x = 0;
if(numberofcandies > 9){
x = 1;
w.setThrowCandiesVisible(x);
}
//System.out.println("Number of Candies" + getNumberOfCandies()); //test print works
//System.out.println("candies eaten" + getCandiesEaten()); //test print works
}
};
public long getNumberOfCandies() {
return numberofcandies;
}
public long getCandiesPerSecond() {
return candiespersecond;
}
public void setCandiesPerSecond(long g) {
candiespersecond = g;
}
public void eatcandies(){
numberofcandies = 0;
}
public long getCandiesEaten(){
return candieseaten;
}
public void setCandiesEaten(long p){
candieseaten = p;
}
}
Your CandyWindow creates a new Counter object in init() - But this Counter object makes a new CandyWindow when it is created: CandyWindow w = new CandyWindow();. So the Counter doesn't reference to the CandyWindow which created the Counter - which I think you meant to do. Try passing the CandyWindow along with Counter like:
counter = new Counter(this);
and creating a constructor for Counter which takes a CandyWindow, and sets w to this reference instead:
public Counter(CandyWindow w) {
this.w = w;
}
The NullPointerException is caused in this case, because the Counter object has a reference to a new CandyWindow, of which the init() function is never called - hence the line: 'w.setCandyAmountLabelText(numberofcandies);' in 'onActionPerformed()' would fail for the CandyAmountLabelText of this new CandyWindow is never initialised.

data/data/com.package/databases folder isn't showed

I made an android dictionary application. I have created a database named "kamusJawa.sqlite" and copied it to the assets folder. I tried the code in this link Own Database in Assets Folder on Android Eclipse Project
This is my database manager class:
package com.kamusJI;
public class DBHelper extends SQLiteOpenHelper{
private static String DBPATH = "/data/data/com.kamusJI/databases/";
private static String DBNAME = "kamusJawa.sqlite";
private SQLiteDatabase DBSQ;
private final Context KJICtx;
public DBHelper(Context context) throws IOException {
super(context, DBNAME, null, 1);
this.KJICtx = context;
// TODO Auto-generated constructor stub
boolean dbexist = cekDB();
if (dbexist) {
//System.out.println("Database exists");
openDB();
} else {
System.out.println("Database doesn't exist");
createDB();
}
}
public void createDB() throws IOException{
boolean dbExist = cekDB();
if(!dbExist){
this.getReadableDatabase();
try{
salinDB();
}catch (IOException e){
throw new Error("Gagal menyalin database");
}
}
}
boolean cekDB() {
//SQLiteDatabase cekDatabase = null;
boolean cekdb = false;
try{
String path = DBPATH + DBNAME;
File dbfile = new File(path);
//cekDatabase = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
cekdb = dbfile.exists();
}catch(SQLException e){
System.out.println("Database tidak ada");
}
return cekdb;
//return cekDatabase !=null ? true : false;
}
private void salinDB() throws IOException{
AssetManager AM = KJICtx.getAssets();
File DbFile = new File(DBPATH+DBNAME);
InputStream in = KJICtx.getAssets().open(DBNAME);
//OutputStream out = new FileOutputStream(DbFile);
OutputStream out = new FileOutputStream("/data/data/com.kamusJI/databases/kamusJawa.sqlite");
DbFile.createNewFile();
byte[] b = new byte[1024];
int i, r;
String[] Files = AM.list("");
Arrays.sort(Files);
i= 1;
String fdb = String.format("kamusJawa.db.00%d", i);
while(Arrays.binarySearch(Files, fdb)>=0){
//InputStream in = AM.open(fdb);
while(( r = in.read(b))>0)
out.write(b,0,r);
in.close();
i++;
fdb = String.format("kamusJawa.db.00%d", i);
}
out.flush();
out.close();
}
public void openDB() throws SQLException{
String path = DBPATH+DBNAME;
DBSQ = SQLiteDatabase.openDatabase(path, null, SQLiteDatabase.OPEN_READONLY);
}
public synchronized void close(){
if(DBSQ !=null)
DBSQ.close();
super.close();
}
#Override
public void onCreate(SQLiteDatabase arg0) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
}
}
and this is my main class:
package com.kamusJI;
public class KJI extends ListActivity {
private KJI this_class = this;
String[] Menu = {"Basa Jawa", "Bahasa Indonesia", "Tambah Data"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, R.layout.row, R.id.Cari, Menu));
ListView lv = getListView();
lv.setTextFilterEnabled(false);
/* Defines On Item Click callback method */
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent action = null;
switch(position) {
case 0:
case 1:
action = new Intent(getApplicationContext(), Cari.class);
action.putExtra("MODE", position);
break;
case 2:
action = new Intent(getApplicationContext(), Tambah.class);
action.putExtra("MODE", position);
break;
case 3:
finish();
return;
}
startActivity(action);
Toast.makeText(getApplicationContext(), ((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
public void InitDatabase() {
AsyncTask<String, Void, String> InitDB = new AsyncTask<String, Void, String>() {
Dialog progress = null;
String msg;
DBHelper dbhelper;
#Override
protected void onPreExecute() {
try {
dbhelper = new DBHelper(this_class);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!dbhelper.cekDB())
progress = ProgressDialog.show(this_class, "", "Installing Database.\nPlease wait.");
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
dbhelper.createDB();
msg = "Database successfully installed.";
} catch (IOException ioe) {
msg = "Database installation failed.";
}
return msg;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (progress!=null) {
progress.dismiss();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();
}
}
};
InitDB.execute(new String());
}
}
When I run my application, then I go to file explorer, I can't find the data/data/com.kamusJI/databases. How it can be like that?
change your database name extension to .db
You need special permissions like root access to read the path:
/data/data/com.package/databases

Resources