Other user Facebook feed error - java

I am trying to fetch facebook feed using graph api in Codename one but it only works with my own account, Whenever other user will try to fetch their feed using my app it throw an error.
Following is my code
public class Test {
private Form current;
private Resources theme;
Form facebook;
Toolbar tb;
Image user;
Label userLabel;
Label username;
Login loginfb;
String clientId = "158093724691158";
String redirectURI = "http://www.codenameone.com/";
String clientSecret = "4f5b275ae702f7b6fde9bc50bfe3b5e3";
Label proLabel;
Label fname;
Label fmail;
Label fgender;
Container container12;
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
// Pro only feature, uncomment if you have a pro subscription
// Log.bindCrashProtection(true);
}
public void start() {
if(current != null){
current.show();
return;
}
try{
Splash spl = new Splash();
spl.show();
new java.util.Timer().schedule(
new java.util.TimerTask() {
#Override
public void run() {
facebook.show();
}
} , 4000);
}catch(IOException e){
e.printStackTrace();
}
facebook = new Form("Facebook", new BoxLayout(BoxLayout.Y_AXIS));
tb = new Toolbar();
facebook.setToolbar(tb);
user = theme.getImage("user.png");
userLabel = new Label(user);
username = new Label("Visitor");
Button facebooklogin = new Button("Login with Facebook");
Button linked = new Button("Login with LinkedIn");
//linked.setUIID("linkedButton");
linked.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
Oauth2 auth2 = new Oauth2("https://www.linkedin.com/oauth/v2/authorization?response_type=code",
"81lq3qpacjvkcu",
"https://www.codenameone.com","r_fullprofile%20r_emailaddress","https://www.linkedin.com/uas/oauth2/accessToken","vzwWfamZ3IUQsJQL");
Oauth2.setBackToParent(true);
auth2.showAuthentication(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
if (evt.getSource() instanceof String) {
String token = (String) evt.getSource();
String expires = Oauth2.getExpires();
System.out.println("Token=" +token + "Expires in " +expires );
} else {
Exception err = (Exception) evt.getSource();
err.printStackTrace();
Dialog.show("Error", "An error occurred while logging in: " + err, "OK", null);
}
}
});
}
});
facebooklogin.addActionListener((evt) -> {
Login fb = FacebookConnect.getInstance();
fb.setClientId(clientId);
fb.setRedirectURI(redirectURI);
fb.setClientSecret(clientSecret);
fb.setScope("user_birthday,user_religion_politics,user_relationships,user_relationship_details,user_hometown,user_location,user_likes,user_education_history,user_work_history,user_website,user_events,user_photos,user_videos,user_friends,user_about_me,user_status,user_games_activity,user_tagged_places,user_posts,rsvp_event,email,read_insights,publish_actions,read_audience_network_insights,read_custom_friendlists,user_action.books,user_action.music,user_action.video,user_action.news,user_action.fitness,user_managed_groups,manage_pages,pages_manage_cta,pages_manage_instant_articles,pages_show_list,publish_pages,read_page_mailboxes,ads_management,ads_read,business_management,pages_messaging,pages_messaging_phone_number,pages_messaging_subscriptions,pages_messaging_payments,public_profile");
loginfb = fb;
fb.setCallback(new LoginListener(LoginListener.FACEBOOK));
if(!fb.isUserLoggedIn()){
fb.doLogin();
}else{
showFacebookUser(fb.getAccessToken().getToken());
}
});
Container container1 = BoxLayout.encloseY(userLabel,username);
container1.setUIID("container1");
tb.addComponentToSideMenu(container1);
tb.addCommandToSideMenu("Home", FontImage.createMaterial(FontImage.MATERIAL_HOME, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Shop by Category", FontImage.createMaterial(FontImage.MATERIAL_ADD_SHOPPING_CART, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Todays Deals", FontImage.createMaterial(FontImage.MATERIAL_LOCAL_OFFER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Orders", FontImage.createMaterial(FontImage.MATERIAL_BOOKMARK_BORDER, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Wish List", FontImage.createMaterial(FontImage.MATERIAL_LIST, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Your Account", FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Gift Cards", FontImage.createMaterial(FontImage.MATERIAL_CARD_GIFTCARD, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Setting", FontImage.createMaterial(FontImage.MATERIAL_SETTINGS, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
tb.addCommandToSideMenu("Logout", FontImage.createMaterial(FontImage.MATERIAL_BACKSPACE, UIManager.getInstance().getComponentStyle("TitleCommand")), (evt) -> {
});
Tabs tab = new Tabs();
Style s = UIManager.getInstance().getComponentStyle("Tab");
FontImage icon1 = FontImage.createMaterial(FontImage.MATERIAL_VPN_KEY, s);
FontImage icon2 = FontImage.createMaterial(FontImage.MATERIAL_LIST, s);
FontImage icon3 = FontImage.createMaterial(FontImage.MATERIAL_ACCOUNT_BOX, s);
Container container11 = BoxLayout.encloseY(facebooklogin,linked);
container12 = BoxLayout.encloseY(new SpanLabel("Some text directly in the tab2"));
Image pro = theme.getImage("user.png");
proLabel = new Label(pro);
Label uname = new Label("Name: ");
fname = new Label("");
Label umail = new Label("Name: ");
fmail = new Label("");
Label ugender = new Label("Name: ");
fgender = new Label("");
Container profileContainer = TableLayout.encloseIn(2, uname,fname,umail,fmail,ugender,fgender);
Container container13 = BoxLayout.encloseY(proLabel,profileContainer);
tab.addTab("Log In",icon1,container11 );
tab.addTab("Wall",icon2, container12 );
tab.addTab("User Profile",icon3, container13);
facebook.add(tab);
}
public void showFacebookUser(String token){
ConnectionRequest conn = new ConnectionRequest(){
#Override
protected void readResponse(InputStream input) throws IOException {
JSONParser parser = new JSONParser();
Map<String, Object> parsed = parser.parseJSON(new InputStreamReader(input, "UTF-8"));
String email = null;
if(email == null){
email=" ";
}
email = (String) parsed.get("email");
String name = (String) parsed.get("name");
String first_name = (String) parsed.get("first_name");
String last_name = (String) parsed.get("last_name");
String gender = (String) parsed.get("gender");
String image = (String) ((Map) ((Map) parsed.get("picture")).get("data")).get("url").toString();
ArrayList<String> data_arr1= (ArrayList) ((Map) parsed.get("feed")).get("data");
JSONArray array = new JSONArray(data_arr1);
Log.p("First NAme : " + first_name);
Log.p("Last Name : " + last_name);
Log.p("Email : " + email);
Log.p("Full Name : " + name);
Log.p("Gender : " + gender);
Log.p("Picture : " +image);
username.setText(name);
userLabel.setIcon(URLImage.createToStorage((EncodedImage) user, "Small_"+image, image, URLImage.RESIZE_SCALE));
proLabel.setIcon(URLImage.createToStorage((EncodedImage) user, image, image, URLImage.RESIZE_SCALE));
fname.setText(name);
fmail.setText(email);
fgender.setText(gender);
ArrayList<String> arrayList = new ArrayList<>();
try{
JSONArray array2 = new JSONArray(array.toString());
for(int i =0; i<array2.length() ; i++){
JSONObject jsonobject = array2.getJSONObject(i);
String story = null;
if(story == null){
story=" ";
}
try {
story = jsonobject.getString("story");
} catch (Exception e) {
e.printStackTrace();
}
String msg = null;
if(msg == null){
msg=" ";
}
try {
msg = jsonobject.getString("message");
} catch (Exception e) {
e.printStackTrace();
}
String full_picture = null;
if(full_picture == null){
full_picture=" ";
}
try{
full_picture = jsonobject.getString("full_picture");
}
catch(Exception e){
e.printStackTrace();
}
Log.p(story);
Log.p(msg);
Log.p(full_picture);
Image wallimage = theme.getImage("blank.jpg");
Label wallimageLabel = new Label(wallimage);
wallimageLabel.setIcon(URLImage.createToStorage((EncodedImage) wallimage, full_picture, full_picture, URLImage.RESIZE_SCALE));
Label wallstory = new Label(story);
Label wallmessage = new Label(msg);
Container wallcontainer = BoxLayout.encloseY(wallmessage,wallstory,wallimageLabel);
container12.add(wallcontainer);
}
}catch(Exception e){
e.printStackTrace();
}
}
};
conn.setPost(false);
conn.setUrl("https://graph.facebook.com/v2.8/me");
conn.addArgumentNoEncoding("access_token", token); //this statement is used to patch access token with url
conn.addArgumentNoEncoding("fields", "email,name,first_name,last_name,gender,picture.width(512).height(512),feed{name,full_picture,message,story},posts");
//above statement is used to provide permission through url so server send data with respect ot permissions.
NetworkManager.getInstance().addToQueue(conn);
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
public class LoginListener extends LoginCallback {
public static final int FACEBOOK = 0;
private int loginType;
public LoginListener(int loginType) {
this.loginType = loginType;
}
public void loginSuccessful() {
try {
AccessToken token = loginfb.getAccessToken();
if (loginType == FACEBOOK) {
showFacebookUser(token.getToken());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void loginFailed(String errorMessage) {
Dialog.show("Login Failed", errorMessage, "Ok", null);
}
}
}
And throws following error:
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
java.lang.NullPointerException
at com.grv.test.Test$3.readResponse(Test.java:220)
at com.codename1.io.ConnectionRequest.performOperation(ConnectionRequest.java:733)
at com.codename1.io.NetworkManager$NetworkThread.run(NetworkManager.java:282)
at com.codename1.impl.CodenameOneThread.run(CodenameOneThread.java:176)
I just want to know that why this application not able to fetch facebook feed from other user account.

Related

Trying to create javafx app that allows the user to easily monitor and maintain a list of websites in embedded derby database

I want to allow the user to drag and drop a link onto the list, which will enter the URL into the database, allow the user to view all links, articles, or something similar on the page in the upper right corner(even simple details such as title and when link was added would be fine), and then view the webview. I cant get it to correctly display the URL details in the upper right corner, or display the webview correctly in the bottom right. I am very familiar with javafx and derby, just not so much with the web aspect. Any help would be greatly appreciated. As of now, the URL can be dragged and dropped onto the list, and the title and some details are displayed incorrectly in the upper right. The webview doesn't work either most of the time. The hyperlink doesn't get displayed correctly in the list either, but that is just some formatting that needs fixed. The end goal is just to allow the user to monitor new posts, articles, or news, on the URLs they enter.
DBUtils.java
public class DBUtils {
final static Properties props = new Properties();
static {
props.put("user", "admin");
props.put("password", "letmein");
}
private static String framework = "embedded";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
private static String protocol = "jdbc:derby:";
public static void setupDb() {
loadDriver();
Connection conn = null;
ArrayList statements = new ArrayList();
Statement s = null;
ResultSet rs = null;
try {
String dbName = "UrlDB";
conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);
System.out.println("Creating database " + dbName);
boolean createTable = false;
s = conn.createStatement();
try {
s.executeQuery("SELECT count(*) FROM urlFeed");
} catch (Exception e) {
createTable = true;
}
if (createTable) {
conn.setAutoCommit(false);
s = conn.createStatement();
statements.add(s);
s.execute("CREATE TABLE UrlFeed(ID INT, Title VARCHAR(255), Url VARCHAR(600))");
System.out.println("Created table UrlFeed ");
conn.commit();
}
shutdown();
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
close(rs);
int i = 0;
while (!statements.isEmpty()) {
Statement st = (Statement) statements.remove(i);
close(st);
}
close(conn);
}}
public static List<UrlFeed> loadFeeds() {
loadDriver();
Connection conn = null;
ResultSet rs = null;
List<UrlFeed> feeds = new ArrayList<>();
try {
String dbName = "UrlDB";
conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);
rs = conn.createStatement().executeQuery("SELECT ID, Title, Url FROM UrlFeed");
while (rs.next()) {
String title = rs.getString("title");
String url = rs.getString("url");
UrlFeed urlFeed = new UrlFeed(title, url);
urlFeed.id = urlFeed.link.hashCode();
feeds.add(urlFeed);
}
shutdown();
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
close(rs);
close(conn);
}
return feeds;
}
private static void shutdown() {
if (framework.equals("embedded")) {
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
} catch (SQLException se) {
if (((se.getErrorCode() == 50000)
&& ("XJ015".equals(se.getSQLState())))) {
System.out.println("Derby shut down normally");
} else {
System.err.println("Derby did not shut down normally");
se.printStackTrace();
}}
}}
public static int saveUrlFeed(UrlFeed urlFeed) {
int pk = urlFeed.link.hashCode();
loadDriver();
Connection conn = null;
ArrayList statements = new ArrayList();
PreparedStatement psInsert = null;
Statement s = null;
ResultSet rs = null;
try {
String dbName = "UrlDB";
conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);
rs = conn.createStatement().executeQuery("SELECT COUNT(id) FROM UrlFeed WHERE id = " + urlFeed.link.hashCode());
rs.next();
int count = rs.getInt(1);
if (count == 0) {
conn.setAutoCommit(false);
s = conn.createStatement();
statements.add(s);
psInsert = conn.prepareStatement("INSERT INTO UrlFeed VALUES (?, ?, ?)");
statements.add(psInsert);
psInsert.setInt(1, pk);
String escapeTitle = urlFeed.channelTitle.replaceAll("\'", "''");
psInsert.setString(2, escapeTitle);
psInsert.setString(3, urlFeed.link);
psInsert.executeUpdate();
conn.commit();
System.out.println("Inserted " + urlFeed.channelTitle + " " + urlFeed.link);
System.out.println("Committed the transaction");
}
shutdown();
} catch (SQLException sqle) {
sqle.printStackTrace();
} finally {
close(rs);
int i = 0;
while (!statements.isEmpty()) {
Statement st = (Statement) statements.remove(i);
close(st);
}
close(conn);
}
return pk;
}
private static void close(AutoCloseable closable) {
try {
if (closable != null) {
closable.close();
closable = null;
}
} catch (Exception sqle) {
sqle.printStackTrace();
}
}
private static void loadDriver() {
try {
Class.forName(driver);
System.out.println("Loaded driver");
} catch (Exception e) {
e.printStackTrace();
}
}
}
DisplayContentsFromDatabase.java
public class DisplayContentsFromDatabase extends Application {
#Override public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 640, 480, Color.WHITE);
final Map<String, Hyperlink> hyperLinksMap = new TreeMap<>();
final WebView newsBrief = new WebView();
final WebEngine webEngine = new WebEngine();
final WebView websiteView = new WebView();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<State>() {
public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue){
if (newValue != State.SUCCEEDED) {
return;
}
UrlFeed urlFeed = parse(webEngine.getDocument(), webEngine.getLocation());
hyperLinksMap.get(webEngine.getLocation()).setText(urlFeed.channelTitle);
StringBuilder urlSource = new StringBuilder();
urlSource.append("<head>\n")
.append("</head>\n")
.append("<body>\n");
urlSource.append("<b>")
.append(urlFeed.channelTitle)
.append(" (")
.append(urlFeed.news.size())
.append(")")
.append("</b><br />\n");
StringBuilder htmlArticleSb = new StringBuilder();
for (NewsArticle article:urlFeed.news) {
htmlArticleSb.append("<hr />\n")
.append("<b>\n")
.append(article.title)
.append("</b><br />")
.append(article.pubDate)
.append("<br />")
.append(article.description)
.append("<br />\n")
.append("<input type=\"button\" onclick=\"alert('")
.append(article.link)
.append("')\" value=\"View\" />\n");
}
String content = urlSource.toString() + "<form>\n" + htmlArticleSb.toString() + "</form></body>\n";
System.out.println(content);
newsBrief.getEngine().loadContent(content);
DBUtils.saveUrlFeed(urlFeed);
}
});
newsBrief.getEngine().setOnAlert(new EventHandler<WebEvent<String>>(){
public void handle(WebEvent<String> evt) {
websiteView.getEngine().load(evt.getData());
}
});
SplitPane splitPane = new SplitPane();
splitPane.prefWidthProperty().bind(scene.widthProperty());
splitPane.prefHeightProperty().bind(scene.heightProperty());
final VBox leftArea = new VBox(10);
final TextField urlField = new TextField();
urlField.setOnAction(new EventHandler<ActionEvent>(){
public void handle(ActionEvent ae){
String url = urlField.getText();
final Hyperlink jfxHyperLink = createHyperLink(url, webEngine);
hyperLinksMap.put(url, jfxHyperLink);
HBox rowBox = new HBox(20);
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
webEngine.load(url);
urlField.setText("");
}
});
leftArea.getChildren().add(urlField);
List<UrlFeed> urlFeeds = DBUtils.loadFeeds();
for (UrlFeed feed:urlFeeds) {
HBox rowBox = new HBox(20);
final Hyperlink jfxHyperLink = new Hyperlink(feed.channelTitle);
jfxHyperLink.setUserData(feed);
final String location = feed.link;
hyperLinksMap.put(feed.link, jfxHyperLink);
jfxHyperLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
webEngine.load(location);
}
}
);
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
}
scene.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasUrl()) {
event.acceptTransferModes(TransferMode.COPY);
} else {
event.consume();
}
}
});
scene.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
HBox rowBox = new HBox(20);
if (db.hasUrl()) {
if (!hyperLinksMap.containsKey(db.getUrl())) {
final Hyperlink jfxHyperLink = createHyperLink(db.getUrl(), webEngine);
hyperLinksMap.put(db.getUrl(), jfxHyperLink);
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
}
webEngine.load(db.getUrl());
}
event.setDropCompleted(success);
event.consume();
}
});
leftArea.setAlignment(Pos.TOP_LEFT);
SplitPane splitPane2 = new SplitPane();
splitPane2.setOrientation(Orientation.VERTICAL);
splitPane2.prefWidthProperty().bind(scene.widthProperty());
splitPane2.prefHeightProperty().bind(scene.heightProperty());
HBox centerArea = new HBox();
centerArea.getChildren().add(newsBrief);
HBox rightArea = new HBox();
rightArea.getChildren().add(websiteView);
splitPane2.getItems().add(centerArea);
splitPane2.getItems().add(rightArea);
splitPane.getItems().add(leftArea);
splitPane.getItems().add(splitPane2);
newsBrief.prefWidthProperty().bind(scene.widthProperty());
websiteView.prefWidthProperty().bind(scene.widthProperty());
ObservableList<SplitPane.Divider> dividers = splitPane.getDividers();
for (int i = 0; i < dividers.size(); i++) {
dividers.get(i).setPosition((i + 1.0) / 3);
}
HBox hbox = new HBox();
hbox.getChildren().add(splitPane);
root.getChildren().add(hbox);
stage.setScene(scene);
stage.show();
}
private static UrlFeed parse(Document doc, String location) {
UrlFeed urlFeed = new UrlFeed();
urlFeed.link = location;
urlFeed.channelTitle = doc.getElementsByTagName("title")
.item(0)
.getTextContent();
NodeList items = doc.getElementsByTagName("item");
for (int i=0; i<items.getLength(); i++){
Map<String, String> childElements = new HashMap<>();
NewsArticle article = new NewsArticle();
for (int j=0; j<items.item(i).getChildNodes().getLength(); j++) {
Node node = items.item(i).getChildNodes().item(j);
childElements.put(node.getNodeName().toLowerCase(), node.getTextContent());
}
article.title = childElements.get("title");
article.description = childElements.get("description");
article.link = childElements.get("link");
article.pubDate = childElements.get("pubdate");
urlFeed.news.add(article);
}
return urlFeed;
}
private Hyperlink createHyperLink(String url, final WebEngine webEngine) {
final Hyperlink jfxHyperLink = new Hyperlink("Loading News...");
UrlFeed aFeed = new UrlFeed();
aFeed.link = url;
jfxHyperLink.setUserData(aFeed);
jfxHyperLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
UrlFeed urlFeed = (UrlFeed)jfxHyperLink.getUserData();
webEngine.load(urlFeed.link);
}
});
return jfxHyperLink;
}
public static void main(String[] args){
DBUtils.setupDb();
Application.launch(args);
}
}
class UrlFeed {
int id;
String channelTitle = "News...";
String link;
List<NewsArticle> news = new ArrayList<>();
public String toString() {
return "urlFeed{" + "id=" + id + ", channelTitle=" + channelTitle + ", link=" + link + ", news=" + news + '}';
}
public UrlFeed() {
}
public UrlFeed(String title, String link) {
this.channelTitle = title;
this.link = link;
}
}
class NewsArticle {
String title;
String description;
String link;
String pubDate;
public String toString() {
return "NewsArticle{" + "title=" + title + ", description=" + description + ", link=" + link + ", pubDate=" + pubDate + ", enclosure=" + '}';
}
}
I copied your code and refactored it.
Catching exceptions and only printing the stack trace means that the program will continue to run. If you can't load the JDBC driver, for example, then what's the point of continuing? The entire program depends on being able to interact with the database.
Exceptions that you cannot recover from should cause the program to terminate. Either the exception is out of your control or it indicates a bug in your program.
Note, however, that it is safe to ignore SQLException when you fail to close a Statement or ResultSet since the program should be able to continue even though the ResultSet/Statement was not closed.
Your JDBC code should use try-with-resources.
You can use class java.sql.DatabaseMetaData to check whether a table exists.
You only need to load the JDBC driver class once.
You should only shut down the database when the program terminates.
Although WebEngine will successfully load the URL that you entered in the urlField, the value returned by method getLocation() may not be identical to what you entered and hence hyperLinksMap will not contain the key you search for. As a result hyperLinksMap.get(webEngine.getLocation()) will return null which means that the following line of your code will throw NullPointerException.
hyperLinksMap.get(webEngine.getLocation()).setText(urlFeed.channelTitle);
You should also handle the case where WebEngine fails to load the URL entered by the user.
Here is the refactored code. Note that I made all the classes public classes.
Class DisplayContentsFromDatabase
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import javafx.application.Application;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.ObservableList;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TextField;
import javafx.scene.input.DragEvent;
import javafx.scene.input.Dragboard;
import javafx.scene.input.TransferMode;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebEvent;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
public class DisplayContentsFromDatabase extends Application {
#Override
public void start(Stage stage) throws Exception {
Group root = new Group();
Scene scene = new Scene(root, 640, 480, Color.WHITE);
final Map<String, Hyperlink> hyperLinksMap = new TreeMap<>();
final WebView newsBrief = new WebView();
final WebEngine webEngine = new WebEngine();
final WebView websiteView = new WebView();
webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
public void changed(ObservableValue<? extends Worker.State> observable,
Worker.State oldValue,
Worker.State newValue) {
if (newValue != Worker.State.SUCCEEDED) {
System.out.println("Worker.State = " + newValue);
if (newValue == Worker.State.FAILED) {
System.out.println("Failed to load URL.");
}
return;
}
UrlFeed urlFeed = parse(webEngine.getDocument(), webEngine.getLocation());
String location = webEngine.getLocation();
System.out.println("Web location: " + location);
Hyperlink link = hyperLinksMap.get(location);
if (link == null) {
System.out.println("Web location mismatch.");
return;
}
link.setText(urlFeed.channelTitle);
StringBuilder urlSource = new StringBuilder();
urlSource.append("<head>\n").append("</head>\n").append("<body>\n");
urlSource.append("<b>").append(urlFeed.channelTitle).append(" (")
.append(urlFeed.news.size()).append(")").append("</b><br />\n");
StringBuilder htmlArticleSb = new StringBuilder();
for (NewsArticle article : urlFeed.news) {
htmlArticleSb.append("<hr />\n").append("<b>\n").append(article.title)
.append("</b><br />").append(article.pubDate).append("<br />")
.append(article.description).append("<br />\n")
.append("<input type=\"button\" onclick=\"alert('").append(article.link)
.append("')\" value=\"View\" />\n");
}
String content = urlSource.toString() + "<form>\n" + htmlArticleSb.toString()
+ "</form></body>\n";
System.out.println(content);
newsBrief.getEngine().loadContent(content);
try {
DBUtils.saveUrlFeed(urlFeed);
}
catch (ClassNotFoundException | SQLException x) {
throw new RuntimeException(x);
}
}
});
newsBrief.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
public void handle(WebEvent<String> evt) {
websiteView.getEngine().load(evt.getData());
}
});
SplitPane splitPane = new SplitPane();
splitPane.prefWidthProperty().bind(scene.widthProperty());
splitPane.prefHeightProperty().bind(scene.heightProperty());
final VBox leftArea = new VBox(10);
final TextField urlField = new TextField();
urlField.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent ae) {
String url = urlField.getText();
final Hyperlink jfxHyperLink = createHyperLink(url, webEngine);
hyperLinksMap.put(url, jfxHyperLink);
HBox rowBox = new HBox(20);
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
webEngine.load(url);
urlField.setText("");
}
});
leftArea.getChildren().add(urlField);
List<UrlFeed> urlFeeds = DBUtils.loadFeeds();
for (UrlFeed feed : urlFeeds) {
HBox rowBox = new HBox(20);
final Hyperlink jfxHyperLink = new Hyperlink(feed.channelTitle);
jfxHyperLink.setUserData(feed);
final String location = feed.link;
hyperLinksMap.put(feed.link, jfxHyperLink);
jfxHyperLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
webEngine.load(location);
}
});
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
}
scene.setOnDragOver(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
if (db.hasUrl()) {
event.acceptTransferModes(TransferMode.COPY);
}
else {
event.consume();
}
}
});
scene.setOnDragDropped(new EventHandler<DragEvent>() {
#Override
public void handle(DragEvent event) {
Dragboard db = event.getDragboard();
boolean success = false;
HBox rowBox = new HBox(20);
if (db.hasUrl()) {
if (!hyperLinksMap.containsKey(db.getUrl())) {
final Hyperlink jfxHyperLink = createHyperLink(db.getUrl(), webEngine);
hyperLinksMap.put(db.getUrl(), jfxHyperLink);
rowBox.getChildren().add(jfxHyperLink);
leftArea.getChildren().add(rowBox);
}
webEngine.load(db.getUrl());
}
event.setDropCompleted(success);
event.consume();
}
});
leftArea.setAlignment(Pos.TOP_LEFT);
SplitPane splitPane2 = new SplitPane();
splitPane2.setOrientation(Orientation.VERTICAL);
splitPane2.prefWidthProperty().bind(scene.widthProperty());
splitPane2.prefHeightProperty().bind(scene.heightProperty());
HBox centerArea = new HBox();
centerArea.getChildren().add(newsBrief);
HBox rightArea = new HBox();
rightArea.getChildren().add(websiteView);
splitPane2.getItems().add(centerArea);
splitPane2.getItems().add(rightArea);
splitPane.getItems().add(leftArea);
splitPane.getItems().add(splitPane2);
newsBrief.prefWidthProperty().bind(scene.widthProperty());
websiteView.prefWidthProperty().bind(scene.widthProperty());
ObservableList<SplitPane.Divider> dividers = splitPane.getDividers();
for (int i = 0; i < dividers.size(); i++) { dividers.get(i).setPosition((i + 1.0) / 3); }
HBox hbox = new HBox();
hbox.getChildren().add(splitPane);
root.getChildren().add(hbox);
stage.setScene(scene);
stage.show();
}
public void stop() throws Exception {
DBUtils.shutdown();
}
private static UrlFeed parse(Document doc, String location) {
UrlFeed urlFeed = new UrlFeed();
urlFeed.link = location;
urlFeed.channelTitle = doc.getElementsByTagName("title").item(0).getTextContent();
NodeList items = doc.getElementsByTagName("item");
for (int i = 0; i < items.getLength(); i++) {
Map<String, String> childElements = new HashMap<>();
NewsArticle article = new NewsArticle();
for (int j = 0; j < items.item(i).getChildNodes().getLength(); j++) {
Node node = items.item(i).getChildNodes().item(j);
childElements.put(node.getNodeName().toLowerCase(), node.getTextContent());
}
article.title = childElements.get("title");
article.description = childElements.get("description");
article.link = childElements.get("link");
article.pubDate = childElements.get("pubdate");
urlFeed.news.add(article);
}
return urlFeed;
}
private Hyperlink createHyperLink(String url, final WebEngine webEngine) {
final Hyperlink jfxHyperLink = new Hyperlink("Loading News...");
UrlFeed aFeed = new UrlFeed();
aFeed.link = url;
jfxHyperLink.setUserData(aFeed);
jfxHyperLink.setOnAction(new EventHandler<ActionEvent>() {
public void handle(ActionEvent evt) {
UrlFeed urlFeed = (UrlFeed) jfxHyperLink.getUserData();
webEngine.load(urlFeed.link);
}
});
return jfxHyperLink;
}
public static void main(String[] args) {
try {
DBUtils.setupDb();
Application.launch(args);
}
catch (Exception x) {
x.printStackTrace();
}
}
}
Class DBUtil
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class DBUtils {
final static Properties props = new Properties();
static {
props.put("user", "admin");
props.put("password", "letmein");
}
private static boolean loaded;
private static String framework = "embedded";
private static String driver = "org.apache.derby.jdbc.EmbeddedDriver";
private static String protocol = "jdbc:derby:";
public static void setupDb() throws ClassNotFoundException, SQLException {
loadDriver();
Statement s = null;
ResultSet rs = null;
String dbName = "UrlDB";
try (Connection conn = DriverManager.getConnection(protocol + dbName + ";create=true",
props)) {
System.out.println("Creating database " + dbName);
DatabaseMetaData dbmd = conn.getMetaData();
rs = dbmd.getTables(null, null, "URLFEED", null);
boolean createTable = !rs.next();
if (createTable) {
s = conn.createStatement();
s.execute("CREATE TABLE UrlFeed(ID INT, Title VARCHAR(255), Url VARCHAR(600))");
System.out.println("Created database table 'UrlFeed'.");
}
else {
System.out.println("Database table 'UrlFeed' already exists.");
}
}
finally {
if (rs != null) {
try {
rs.close();
}
catch (SQLException xSql) {
// Ignore.
}
}
if (s != null) {
try {
s.close();
}
catch (SQLException xSql) {
// Ignore.
}
}
}
}
public static List<UrlFeed> loadFeeds() throws ClassNotFoundException, SQLException {
loadDriver();
List<UrlFeed> feeds = new ArrayList<>();
String dbName = "UrlDB";
try (Connection conn = DriverManager.getConnection(protocol + dbName + ";create=true",
props);
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT ID, Title, Url FROM UrlFeed")) {
while (rs.next()) {
String title = rs.getString("title");
String url = rs.getString("url");
UrlFeed urlFeed = new UrlFeed(title, url);
urlFeed.id = urlFeed.link.hashCode();
feeds.add(urlFeed);
}
}
return feeds;
}
public static void shutdown() {
if (framework.equals("embedded")) {
try {
DriverManager.getConnection("jdbc:derby:;shutdown=true");
}
catch (SQLException se) {
if (((se.getErrorCode() == 50000) && ("XJ015".equals(se.getSQLState())))) {
System.out.println("Derby shut down normally");
}
else {
System.err.println("Derby did not shut down normally");
se.printStackTrace();
}
}
}
}
public static int saveUrlFeed(UrlFeed urlFeed) throws ClassNotFoundException, SQLException {
int pk = urlFeed.link.hashCode();
loadDriver();
PreparedStatement psInsert = null;
ResultSet rs = null;
String dbName = "UrlDB";
try (Connection conn = DriverManager.getConnection(protocol + dbName + ";create=true",
props);
PreparedStatement s = conn.prepareStatement("SELECT COUNT(id) FROM UrlFeed WHERE id = ?")) {
s.setInt(1, pk);
rs = s.executeQuery();
rs.next();
int count = rs.getInt(1);
if (count == 0) {
psInsert = conn.prepareStatement("INSERT INTO UrlFeed VALUES (?, ?, ?)");
psInsert.setInt(1, pk);
String escapeTitle = urlFeed.channelTitle.replaceAll("\'", "''");
psInsert.setString(2, escapeTitle);
psInsert.setString(3, urlFeed.link);
count = psInsert.executeUpdate();
System.out.println("Inserted " + urlFeed.channelTitle + " " + urlFeed.link);
}
}
finally {
close(rs);
close(psInsert);
}
return pk;
}
private static void close(AutoCloseable closable) {
try {
if (closable != null) {
closable.close();
closable = null;
}
}
catch (Exception sqle) {
sqle.printStackTrace();
}
}
private static void loadDriver() throws ClassNotFoundException {
if (!loaded) {
Class.forName(driver);
System.out.println("Loaded driver");
loaded = true;
}
}
}
Class UrlFeed
import java.util.ArrayList;
import java.util.List;
public class UrlFeed {
int id;
String channelTitle = "News...";
String link;
List<NewsArticle> news = new ArrayList<>();
public String toString() {
return String.format("urlFeed{id=%s, channelTitle=%s, link=%s, news=%s}",
id,
channelTitle,
link,
news);
}
public UrlFeed() {
}
public UrlFeed(String title, String link) {
this.channelTitle = title;
this.link = link;
}
}
Class NewsArticle
public class NewsArticle {
String title;
String description;
String link;
String pubDate;
public String toString() {
return String.format("NewsArticle{title=%s, description=%s, link=%s, pubDate=%s, enclosure=}",
title,
description,
link,
pubDate);
}
}
Currently the above code only prints to standard output. You should change that so that the user is made aware, via the GUI, of what the program is doing. For example, while the Web page is loading, you could display a progress indicator. And when WebEngine fails to load the entered URL, you could display an alert.
EDIT
In response to your comment, where you wrote:
the webview doesn't seem to be loading in the bottom right. Any suggestions?
I believe you are referring to local variable websiteView in method start of class DisplayContentsFromDatabase, i.e.
final WebView websiteView = new WebView();
The only part of your code that references that variable is as follows (also in method start):
newsBrief.getEngine().setOnAlert(new EventHandler<WebEvent<String>>() {
public void handle(WebEvent<String> evt) {
websiteView.getEngine().load(evt.getData());
}
});
Here is a quote from the javadoc of method setOnAlert:
Sets the value of the property onAlert.
Property Description:JavaScript alert handler property. This handler is invokedwhen a script running on the Web page calls the alert function.
So you need to enter a URL for a Web page that contains JavaScript and that JavaScript displays an alert. Only then will the code try to load something and display it in websiteView. I beg your pardon, but I'm not going to try to test that code.

