Hello. I'm kinda stuck.
I got an error, I'm not able to close my previous window to set the new one.
Here is my controller :
public class Controller implements Initializable {
//------------- init Order -------------//
#FXML
private Label text10;
#FXML
private Label text20;
#FXML
private Label text30;
#FXML
private Label text40;
#FXML
private Label text50;
#FXML
private TextField entry10;
#FXML
private TextField entry20;
#FXML
private TextField entry30;
#FXML
private Button btnConnect10;
//------------- init Reception -------------//
#FXML
private Label text11;
#FXML
private Label text21;
#FXML
private Label text31;
#FXML
private Label text41;
#FXML
private Label text51;
#FXML
private TextField entry11;
#FXML
private TextField entry21;
#FXML
private TextField entry31;
#FXML
private Button btnConnect11;
//------------- init Connexion -------------//
#FXML
private ImageView img;
#FXML
private Label user;
#FXML
private Label password;
#FXML
private TextField usr;
#FXML
private PasswordField passwd;
#FXML
private Button btnConnect13;
//------------- init popup -------------//
#FXML
private Label popup;
//------------- Stage -------------//
Stage prevStage;
public void setPrevStage(Stage stage) {
this.prevStage = stage;
}
#FXML
private void buttonPressed(KeyEvent e) {
if (e.getCode() == KeyCode.ENTER) {
System.out.println("je suis un krab");
}
}
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {
//init classe
Controller ctr = new Controller();
//fenetre Commande
if (event.getSource() == btnConnect10) {
ctr.Commande(entry10.getText(), entry20.getText(), entry30.getText());
}
//fenetre Reception
if (event.getSource() == btnConnect11) {
ctr.Reception(entry11.getText(), entry21.getText(), entry31.getText());
}
//fenetre connexion
if (event.getSource() == btnConnect13) {
ctr.Connect(usr.getText(), passwd.getText());
}
}
//Menu d'affchage
private void menu(int access) throws IOException {
//init fenetre
Stage stage = new Stage();
Pane myPane = null;
Scene scene;
switch (access) {
case 1:
stage.setTitle("Commande OR tool");
myPane = FXMLLoader.load(getClass().getResource("CommandeFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
case 2:
//recupère les infos de la fenetre
stage.setTitle("Réception OR tool");
myPane = FXMLLoader.load(getClass().getResource("ReceptionFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
case 3:
stage.setTitle("Admin OR tool");
myPane = FXMLLoader.load(getClass().getResource("AdminFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show();
break;
default:
//error
System.out.println("erreur changing window");
}
}private void Connect(String getuser, String getpasswd) throws IOException {
ConnectBDD bdd = new ConnectBDD();
Controller ctr = new Controller();
System.out.println("user = "+getuser+"\npassword ="+getpasswd);
//test
if (!getuser.isEmpty() && !getpasswd.isEmpty()) {
//check if user exist
if (bdd.connectUserTest(getuser, getpasswd) == true) {
//get the access level
int acces = bdd.connectUser (getuser, getpasswd);
//Changing window
ctr.menu(acces);
}
else {
System.out.println("user not in the data base");
}
} //message d'erreur
//to do faire un pop up
else {
System.out.println("no entry");
}
}
And the main
public class JavaFX extends Application {
#FXML
#Override
public void start(Stage primaryStage) throws Exception {
primaryStage.setTitle("OR tool");
FXMLLoader myLoader = new FXMLLoader(getClass().getResource("ConnectFXML.fxml"));
Pane myPane = (Pane) myLoader.load();
Controller controller = (Controller) myLoader.getController();
controller.setPrevStage(primaryStage);
Scene myScene = new Scene(myPane);
primaryStage.setScene(myScene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
I got a nice stack
Exception in thread "JavaFX Application Thread" java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1774)
at javafx.fxml.FXMLLoader$ControllerMethodEventHandler.handle(FXMLLoader.java:1657)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:86)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:49)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Node.fireEvent(Node.java:8411)
at javafx.scene.control.Button.fire(Button.java:185)
at com.sun.javafx.scene.control.behavior.ButtonBehavior.mouseReleased(ButtonBehavior.java:182)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:96)
at com.sun.javafx.scene.control.skin.BehaviorSkinBase$1.handle(BehaviorSkinBase.java:89)
at com.sun.javafx.event.CompositeEventHandler$NormalEventHandlerRecord.handleBubblingEvent(CompositeEventHandler.java:218)
at com.sun.javafx.event.CompositeEventHandler.dispatchBubblingEvent(CompositeEventHandler.java:80)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:238)
at com.sun.javafx.event.EventHandlerManager.dispatchBubblingEvent(EventHandlerManager.java:191)
at com.sun.javafx.event.CompositeEventDispatcher.dispatchBubblingEvent(CompositeEventDispatcher.java:59)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:58)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.BasicEventDispatcher.dispatchEvent(BasicEventDispatcher.java:56)
at com.sun.javafx.event.EventDispatchChainImpl.dispatchEvent(EventDispatchChainImpl.java:114)
at com.sun.javafx.event.EventUtil.fireEventImpl(EventUtil.java:74)
at com.sun.javafx.event.EventUtil.fireEvent(EventUtil.java:54)
at javafx.event.Event.fireEvent(Event.java:198)
at javafx.scene.Scene$MouseHandler.process(Scene.java:3757)
at javafx.scene.Scene$MouseHandler.access$1500(Scene.java:3485)
at javafx.scene.Scene.impl_processMouseEvent(Scene.java:1762)
at javafx.scene.Scene$ScenePeerListener.mouseEvent(Scene.java:2494)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:380)
at com.sun.javafx.tk.quantum.GlassViewEventHandler$MouseEventNotification.run(GlassViewEventHandler.java:294)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.lambda$handleMouseEvent$354(GlassViewEventHandler.java:416)
at com.sun.javafx.tk.quantum.QuantumToolkit.runWithoutRenderLock(QuantumToolkit.java:389)
at com.sun.javafx.tk.quantum.GlassViewEventHandler.handleMouseEvent(GlassViewEventHandler.java:415)
at com.sun.glass.ui.View.handleMouseEvent(View.java:555)
at com.sun.glass.ui.View.notifyMouse(View.java:937)
at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
at com.sun.glass.ui.win.WinApplication.lambda$null$148(WinApplication.java:191)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:71)
at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:275)
at javafx.fxml.FXMLLoader$MethodHandler.invoke(FXMLLoader.java:1769)
... 48 more
The most important part is
Caused by: java.lang.NullPointerException
at javafx.Controller.menu(Controller.java:149)
at javafx.Controller.Connect(Controller.java:303)
at javafx.Controller.handleButtonAction(Controller.java:130)
ligne 149 is when i try to close the previous windows. "prevStage.close();" in the menu function of the controller
ligne 303 is the call of the fuction menu in the test of connexion.
ligne 130 is in the handleButtonAction when i call the connect function
When I try to open a new window in the handler it works perfectly. But I need to adpat the window to the access level of the user.
But now I've got a java.lang.NullPointerException.
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {//init fenetre
Stage stage = new Stage();
Pane myPane = null;
Scene scene;stage.setTitle("Réception OR tool");
myPane = FXMLLoader.load(getClass().getResource("ReceptionFXML.fxml"));
scene = new Scene(myPane);
stage.setScene(scene);
prevStage.close();
stage.show(); }
You are repeatedly creating new controller instances in your code:
Controller ctr = new Controller();
For these new instances, nothing will be initialized: you never call setPrevStage() on these instances so prevStage will not be initialized and, since these instances are not created by the FXMLLoader, the #FXML-annotated fields will not be initialized.
Remove the calls to the Controller constructor, and invoke the methods on the current instance:
#FXML
private void handleButtonAction(ActionEvent event) throws IOException {
// remove this:
//Controller ctr = new Controller();
//fenetre Commande
if (event.getSource() == btnConnect10) {
// replace this
// ctr.Commande(entry10.getText(), entry20.getText(), entry30.getText());
// with this
Commande(entry10.getText(), entry20.getText(), entry30.getText());
// or equivalently
// this.Commande(entry10.getText(), entry20.getText(), entry30.getText());
}
//fenetre Reception
if (event.getSource() == btnConnect11) {
Reception(entry11.getText(), entry21.getText(), entry31.getText());
}
//fenetre connexion
if (event.getSource() == btnConnect13) {
Connect(usr.getText(), passwd.getText());
}
}
and similarly throughout your code.
Related
I want to make a FadeTransition within a pane in my application. Also, with this FadeTransition I set the visibitilitys of some JavaFX inside the pane to false, to make them disappear. It's working fine but, when I call another method that I named waitForResponse(event) after the FadeTransition it just stops working. I don't know why.
If I comment the waitForResponse(event) the FadeTransitions start working again.
I've thought that maybe it's a problem with the Socket and the InputStreamReader inside the waitForResponse(event), but I tested taking it out and making another basic thing inside this method still not work.
I've made other tests and dicovered that FadeTransition and other visibility changes doesn't work if I put any bufferedReader, other loops ou decision structures after it.
I just want to make a loading screen that prevent user to click anywhere until it's finished.
This is the code:
public class LoadingScreenController implements Initializable {
// Socket que vai ser utilizado nos vários métodos para conversar com o servidor
private Socket cliente;
// PrintWriter que vai ser utilizado pelos vários métodos e vai passar o
// argumento para o switch case
private PrintWriter pr;
private InputStreamReader in;
private BufferedReader bf;
private String option;
private String response;
#FXML
private Button refreshButton;
#FXML
private ImageView loadingGif;
#FXML
private Label txtLabel;
#FXML
private AnchorPane rootPane;
public String getOption() {
return option;
}
public void setOption(String option) {
this.option = option;
}
#Override
public void initialize(URL url, ResourceBundle rb) {
}
#FXML
private void makeFadeInTransition() {
FadeTransition fadeTransition = new FadeTransition(Duration.seconds(1), loadingGif);
fadeTransition.setFromValue(0.0);
fadeTransition.setToValue(1.0);
fadeTransition.play();
}
#FXML
private void onRefreshButtonAction(ActionEvent event) {
if (option == null) {
throw new IllegalStateException("Entity was null");
}
refreshButton.setVisible(false);
refreshButton.setDisable(true);
txtLabel.setVisible(false);
makeFadeInTransition();
sendOptionToServer(event);
}
#FXML
private void sendOptionToServer(ActionEvent event) {
try {
cliente = new Socket("localhost", 3322);
pr = new PrintWriter(cliente.getOutputStream());
in = new InputStreamReader(cliente.getInputStream());
bf = new BufferedReader(in);
pr.println(option);
pr.flush();
waitForReponse(event, bf);
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForReponse(ActionEvent event, BufferedReader bf) throws IOException {
response = bf.readLine();
switch (response) {
case "a":
Utils.currentStage(event).close();
break;
}
}
}
Your sendOptionToServer(...) method, and in particular your waitForResponse(...) method, contains blocking calls that block execution until they are complete (i.e. until you receive a response from the server). Since you're running these on the FX Application Thread, you prevent that thread from doing its normal work until those calls complete. This means it won't update the UI or process any user events until you have received and processed the response from the server.
You should place the calls to blocking methods in a background thread to allow the FX Application Thread to proceed in the meantime. The javafx.concurrent API makes this reasonably easy to do; here a Task should suffice.
Here's a version that uses a Task. I also used a "try with resources" to ensure everything that needs to be closed is correctly closed.
#FXML
private void sendOptionToServer(ActionEvent event) {
Task<String> serverCommunicationTask = new Task<>() {
#Override
protected String call() throws Exception {
try (
Socket cliente = new Socket("localhost", 3322);
PrintWriter pr = new PrintWriter(cliente.getOutputStream());
BufferedReader bf = new BufferedReader(new InputStreamReader(cliente.getInputStream()));
) {
pr.println(option);
pr.flush();
return bf.readLine();
}
}
};
serverCommunicationTask.setOnSucceeded(event -> {
if ("a".equals(serverCommunicationTask.getValue())) {
rootPane.getScene().getWindow().hide();
}
});
serverCommunicationTask.setOnFailed(event -> {
event.getException().printStackTrace();
// handle exception...
});
Thread thread = new Thread(serverCommunicationTask);
thread.setDaemon(true);
thread.start();
}
This question already has answers here:
Passing Parameters JavaFX FXML
(10 answers)
Closed 6 years ago.
HI really need help with this assignment. How can I pass a connection from my login window to my main window. I have a login window where I ask the user to a select server type (Ex: MySQL, SQL, MySQL Local), user type (Ex: Parent, Admin, Student), database name (the name of the database they want to connect to), server name (root), and server password. If all information are correct, then it will open the main window. Now I pass that sql connection to my main window so I can code to load data from my database to my table.
All need help with is to pass connect to my other class or scene, stage. This is due in 3 days. If you need the FXML code I can send them too. Please, Please I really need the help to pass connection
Here is my connection code
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Scanner;
import javafx.scene.control.Alert;
public class Connections {
private static Alert al;
public static final int MYSQLLOCAL = 1;
public static final int MYSQLREMOTE= 2;
public static final int SQLSERVERLOCAL = 3;
public static final int SQLSERVER = 4;
public static final int UNKNOWN = -1;
public static java.sql.Connection getconnect(int which, String name, String uid, String pass) {
Scanner scan = new Scanner(System.in);
java.sql.Connection connection = null;
String driver = getDriver(which);
String url = getURL(which, name);
System.out.println(driver);
System.out.println(url);
try
{ // load the driver
Class.forName(driver).newInstance();
System.out.println("Known drivers that are registered:");
Enumeration enumer = DriverManager.getDrivers();
while (enumer.hasMoreElements())
System.out.println(enumer.nextElement());
}
catch( ClassNotFoundException | InstantiationException | IllegalAccessException e )
{
return null;
}
try
{
connection = DriverManager.getConnection(url, uid, pass);
System.out.println("Connection pass");
}
catch(Exception e )
{
return null;
}
return connection;
}
public static Connection connect(int which, String name) {
java.sql.Connection connection = null;
String driver = getDriver(which);
String url = getURL(which, name);
System.out.println(driver);
System.out.println(url);
try { // load the driver
Class.forName(driver).newInstance();
System.out.println("Known drivers that are registered:");
Enumeration enumer = DriverManager.getDrivers();
while (enumer.hasMoreElements())
System.out.println(enumer.nextElement());
}
catch( ClassNotFoundException | InstantiationException | IllegalAccessException e )
{
return null;
}
try {
connection = DriverManager.getConnection(url, "", "");
System.out.println("Connection successful!");
}
catch( SQLException e )
{
al = new Alert(Alert.AlertType.INFORMATION);
al.setTitle("Error");
al.setHeaderText(null);
al.setContentText("Login failed. Please make sure all information"
+ " are correct");
al.showAndWait();
return null;
}
return connection;
}
public static String getDriver(int num) {
switch (num) {
case SQLSERVER:
return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
case MYSQLLOCAL:
return "com.mysql.jdbc.Driver";
case MYSQLREMOTE:
return "com.mysql.jdbc.Driver";
case SQLSERVERLOCAL:
return "com.microsoft.sqlserver.jdbc.SQLServerDriver";
default:
return "error";
}
}
public static String getURL(int num, String names) {
Scanner scan = new Scanner(System.in);
String name = names;
switch (num) {
case SQLSERVER:
{
if (name.equals("default"))
return "jdbc:sqlserver://164.106.3.23:9012";
else
return "jdbc:sqlserver://164.106.3.23:9012" + "; databaseName=" + name;
// change this to match your ODBC connection name
}
case MYSQLLOCAL:
{
return "jdbc:mysql://localhost:3306/"+name;
}
case MYSQLREMOTE:
{
return "jdbc:mysql://164.106.3.22:3098/"+ name;
}
default:
return "error";
}
}
}
Here is my FXML controller for login
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.Event;
import javafx.fxml.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
public class GiantsLoginController {
public String dataName, serverName, password;
public int num;
private Connection connect = null;
private Statement stmt = null;
private boolean userPass, connected;
private Connections connection;
#FXML
private ComboBox<String> sType;
#FXML
public TextField dbName;
#FXML
private TextField sName;
#FXML
private Button loginB;
#FXML
private PasswordField sPassword;
#FXML
private Pane paneL;
#FXML
private GridPane gPane;
#FXML
private ComboBox<String> uType;
ObservableList<String> sLists = FXCollections.observableArrayList("MySQL LOCAL",
"MYSQL REMOTE", "SQL SERVER LOCAL", "SQL SERVER");
ObservableList<String> uList = FXCollections.observableArrayList("Player",
"Admin");
#FXML
public void initialize() {
sType.setItems(sLists);
uType.setItems(uList);
}
#FXML
public void loginBClick (Event event) {
if (isAllFieldFillup()) {
switch(uType.getValue().trim()) {
case "Admin":
if (connectCheck()) {
try {
Parent giantsAdmin = FXMLLoader.load(getClass().getResource("GiantsAdmin.fxml"));
Scene gAdminScene = new Scene(giantsAdmin);
Stage gAdminStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
gAdminStage.hide();
gAdminStage.setScene(gAdminScene);
gAdminStage.setTitle("Giants Admin");
gAdminStage.getScene().getStylesheets().add(getClass().getResource("style.css").toExternalForm());
gAdminStage.show();
}
catch (Exception e) {
}
}
case "Player":
if (connectCheck()) {
try {
Parent giantsPlayer = FXMLLoader.load(getClass().getResource("GiantsPlayer.fxml"));
Scene gPlayerScene = new Scene(giantsPlayer);
Stage gPlayerStage = (Stage) ((Node) event.getSource()).getScene().getWindow();
gPlayerStage.hide();
gPlayerStage.setScene(gPlayerScene);
gPlayerStage.setTitle("Giants Playe");
gPlayerStage.getScene().getStylesheets().add(getClass().getResource("style.css").toExternalForm());
gPlayerStage.show();
}
catch (Exception e) {
}
}
}
}
}
public void closeConnection () {
if (connect != null) {
try {
stmt.close();
connect.close();
}
catch (SQLException e) {
}
}
}
public boolean connectCheck() {
connected = false;
dataName = dbName.getText();
serverName = sName.getText();
password = sPassword.getText();
switch (sType.getValue()) {
case "MySQL LOCAL":
num = 1;
break;
case "MYSQL REMOTE":
num = 2;
break;
case "SQL SERVER LOCAL":
num = 3;
break;
case "SQL SERVER":
num = 4;
break;
default:
}
if (connect == null) {
connect = Connections.getconnect(num, dataName, serverName, password);
}
if (connect == null ) {
System.out.println("Still no connection");
}
if (stmt == null) {
try {
stmt = connect.createStatement();
connected = true;
} catch (SQLException e) {
Alert notify = new Alert(Alert.AlertType.INFORMATION);
notify.setTitle("Blank filed");
notify.setHeaderText(null);
notify.setContentText("Incorrect login.");
notify.showAndWait();
connected = false;
}
}
return connected;
}
private boolean isAllFieldFillup() {
boolean allInfo;
if (sType.getValue().equals("server type") && dbName.getText().isEmpty()
&& sName.getText().isEmpty() && sPassword.getText().isEmpty()) {
Alert notify = new Alert(Alert.AlertType.INFORMATION);
notify.setTitle("Blank filed");
notify.setHeaderText(null);
notify.setContentText("You are missing some information.");
notify.showAndWait();
allInfo = false;
}
else {
allInfo = true;
}
return allInfo;
}
}
Here is my here is the controller for my main window where I have the table
import java.io.IOException;
import java.sql.Statement;
import javafx.collections.*;
import javafx.event.Event;
import javafx.fxml.*;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.stage.Stage;
public class GiantsAdminController {
#FXML
private Button connect = null;
private boolean connected;
private Statement stmt;
#FXML
private TextField aRank;
#FXML
private TextField aName;
#FXML
private TextField aPosition;
#FXML
private TextField aSchool;
#FXML
private TextField aAge;
#FXML
private TextField aWar;
#FXML
private Button clearB;
#FXML
private Button addB;
#FXML
private TableColumn<?, ?> rank;
#FXML
private TableColumn<?, ?> name;
#FXML
private TableColumn<?, ?> position;
#FXML
private TableColumn<?, ?> school;
#FXML
private TableColumn<?, ?> age;
#FXML
private TableColumn<?, ?> war;
#FXML
private TextField qSearch;
#FXML
private Button search;
#FXML
private Button singout;
#FXML
private Button delete;
#FXML
private ComboBox<String> serverType;
#FXML
private TextField dbName;
#FXML
private TextField serverName;
#FXML
private TextField sPassword;
ObservableList<String> sLists = FXCollections.observableArrayList("MySQL LOCAL",
"MYSQL REMOTE", "SQL SERVER LOCAL", "SQL SERVER");
#FXML
public void initialize() {
serverType.setItems(sLists);
}
#FXML
public void clearBClick (Event event) {
aRank.clear();
aName.clear();
aPosition.clear();
aSchool.clear();
aAge.clear();
aWar.clear();
}
#FXML
public void SingOutClick(Event event) throws IOException {
((Node)event.getSource()).getScene().getWindow().hide();
Stage stage = new Stage();
//stage.hide();
Parent giantsLogin = FXMLLoader.load(getClass().getResource("/giants/GiantsLogin.fxml"));
Scene gLScene = new Scene(giantsLogin);
gLScene.getStylesheets().add(getClass().getResource("style.css").toExternalForm());
stage.setScene(gLScene);
stage.show();
}
}
Implement a method in your Controller in which you can set the according stage e.g. public void setMain(Stage main){};
Then try:
FXMLLoader loader = new FXMLLoader(getClass().getResource("Style.fxml"));
Parent root = loader.load();
YourController cc = loader.getController();
cc.setMain(primaryStage);
If you instatiate the loader instead of using the static method
Parent root = FXMLLoader.load("Style.fxml");
you can get access to your controller, pass your main stage and thus get access to the stage inside your controller.
Found a neat sample that really helped with illustrating how DnD works when it drags a values from a list and places it on the panel.
This sample grabs a copy of the list value.
I have since modified the sample to add a JButton. I can DnD this onto the panel but it moves it instead of making a copy.
Is there something specific as to why the JButton was moved instead of copied?
What change is required to have the button copied instead of moved?
I even tried pressing the CTRL key as I dragged the button but it still moved it instead of copying.
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.dnd.*;
import java.io.IOException;
import javax.swing.*;
public class TestDnD {
public static void main(String[] args) {
new TestDnD();
}
public TestDnD() {
EventQueue.invokeLater(new Runnable() {
#Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException ex) {
} catch (InstantiationException ex) {
} catch (IllegalAccessException ex) {
} catch (UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JList list;
public TestPane() {
setLayout(new BorderLayout());
list = new JList();
DefaultListModel model = new DefaultListModel();
model.addElement(new User("Shaun"));
model.addElement(new User("Andy"));
model.addElement(new User("Luke"));
model.addElement(new User("Han"));
model.addElement(new User("Liea"));
model.addElement(new User("Yoda"));
list.setModel(model);
add(new JScrollPane(list), BorderLayout.WEST);
//Without this call, the application does NOT recognize a drag is happening on the LIST.
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
list,
DnDConstants.ACTION_COPY_OR_MOVE,
new DragGestureHandler(list)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
JPanel panel = new JPanel(new GridBagLayout());
add(panel);
//This registers the Target (PANEL) where the Drop is to occur.
DropTarget dt = new DropTarget(
panel,
DnDConstants.ACTION_COPY_OR_MOVE,
new DropTargetHandler(panel), ////DropTargetHandler - is defined below
true); ///and really just implements DropTargetListener
setupButtonTest();
}
private void setupButtonTest()
{
JButton myButton = new JButton("Drag Drop Me");
add(myButton, BorderLayout.NORTH);
DragGestureRecognizer dgr = DragSource.getDefaultDragSource().createDefaultDragGestureRecognizer(
myButton,
DnDConstants.ACTION_COPY, // ACTION_COPY_OR_MOVE,
new DragGestureHandler(myButton)); ///DragGestureHandler - is defined below
///and really just implements DragGestureListener
///and the implemented method defines what is being transferred.
}
}
public static class User {
private String name;
public User(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
////This Class handles the actual item or data being transferred (dragged).
public static class UserTransferable implements Transferable {
public static final DataFlavor JIMS_DATA_FLAVOR = new DataFlavor(User.class, "User");
private User user;
private JButton jbutton;
public UserTransferable(User user) {
this.user = user;
}
public UserTransferable(JButton user) {
this.jbutton = user;
}
#Override
public DataFlavor[] getTransferDataFlavors() {
//Executed as soon as the User Object is dragged.
System.out.println("UserTransferable : getTransferDataFlavors()");
return new DataFlavor[]{JIMS_DATA_FLAVOR};
}
#Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
//This is what is executed once the item is dragged into a JComponent that can accept it.
System.out.println("UserTransferable : isDataFlavorSupported()");
return JIMS_DATA_FLAVOR.equals(flavor);
}
#Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
//Once a Drop is done then this method provides the data to actually drop.
System.out.println("UserTransferable : getTransferData()");
Object value = null;
if (JIMS_DATA_FLAVOR.equals(flavor)) {
if (user != null)
value = user;
else if (jbutton != null)
value = jbutton;
} else {
throw new UnsupportedFlavorException(flavor);
}
return value;
}
}
protected class DragGestureHandler implements DragGestureListener {
private JList list;
private JButton button;
public DragGestureHandler(JList list) {
this.list = list;
}
public DragGestureHandler(JButton list) {
this.button = list;
}
#Override
public void dragGestureRecognized(DragGestureEvent dge) {
//This executes once the dragging starts.
System.out.println("DragGestureHandler : dragGesturRecognized()");
if (dge.getComponent() instanceof JList)
{
Object selectedValue = list.getSelectedValue();
if (selectedValue instanceof User) {
User user = (User) selectedValue;
Transferable t = new UserTransferable(user); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
else if (dge.getComponent() instanceof JButton)
{
Object selectedValue = dge.getComponent();
if (selectedValue instanceof JButton) {
JButton jb = button;
Transferable t = new UserTransferable(jb); ////This is where you define what is being transferred.
DragSource ds = dge.getDragSource();
ds.startDrag(
dge,
null,
t,
new DragSourceHandler());
}
}
}
}
protected class DragSourceHandler implements DragSourceListener {
public void dragEnter(DragSourceDragEvent dsde) {
//This means you have entered a possible Target.
System.out.println("DragSourceHandler : DragEnter()");
}
public void dragOver(DragSourceDragEvent dsde) {
//Continually executes while the DRAG is hovering over an potential TARGET.
System.out.println("DragSourceHandler : DragOver()");
}
public void dropActionChanged(DragSourceDragEvent dsde) {
}
public void dragExit(DragSourceEvent dse) {
//Executes once the potential target has been exited.
System.out.println("DragSourceHandler : DragExit()");
}
public void dragDropEnd(DragSourceDropEvent dsde) {
//Once the mouse button is lifted to do the drop.
//Executes against any potential drop.
System.out.println("DragSourceHandler : dragDropEnd()");
}
}
protected class DropTargetHandler implements DropTargetListener {
////THESE ARE EXECUTED ONLY WHEN THE MOUSE AND DRAGGED ITEM IS OVER THE TARGET.
private JPanel panel;
public DropTargetHandler(JPanel panel) {
this.panel = panel;
}
public void dragEnter(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dragEnter()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
//This shows the outline within the TARGET to indicate it will accept the DROP.
System.out.println(" Accept...");
dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
} else {
//If an item is not registered to accept a certain drop this is executed.
System.out.println(" DropTargetHandler : DragEnter() - Else");
dtde.rejectDrag();
}
}
public void dragOver(DropTargetDragEvent dtde) {
//Active while the item is being Dragged over the Target
System.out.println("DropTargetHandler : dragOver()");
}
public void dropActionChanged(DropTargetDragEvent dtde) {
System.out.println("DropTargetHandler : dropActionChanged()");
}
public void dragExit(DropTargetEvent dte) {
//Once the dragged item is taken out of the Target area.
System.out.println("DropTargetHandler : dragExit()");
}
public void drop(DropTargetDropEvent dtde) {
//Once the mouse button is released to do the Drop then this is executed.
System.out.println("DropTargetHandler : drop()");
if (dtde.getTransferable().isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
Transferable t = dtde.getTransferable();
if (t.isDataFlavorSupported(UserTransferable.JIMS_DATA_FLAVOR)) {
try {
Object transferData = t.getTransferData(UserTransferable.JIMS_DATA_FLAVOR);
if (transferData instanceof User) {
User user = (User) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(new JLabel(user.getName()));
panel.revalidate();
panel.repaint();
}
else if (transferData instanceof JButton) {
JButton jb = (JButton) transferData;
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
panel.add(jb);
panel.revalidate();
panel.repaint();
}
else {
dtde.rejectDrop();
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
dtde.rejectDrop();
} catch (IOException ex) {
ex.printStackTrace();
dtde.rejectDrop();
}
} else {
dtde.rejectDrop();
}
}
}
}
}
I have a fragment that gives me the listView of all songs that that I have stored on my phone. When I click on a particular song in my list, I should be able to play it using a MusicService.
This fragment (menu2_Fragment) is initialized in an ActionBarActivity when a particular drawer item is selected. See following code:
#Override
public void onNavigationDrawerItemSelected(int position) {
Fragment objFragment = null;
switch(position){
case 0:
objFragment = new menu1_Fragment();
getSupportActionBar().setTitle("Scan for Users");
break;
case 1:
objFragment = new menu2_Fragment();
getSupportActionBar().setTitle("Your Music");
// objFragment = new MyMusicFragment();
break;
case 2:
objFragment = new menu3_Fragment();
getSupportActionBar().setTitle("Popular Music");
}
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, objFragment)
.commit();
}
This is the Fragment code:
package com.example.cs446.soundscope;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.MediaController;
import com.example.cs446.soundscope.Adapter.SongAdapter;
import com.example.cs446.soundscope.data.Song;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
/**
* Created by val on 27/02/15.
*/
public class menu2_Fragment extends Fragment implements MediaController.MediaPlayerControl{
View rootview;
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false;
private boolean playbackPaused=false;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
rootview = inflater.inflate(R.layout.activity_main,container, false);
songView = (ListView)rootview.findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
//sort all of the songList by title
Collections.sort(songList, new Comparator<Song>() {
//function that does the sorting
#Override
public int compare(Song lhs, Song rhs) {
return lhs.getTitle().compareTo(rhs.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(getActivity(),songList);
songView.setAdapter(songAdt);
setController();
//startActivity(new Intent(this, MainActivity.class));
return rootview;
}
//get the song information for your filesystem
public void getSongList(){
//use the contentResolver to retrieve the uri for the music file
//a cursor instance is created with the contentResolver
ContentResolver musicResolver = this.getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//store the songs into the song list array list
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//set the controller up
private void setController(){
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.song_list));
controller.setEnabled(true);
}
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
#Override
public void start() {
musicSrv.go();
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
When I click on an item in the ListView, instead of playing the song my app crashes and I receive the following error message:
03-02 00:46:29.142 6485-6485/com.example.cs446.soundscope E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.cs446.soundscope, PID: 6485
java.lang.IllegalStateException: Could not find a method songPicked(View) in the activity class com.example.cs446.soundscope.ListNearbyUsers for onClick handler on view class android.widget.LinearLayout
at android.view.View$1.onClick(View.java:3994)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NoSuchMethodException: songPicked [class android.view.View]
at java.lang.Class.getMethod(Class.java:664)
at java.lang.Class.getMethod(Class.java:643)
at android.view.View$1.onClick(View.java:3987)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
The playing music functionality works fine when it's not implemented inside a Fragment, but instead implemented inside an Activity. Has anyone seen an error like this before?
It means that you didn't declare andoid:onClick="songPicked" in your fragment layout.
And I know you are coming from tutsplus :)
I face the error :
1566-1566/com.example.rom.romproject E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.rom.romproject, PID: 1566
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3823)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.rom.romproject.ContactView.contactFavorite(ContactView.java:37)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3818)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
This happens when im clicking on a button i created.
The button purpose is to insert Data into my sql table.
The SQL class :
public class sqlDatabaseAdapter
{
sqlHelper helper;
public sqlDatabaseAdapter(Context context)
{
helper = new sqlHelper(context);
}
public long insertData(String name, String phone)
{
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues content = new ContentValues();
content.put(sqlHelper.NAME, name);
content.put(sqlHelper.PHONE, phone);
return db.insert(helper.TABLE_NAME, null, content);
}
static class sqlHelper extends SQLiteOpenHelper
{
static final String DATABASE_NAME = "ContactDB";
static final String TABLE_NAME = "Favorites";
static final int DB_VERSION = 1;
static final String UID = "_id";
static final String NAME = "Name";
static final String PHONE = "Phone";
static final String CREATE_TABLE = "CREATE TABLE "+ TABLE_NAME +" ("+UID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+NAME+" VARCHAR(255), "+PHONE+" VARCHAR(255));";
static final String DROP_TABLE = "DROP TABLE IF EXISTS"+TABLE_NAME;
private Context context;
public sqlHelper(Context context)
{
super(context, DATABASE_NAME, null, DB_VERSION);
this.context = context;
Message.Message(context, "Constructor Called");
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(CREATE_TABLE);
Message.Message(context, "onCreate Called");
} catch( SQLException e)
{
Message.Message(context, "" + e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
try {
db.execSQL(DROP_TABLE);
onCreate(db);
Message.Message(context, "OnUpgrade Called");
} catch(SQLException e)
{
Message.Message(context, "" + e);
}
}
}
}
Now, im not rly sure at the source of the problem , so i will post both of my activites.
Btw : the info im trying to insert to the SQL is a contact name and phone
(that i get from the main activity list view).
Main Activity ( List view of phone contacts ) :
public class MainActivity extends ListActivity {
ListView l;
Cursor cursor;
SimpleCursorAdapter listAdapter;
sqlDatabaseAdapter helper;
#Override
public int getSelectedItemPosition()
{
return super.getSelectedItemPosition();
}
#Override
public long getSelectedItemId()
{
return super.getSelectedItemId();
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cursor = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
startManagingCursor(cursor);
String[] from = {ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,ContactsContract.CommonDataKinds.Phone.NUMBER, ContactsContract.CommonDataKinds.Phone._ID};
int[] to = {android.R.id.text1,android.R.id.text2};
listAdapter = new SimpleCursorAdapter(this,android.R.layout.simple_list_item_2,cursor,from,to);
setListAdapter(listAdapter);
l = getListView();
l.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
helper = new sqlDatabaseAdapter(this);
helper.helper.getWritableDatabase();
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
super.onListItemClick(l, v, position, id);
TextView _tempName= (TextView)v.findViewById(android.R.id.text1);
String _temp = _tempName.getText().toString();
TextView _tempPhone = (TextView)v.findViewById(android.R.id.text2);
String _temp2 = _tempPhone.getText().toString();
Intent intent = new Intent(this, ContactView.class);
intent.putExtra("contactName", _temp);
intent.putExtra("contactPhone", _temp2);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The second activity (where the button is ) :
public class ContactView extends ActionBarActivity {
Button _Call;
Button _Favorite;
FavoriteContact contact = new FavoriteContact();
sqlDatabaseAdapter helper;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_view);
_Call = (Button)findViewById(R.id.bCall);
_Favorite = (Button)findViewById(R.id.bFavorite);
contact.setName(getIntent().getExtras().getString("contactName"));
contact.setPhone(getIntent().getExtras().getString("contactPhone"));
setTitle(contact.getName());
}
public void contactFavorite(View view)
{
long id = 0L;
id = helper.insertData(contact.getName(), contact.getPhone());
/*
if( id < 0)
{
Message.Message(this, "Unsuccessful");
}
else
{
Message.Message(this, "Successfully inserted to favorite contacts ");
}
*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_contact_view, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Contact class i created and FavoriteContact class :
(favoritecontact extends Contact)
public class Contact
{
private String Name = null;
private String Phone = null;
public String getPhone() {
return Phone;
}
public void setPhone(String phone) {
Phone = phone;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
}
public class FavoriteContact extends Contact
{
private Boolean isFavorite;
public Boolean getIsFavorite() {
return isFavorite;
}
public void setIsFavorite(Boolean isFavorite) {
this.isFavorite = isFavorite;
}
}
i think i gave everything i need...
sorry for my bad english and its my first time posting here so i dont rly know how it works :D
thanks for every bit of help .
The variable helper is never initialized in ContactView.