Trying to add data to tableView from arrayList (javaFx)

I am trying to populate the tableView with the data that is in the observableList but it will not show up when i run the program.
Here are parts of my program:
private TableView<Crypto> tableView = new TableView<Crypto>();
private static ArrayList<Crypto> cryptoData = new ArrayList();
private static ObservableList<Crypto> data = FXCollections.observableArrayList(cryptoData);
//*******Crypto Class************
static class Crypto{
private SimpleStringProperty coinName,
coinsBought,
costPerCoin,
totalSpent,
currentPrice,
currentValue,
profit,
roi;
public String getcoinName() {
return coinName.get();
}
public String getCoinsBought() {
return coinsBought.get();
}
public String getCostPerCoin() {
return costPerCoin.get();
}
public String getTotalSpent() {
return totalSpent.get();
}
public String getCurrentPrice() {
return currentPrice.get();
}
public String getCurrentValue() {
return currentValue.get();
}
public String getProfit() {
return profit.get();
}
public String getRoi() {
return roi.get();
}
Crypto(String name, String numBought, String costPerCoin, String totalSpent, String curPrice, String curValue, String profit, String roi){
this.coinName = new SimpleStringProperty(name);
this.coinsBought = new SimpleStringProperty(numBought);
this.costPerCoin = new SimpleStringProperty(costPerCoin);
this.totalSpent = new SimpleStringProperty(totalSpent);
this.currentPrice = new SimpleStringProperty(curPrice);
this.currentValue = new SimpleStringProperty(curValue);
this.profit = new SimpleStringProperty(profit);
this.roi = new SimpleStringProperty(roi);
}
#Override
public String toString() {
return ("[" + coinName.get() + ", " + coinsBought.get() + ", " + costPerCoin.get() + ", " +
totalSpent.get() + ", " + currentPrice.get() + ", " + currentValue.get() + ", " +
profit.get() + ", " + roi.get() + "]");
}
}//*********END Crypto Class*************
#Override
public void start(Stage primaryStage) {
try {
GridPane root = new GridPane();
//title text
Text titleText = new Text();
titleText.setText("Crypto Portfolio");
titleText.setY(600);
titleText.setFont(Font.font("Veranda", FontWeight.BOLD, FontPosture.REGULAR,40));
//refresh button
Button refresh = new Button("Refresh Prices");
refresh.setOnAction(e -> {
//ADD button refresh
});
//total amount text
Text totalDollar = new Text();
totalDollar.setText(getTotalDollar());
//table columns
TableColumn coinColumn = new TableColumn("Coin");
coinColumn.setCellValueFactory(new PropertyValueFactory<>("coinName"));
TableColumn costColumn = new TableColumn("Cost");
costColumn.setCellValueFactory(new PropertyValueFactory<>("totalSpent"));
TableColumn coinBoughtColumn = new TableColumn("Coins Bought");
coinBoughtColumn.setCellValueFactory(new PropertyValueFactory<>("coinsBought"));
TableColumn costPerCoinColumn = new TableColumn("Cost per Coin");
costPerCoinColumn.setCellValueFactory(new PropertyValueFactory<>("costPerCoin"));
TableColumn currentPriceColumn = new TableColumn("Current Coin Price");
currentPriceColumn.setCellValueFactory(new PropertyValueFactory<>("currentPrice"));
TableColumn currentValueColumn = new TableColumn("Curren Value");
currentValueColumn.setCellValueFactory(new PropertyValueFactory<>("currentValue"));
TableColumn profitColumn = new TableColumn("Profit");
profitColumn.setCellValueFactory(new PropertyValueFactory<>("profit"));
TableColumn roiColumn = new TableColumn("ROI");
roiColumn.setCellValueFactory(new PropertyValueFactory<>("roi"));
tableView.setItems(data);
tableView.getColumns().addAll(coinColumn, costColumn, coinBoughtColumn, costPerCoinColumn, currentPriceColumn, currentValueColumn, profitColumn, roiColumn);
Scene scene = new Scene(root,1200,900);
scene.getStylesheets().add(getClass().getResource("application.css").toExternalForm());
root.setHgap(10);
root.setVgap(10);
//sets gridLines visible for debug
root.setGridLinesVisible(true);
primaryStage.setScene(scene);
primaryStage.setTitle("Mike's Crypto Portfolio");
root.add(titleText, 0,0);
root.add(refresh, 3, 0);
root.add(tableView, 0, 1);
primaryStage.show();
new Thread () {
#Override
public void run() {
try {
readCSV("crypto.csv");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
};
}.start();
} catch(Exception e) {
e.printStackTrace();
}
}//*****************END Start***************************
}
I thought if I added this it would work but I get a WARNING: Can not retrieve property 'coinName' in PropertyValueFactory: javafx.scene.control.cell.PropertyValueFactory#2cc2c23 with provided class type: class application.Main$Crypto java.lang.IllegalStateException: Cannot read from unreadable property coinName
but for everything besides coinName the error also adds :java.lang.RuntimeException: java.lang.IllegalAccessException: class com.sun.javafx.reflect.Trampoline cannot access a member of class application.Main$Crypto with modifiers "public"
for(Crypto coin : cryptoData) {
data.add(coin);
}

JTextArea not updating when selection changes in JComboBox

I am trying to add a class for each course in the drop down menu on the right corner of the image, as shown in the code in the action Performed there is one class but the same class opens for all the courses so how can i make each one of them open a different class?
this part is confusing me im not sure if i need to do anything with it or not
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
the list of courses in the left corner works perfectly fine with me but my only problem is instead of the list on the left i want the list on the right to work and it has something to do with crse
public class CourseWork extends JFrame implements ActionListener, KeyListener {
CommonCode cc = new CommonCode();
JPanel pnl = new JPanel(new BorderLayout());
JTextArea txtNewNote = new JTextArea();
JTextArea txtDisplayNotes = new JTextArea();
JTextField search = new JTextField();
ArrayList<String> note = new ArrayList<>();
ArrayList<String> course = new ArrayList<>();
JComboBox courseList = new JComboBox();
String crse = "";
AllNotes allNotes = new AllNotes();
public static void main(String[] args) {
// This is required for the coursework.
//JOptionPane.showMessageDialog(null, "Racha Chaouby");
CourseWork prg = new CourseWork();
}
// Using MVC
public CourseWork() {
model();
view();
controller();
}
#Override
public void actionPerformed(ActionEvent ae) {
if ("Close".equals(ae.getActionCommand())) {
}
if ("Course".equals(ae.getActionCommand())) {
crse = courseList.getSelectedItem().toString();
COMP1752 cw = new COMP1752();
}
if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
}
if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
}
if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
}
if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
if ("Course1752".equals(ae.getActionCommand())) {
COMP1752 cw = new COMP1752();
}
if ("Course1753".equals(ae.getActionCommand())) {
COMP1753 cw = new COMP1753();
}
if ("Cours1110".equals(ae.getActionCommand())) {
MATH1110 cw = new MATH1110();
}
}
#Override
public void keyTyped(KeyEvent e) {
System.out.println("keyTyped not coded yet.");
}
#Override
public void keyPressed(KeyEvent e) {
System.out.println("keyPressed not coded yet.");
}
#Override
public void keyReleased(KeyEvent e) {
System.out.println("keyReleased not coded yet.");
}
private void model() {
course.add("COMP1752");
course.add("COMP1753");
course.add("MATH1110");
crse = course.get(0);
//Note nt = new Note();
//nt.noteID = 1;
//t.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "Arrays are of fixed length and are inflexible.";
//allNotes.allNotes.add(nt);
//nt = new Note();
//nt.noteID = 2;
//nt.dayte = getDateAndTime();
//nt.course = crse;
//nt.note = "ArraysList can be added to and items can be deleted.";
//allNotes.allNotes.add(nt);
}
private void view() {
Font fnt = new Font("Georgia", Font.PLAIN, 24);
JMenuBar menuBar = new JMenuBar();
JMenu kurs = new JMenu();
kurs = new JMenu("Courses");
kurs.setToolTipText("Course tasks");
kurs.setFont(fnt);
kurs.add(makeMenuItem("COMP1752", "Course1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("COMP1753", "Course1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("MATH1110", "Course1110", "Coursework requirments.", fnt));
menuBar.add(kurs);
JMenu note = new JMenu();
note = new JMenu("Note");
note.setToolTipText("Note tasks");
note.setFont(fnt);
note.add(makeMenuItem("New", "NewNote", "Create a new note.", fnt));
note.addSeparator();
note.add(makeMenuItem("Close", "Close", "Clear the current note.", fnt));
menuBar.add(note);
menuBar.add(makeMenuItem("Exit", "Exit", "Close this program", fnt));
// This will add each course to the combobox
for (String crse : course) {
courseList.addItem(crse);
}
courseList.setFont(fnt);
courseList.setMaximumSize(courseList.getPreferredSize());
courseList.addActionListener(this);
courseList.setActionCommand("Course");
menuBar.add(courseList);
this.setJMenuBar(menuBar);
JToolBar toolBar = new JToolBar();
// Setting up the ButtonBar
JButton button = null;
button = makeButton("Document", "Coursework",
"Open the coursework window.",
"Coursework");
toolBar.add(button);
button = makeButton("Create", "NewNote",
"Create a new note.",
"New");
toolBar.add(button);
button = makeButton("closed door", "Close",
"Close this note.",
"Close");
toolBar.add(button);
toolBar.addSeparator();
button = makeButton("exit button", "Exit",
"Exit from this program.",
"Exit");
toolBar.add(button);
toolBar.addSeparator();
// This forces anything after it to the right.
toolBar.add(Box.createHorizontalGlue());
search.setMaximumSize(new Dimension(6900, 30));
search.setFont(fnt);
toolBar.add(search);
toolBar.addSeparator();
button = makeButton("search", "SearchKeyword",
"Search for this text.",
"Search");
toolBar.add(button);
add(toolBar, BorderLayout.NORTH);
JPanel pnlWest = new JPanel();
pnlWest.setLayout(new BoxLayout(pnlWest, BoxLayout.Y_AXIS));
pnlWest.setBorder(BorderFactory.createLineBorder(Color.black));
txtNewNote.setFont(fnt);
pnlWest.add(txtNewNote);
JButton btnAddNote = new JButton("Add note");
btnAddNote.setActionCommand("NewNote");
btnAddNote.addActionListener(this);
pnlWest.add(btnAddNote);
add(pnlWest, BorderLayout.WEST);
JPanel cen = new JPanel();
cen.setLayout(new BoxLayout(cen, BoxLayout.Y_AXIS));
cen.setBorder(BorderFactory.createLineBorder(Color.black));
txtDisplayNotes.setFont(fnt);
cen.add(txtDisplayNotes);
add(cen, BorderLayout.CENTER);
setExtendedState(JFrame.MAXIMIZED_BOTH);
setTitle("Coursework");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true); // Needed to ensure that the items can be seen.
}
private void controller() {
addAllNotes();
}
protected JMenuItem makeMenuItem(
String txt,
String actionCommand,
String toolTipText,
Font fnt) {
JMenuItem mnuItem = new JMenuItem();
mnuItem.setText(txt);
mnuItem.setActionCommand(actionCommand);
mnuItem.setToolTipText(toolTipText);
mnuItem.setFont(fnt);
mnuItem.addActionListener(this);
return mnuItem;
}
protected JButton makeButton(
String imageName,
String actionCommand,
String toolTipText,
String altText) {
//Create and initialize the button.
JButton button = new JButton();
button.setToolTipText(toolTipText);
button.setActionCommand(actionCommand);
button.addActionListener(this);
//Look for the image.
String imgLocation = System.getProperty("user.dir")
+ "\\icons\\"
+ imageName
+ ".png";
File fyle = new File(imgLocation);
if (fyle.exists() && !fyle.isDirectory()) {
// image found
Icon img;
img = new ImageIcon(imgLocation);
button.setIcon(img);
} else {
// image NOT found
button.setText(altText);
System.err.println("Resource not found: " + imgLocation);
}
return button;
}
private void addNote(String text) {
allNotes.addNote(allNotes.getMaxID(), crse, text);
addAllNotes();
}
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotes()) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
public String getDateAndTime() {
String UK_DATE_FORMAT_NOW = "dd-MM-yyyy HH:mm:ss";
String ukDateAndTime;
Calendar cal = Calendar.getInstance();
SimpleDateFormat uksdf = new SimpleDateFormat(UK_DATE_FORMAT_NOW);
ukDateAndTime = uksdf.format(cal.getTime());
return ukDateAndTime;
}
}
code snippet
this is the AllNotes class:
public class AllNotes extends CommonCode {
private ArrayList<Note> allNotes = new ArrayList<>();
private String crse = "";
private int maxID = 0;
AllNotes() {
readAllNotes();
}
public final int getMaxID() {
maxID++;
return maxID;
}
private void readAllNotes() {
ArrayList<String> readNotes = new ArrayList<>();
readNotes = readTextFile(appDir + fileSeparator + "Notes.txt");
System.out.println(readNotes.get(0));
if (!"File not found".equals(readNotes.get(0))) {
allNotes.clear();
for (String str : readNotes) {
String[] tmp = str.split("\t");
int nid = Integer.parseInt(tmp[0]);
Note n = new Note(nid, tmp[1], tmp[2], tmp[3]);
allNotes.add(n);
if (nid > maxID) {
maxID = nid;
}
}
}
maxID++;
}
public void addNote(int maxID, String course, String note) {
Note myNote = new Note(maxID, course, note);
allNotes.add(myNote);
writeAllNotes();
}
public ArrayList<Note> getAllNotes() {
return allNotes;
}
private void writeAllNotes() {
String path = appDir + fileSeparator +"Notes.txt";
ArrayList<String> writeNote = new ArrayList<>();
for (Note n : allNotes) {
String tmp = n.getNoteID() + "\t";
tmp += n.getCourse() + "\t";
tmp += n.getDayte() + "\t";
tmp += n.getNote();
writeNote.add(tmp);
}
try {
writeTextFile(path, writeNote);
} catch (IOException ex) {
System.out.println("Problem! " + path);
}
}
public String searchAllNotesByKeyword(String noteList, int i, String s) {
if (i == allNotes.size()) {
return noteList;
}
if (allNotes.get(i).getNote().contains(s)) {
noteList += allNotes.get(i).getNote() + "\n";
}
return searchAllNotesByKeyword(noteList, i + 1, s);
}
}
When you init your drop down of courses, set the action command to be the same value that you record in your file, this will make everything consistent when looking up notes from the file. so this way
kurs.add(makeMenuItem("Course 1752", "COMP1752", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1753", "COMP1753", "Coursework requirments.", fnt));
kurs.add(makeMenuItem("Course 1110", "MATH1110", "Coursework requirments.", fnt));
Then change actionPerformed to store the selected value form the drop down to the crse attribute, and call addAllNotes() to refresh the notes list
#Override
public void actionPerformed(ActionEvent ae) {
System.out.println("actionPerformed: " + ae.getActionCommand());
if ("Close".equals(ae.getActionCommand())) {
} else if ("Course".equals(ae.getActionCommand())) {
// set the value of the selected element into the crse attribute
crse = courseList.getSelectedItem().toString();
// Refresh the text area
addAllNotes();
} else if ("Exit".equals(ae.getActionCommand())) {
System.exit(0);
} else if ("NewNote".equals(ae.getActionCommand())) {
addNote(txtNewNote.getText());
txtNewNote.setText("");
} else if ("SearchKeyword".equals(ae.getActionCommand())) {
String lyst = allNotes.searchAllNotesByKeyword("", 0, search.getText());
txtDisplayNotes.setText(lyst);
} else if ("Coursework".equals(ae.getActionCommand())) {
CWDetails cw = new CWDetails();
}
System.out.println("selectedCourse: " + crse);
}
in AllNotes, create a new method to return the notes for a specific course.
public ArrayList<Note> getAllNotesForCourse(String course) {
ArrayList<Note> notes = new ArrayList<>();
for(Note note : allNotes) {
if(course.equalsIgnoreCase(note.getCourse())) {
notes.add(note);
}
}
return notes;
}
then in the addAllNotes method, call getAllNotesForCourse, passing the selected course. This will update txtDisplayNotes with the notes from the selected course
private void addAllNotes() {
String txtNotes = "";
for (Note n : allNotes.getAllNotesForCourse(crse)) {
txtNotes += n.getNote() + "\n";
}
txtDisplayNotes.setText(txtNotes);
}
I think this is all I modified and it works for me.

Codename one google sign in issue

I am trying to do login with google in my app but when I am clicking on the google login but it displays existing account, And when I choose an existing account for signing it will not redirect to app or redirect Uri it again and again display that existing account popup window.
Below is my code:-
google.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent evt) {
String clientId = "XXXXXXXXX-kv0h8ef3k0ppo9lda1bpopjacfde4ds5.apps.googleusercontent.com";
String redirectURI = "https://www.codenameone.com/oauth2callback";
String clientSecret = "XXXXXXXXXXXXQE1quZ";
Login gc = GoogleConnect.getInstance();
gc.setClientId(clientId);
gc.setRedirectURI(redirectURI);
gc.setClientSecret(clientSecret);
userlogin = gc;
gc.setCallback(new LoginListener(LoginListener.GOOGLE));
if(!gc.isUserLoggedIn()){
gc.doLogin();
}else{
showGoogleUser(gc.getAccessToken().getToken());
}
}
});
public class LoginListener extends LoginCallback {
public static final int FACEBOOK = 0;
public static final int GOOGLE = 1;
private int loginType;
public LoginListener(int loginType) {
this.loginType = loginType;
}
public void loginSuccessful() {
try {
AccessToken token = userlogin.getAccessToken();
if (loginType == FACEBOOK) {
showFacebookUser(token.getToken());
} else if (loginType == GOOGLE) {
showGoogleUser(token.getToken());
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void loginFailed(String errorMessage) {
Dialog.show("Login Failed", errorMessage, "Ok", null);
}
private void showGoogleUser(String token){
Dialog.show("Login","Login successful","Ok","");
ConnectionRequest req = new ConnectionRequest();
req.addRequestHeader("Authorization", "Bearer " + token);
req.setUrl("https://www.googleapis.com/plus/v1/people/me");
req.setPost(false);
InfiniteProgress ip = new InfiniteProgress();
Dialog d = ip.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req);
d.dispose();
byte[] data = req.getResponseData();
JSONParser parser = new JSONParser();
Map map = null;
try {
map = parser.parseJSON(new InputStreamReader(new ByteArrayInputStream(data), "UTF-8"));
} catch (IOException ex) {
ex.printStackTrace();
}
String name = (String) map.get("displayName");
Map im = (Map) map.get("image");
String url = (String) im.get("url");
username.setText(name);
userLabel.setIcon(URLImage.createToStorage((EncodedImage) user, url, url, URLImage.RESIZE_SCALE));
TextArea search = new TextArea();
Button searchbutton = new Button("Search");
container12.add(search);
container12.add(searchbutton);
searchbutton.addActionListener((evt) -> {
String searchstr = search.getText();
ConnectionRequest req2 = new ConnectionRequest()
{
#Override
protected void readResponse(InputStream input) throws IOException {
InputStreamReader reader = new InputStreamReader(input);
JSONParser parser1 = new JSONParser();
Map<String, Object> parsed2 = parser1.parseJSON(reader);
Log.p(parsed2.toString());
ArrayList array = (ArrayList)parsed2.get("items");
JSONArray items_array = new JSONArray(array);
ArrayList<String> arrayList = new ArrayList<>();
try{
JSONArray array2 = new JSONArray(items_array.toString());
for(int i =0; i<array2.length() ; i++){
JSONObject jsonobject = array2.getJSONObject(i);
String name = jsonobject.getString("displayName");
String image = (String) ((JSONObject) jsonobject.get("image")).getString("url");
Image searchimage = theme.getImage("user.png");
Label searchLabel = new Label(searchimage);
searchLabel.setIcon(URLImage.createToStorage((EncodedImage) user, image, image, URLImage.RESIZE_SCALE));
Label namelabel = new Label(name);
container12.add(namelabel);
container12.add(searchLabel);
}
}catch (JSONException ex) {
ex.printStackTrace();
}
}
};
req2.setPost(false);
req.addRequestHeader("Authorization", "Bearer " + token);
req2.setUrl("https://www.googleapis.com/plus/v1/people");
req2.addArgument("query", search.getText());
req2.addArgument("key", googleApiKey);
InfiniteProgress ip2 = new InfiniteProgress();
Dialog d2 = ip2.showInifiniteBlocking();
NetworkManager.getInstance().addToQueueAndWait(req2);
d2.dispose();
});
}
If you are already logged in, your code looks like it just shows the info about the logged in user. If you want to log in as a different user, you need to log out first, using the GoogleConnect.doLogout() method.

RMS stored values are not permanently available in J2ME emulator

I have code to stored the value using RMS in J2ME. It's working fine on emulator. So, my first problem is
When i restart the emulator all the stored values are deleted.
Stored values are showing in the emulator, but not in the Mobile, in which i am testing my application.
I am using NetBeans for developing my J2ME application.
===UPDATED===
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
public class TryNew extends MIDlet implements CommandListener, ItemCommandListener {
private RecordStore record;
private StringItem registered;
static final String REC_STORE = "SORT";
//Button existUser;
Display display = null;
private Ticker ticker;
Form form = null;
Form form1 = null;
TextField tb, tb1, tb2, tb3;
ChoiceGroup operator = null;
String str = null;
Command backCommand = new Command("Back", Command.BACK, 0);
Command loginCommand = new Command("Login", Command.OK, 2);
Command saveCommand = new Command("Save New", Command.OK, 1);
Command sendCommand = new Command("Send", Command.OK, 2);
Command selectCommand = new Command("Select", Command.OK, 0);
Command exitCommand = new Command("Exit", Command.STOP, 3);
private ValidateLogin ValidateLogin;
public TryNew() {
}
public void startApp() throws MIDletStateChangeException {
display = Display.getDisplay(this);
form = new Form("Login");
registered = new StringItem("", "Registered ?", StringItem.BUTTON);
form1 = new Form("Home");
tb = new TextField("Login Id: ", "", 10, TextField.PHONENUMBER);//TextField.PHONENUMBER
tb1 = new TextField("Password: ", "", 30, TextField.PASSWORD);
operator = new ChoiceGroup("Select Website", Choice.POPUP, new String[]{"Game", "Joke", "SMS"}, null);
form.append(tb);
form.append(tb1);
form.append(operator);
form.append(registered);
registered.setDefaultCommand(selectCommand);
registered.setItemCommandListener(this);
form.addCommand(saveCommand);
ticker = new Ticker("Welcome Screen");
form.addCommand(loginCommand);
form.addCommand(selectCommand);
form.addCommand(exitCommand);
// existUser = new StringItem(null, "Registered ?");
// form.append(existUser);
form.setCommandListener(this);
form1.addCommand(exitCommand);
form1.addCommand(sendCommand);
form1.setCommandListener(this);
form.setTicker(ticker);
display.setCurrent(form);
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
void showMessage(String message, Displayable displayable) {
Alert alert = new Alert("");
alert.setTitle("Error");
alert.setString(message);
alert.setType(AlertType.ERROR);
alert.setTimeout(5000);
display.setCurrent(alert, displayable);
}
public void commandAction(Command c, Displayable d) {
if (c == exitCommand) {
destroyApp(true);
notifyDestroyed();
} else if (c == backCommand) {
display.setCurrent(form);
} else if (c == loginCommand) {
ValidateLogin = new ValidateLogin(this);
ValidateLogin.start();
ValidateLogin.validateLogin(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
} else if (c == saveCommand) {
openRecord();
writeRecord(tb.getString(), tb1.getString(), operator.getString(operator.getSelectedIndex()));
closeRecord();
showAlert("Login Credential Saved Successfully !!");
}
}
////==============================================================================/////
/// Record Management
public void openRecord() {
try {
record = RecordStore.openRecordStore(REC_STORE, true);
} catch (Exception e) {
db(e.toString());
}
}
public void closeRecord() {
try {
record.closeRecordStore();
} catch (Exception e) {
db(e.toString());
}
}
public void deleteRecord() {
if (RecordStore.listRecordStores() != null) {
try {
RecordStore.deleteRecordStore(REC_STORE);
} catch (Exception e) {
db(e.toString());
}
}
}
public void writeRecord(String login_id, String pwd, String operator_name) {
String credential = login_id + "," + pwd + "," + operator_name;
byte[] rec = credential.getBytes();
try {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
record.addRecord(rec, 0, rec.length);
}
} catch (Exception e) {
db(e.toString());
}
}
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
public void readRecord() {
try {
if (record.getNumRecords() > 0) {
Comparator comp = new Comparator();
RecordEnumeration re = record.enumerateRecords(null, comp, false);
while (re.hasNextElement()) {
String str = new String(re.nextRecord());
showAlert(str);
}
}
} catch (Exception e) {
db(e.toString());
}
}
private void db(String error) {
System.err.println("Exception: " + error);
}
public void commandAction(Command c, Item item) {
if (c == selectCommand && item == registered) {
openRecord();
readRecord();
closeRecord();
}
}
class Comparator implements RecordComparator {
public int compare(byte[] rec1, byte[] rec2) {
String str1 = new String(rec1);
String str2 = new String(rec2);
int result = str1.compareTo(str2);
if (result == 0) {
return RecordComparator.EQUIVALENT;
} else if (result < 0) {
return RecordComparator.PRECEDES;
} else {
return RecordComparator.FOLLOWS;
}
}
}
class ValidateLogin implements Runnable {
TryNew midlet;
private Display display;
String login_id;
String pwd;
String operator_name;
public ValidateLogin(TryNew midlet) {
this.midlet = midlet;
display = Display.getDisplay(midlet);
}
public void start() {
Thread t = new Thread(this);
t.start();
}
public void run() {
if (login_id.length() > 10 || login_id.length() < 10) {
showAlert("Please Enter valid Login Id");
} else if (pwd.length() < 1) {
showAlert("Please Password !!");
} else {
showHome();
}
}
/* This method takes input from user like text and pass
to servlet */
public void validateLogin(String login_id, String pwd, String operator_name) {
this.login_id = login_id;
this.pwd = pwd;
this.operator_name = operator_name;
}
/* Display Error On screen*/
private void showAlert(String err) {
Alert a = new Alert("");
a.setString(err);
a.setTimeout(Alert.FOREVER);
display.setCurrent(a);
}
private void showHome() {
tb2 = new TextField("To: ", "", 30, TextField.PHONENUMBER);
tb3 = new TextField("Message: ", "", 300, TextField.ANY);
form1.append(tb2);
form1.append(tb3);
form1.addCommand(loginCommand);
//display.setCurrent(tb3);
display.setCurrent(form1);
}
};
}
This is what i got, when i click the Manage Emulator
You need to fix the storage_root of your app in WTK,
Whenever you start your enulator it would refer to same storage_root, by default it creates different data files for each session

Categories