I wrote a simple j2me app for order tracking using Netbeans 6.8. The app allows the user to insert a new order, and search for orders by their order id. The app consists of just a single Midlet and the code is shown below. I have also put up the same code at http://pastie.org/1044069 . Im getting an error "Error:java.lang.IllegalStateException" at line 230 which is searchResultsForm.append(userId);
package hello;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.util.Vector;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Display;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.StringItem;
import javax.microedition.lcdui.TextField;
import javax.microedition.midlet.*;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreNotFoundException;
public class J2MEOrderTracker extends MIDlet implements CommandListener {
private Display display = Display.getDisplay(this);
Form mainForm = new Form("Order Tracker App");
Form searchForm;
StringItem errorMessage = new StringItem("", "");
//UI Text Fields
TextField searchField = new TextField("Search By Order Id", null,25,TextField.ANY);
TextField userId = new TextField("User Id", null,10,TextField.ANY);
TextField customerId = new TextField("Customer Id", "", 10, TextField.ANY);
TextField productName = new TextField("Product Name", "", 40, TextField.ANY);
TextField orderQty = new TextField("Product Qty", "", 2, TextField.NUMERIC);
TextField orderStatus = new TextField("Order Status", "", 2, TextField.ANY);
TextField orderId = new TextField("Order Id", "", 25, TextField.ANY);
//Command buttons
private Command searchOrderButton = new Command("Search Order", Command.OK,1);
private Command searchResultsButton = new Command("Search Results",Command.OK, 1);
private Command insertOrderButton = new Command("Insert New Order",Command.OK, 1);
private Command addOrderButton = new Command("Add Order", Command.OK, 1);
private Command exitButton = new Command("Exit Application", Command.OK, 2);
private Command backButton = new Command("Back",Command.BACK,1);
//Record Store
RecordStore recStore;
//Constants
private static final String ORDER_SHIPPED = "N";
private static final String RECORD_ADDED = "N";
public J2MEOrderTracker(){
mainForm.addCommand(insertOrderButton);
mainForm.addCommand(searchOrderButton);
mainForm.addCommand(exitButton);
mainForm.append(errorMessage);
mainForm.setCommandListener(this);
display.setCurrent(mainForm);
}
private void createDatabase(){
connect();
}
private void connect(){
try {
try {
recStore = RecordStore.openRecordStore("OrderDB",false);
}
catch(RecordStoreNotFoundException re){
}
if (recStore == null) {
//Create new one
recStore = RecordStore.openRecordStore("OrderDB", true);
}
}
catch (Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
private void closeConnection() {
try{
if(recStore != null){
recStore.closeRecordStore();
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
private String insertRecord(){
String orderId = null;
try{
int recordID = 0;
ByteArrayOutputStream bytstream = new ByteArrayOutputStream();
DataOutputStream writer = new DataOutputStream(bytstream);
//Generate a unique key for the Order Id
long timeStamp = System.currentTimeMillis();
orderId = userId.getString() + String.valueOf(timeStamp);
writer.writeUTF(orderId);
writer.writeUTF(userId.getString());
writer.writeUTF(customerId.getString());
writer.writeUTF(productName.getString());
writer.writeUTF(orderQty.getString());
writer.writeUTF(ORDER_SHIPPED);
writer.writeUTF(RECORD_ADDED);
writer.writeLong(timeStamp);
writer.flush();
byte [] rec = bytstream.toByteArray();
recordID = recStore.addRecord(rec,0,rec.length);
System.out.println("recordID" + recordID);
System.out.println("orderId" + orderId);
writer.close();
bytstream.close();
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
return orderId;
}
private Vector fetchData(String orderId){
Vector records = new Vector();
try{
ByteArrayInputStream stream;
DataInputStream reader;
String orderID;
for(int i = 1 ; i <= recStore.getNumRecords() && records.size() == 0 ; i++){
byte [] rec = new byte[recStore.getRecordSize(i)];
rec = recStore.getRecord(i);
stream = new ByteArrayInputStream(rec);
reader = new DataInputStream(stream);
orderID = reader.readUTF();
if(orderID.equals(orderId)){
records.addElement(orderId);
// User Id
records.addElement(reader.readUTF());
// Customer Id
records.addElement(reader.readUTF());
// Product Name
records.addElement(reader.readUTF());
// Productquantity
records.addElement(reader.readUTF());
// Order status
records.addElement(reader.readUTF());
// sync status
records.addElement(reader.readUTF());
// order create date
records.addElement(reader.readUTF());
// record id
records.addElement(new Integer(i));
}
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
return records;
}
public void startApp() {
createDatabase();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
closeConnection();
}
public void commandAction(Command c, Displayable d) {
try {
if(c == exitButton){
destroyApp(false);
notifyDestroyed();
return;
}
else if(c == backButton){
display.setCurrent(mainForm);
mainForm.setCommandListener(this);
return;
}
else if(c == searchOrderButton){
searchForm = new Form("Search Order By Order Id");
searchForm.append(searchField);
searchForm.addCommand(searchResultsButton);
searchForm.addCommand(backButton);
searchForm.addCommand(exitButton);
searchForm.setCommandListener(this);
display.setCurrent(searchForm);
}
else if(c == searchResultsButton){
Form searchResultsForm = new Form("Search Order Results");
Vector results = fetchData(searchField.getString());
if(results != null && results.size() > 0){
orderId.setString((String) results.elementAt(0));
userId.setString((String) results.elementAt(1));
customerId.setString((String) results.elementAt(2));
productName.setString((String) results.elementAt(3));
orderQty.setString((String) results.elementAt(4));
orderStatus.setString((String) results.elementAt(5));
searchResultsForm.append(userId); //Error:java.lang.IllegalStateException
searchResultsForm.append("\n");
searchResultsForm.append(customerId);
searchResultsForm.append("\n");
searchResultsForm.append(productName);
searchResultsForm.append("\n");
searchResultsForm.append(orderQty);
searchResultsForm.append("\n");
searchResultsForm.append(orderStatus);
searchResultsForm.append("\n");
}
else{
searchResultsForm.append("No Results Found !");
}
display.setCurrent(searchResultsForm);
}
else if (c == insertOrderButton)
{
Form insertOrderForm = new Form("Insert Order");
insertOrderForm.addCommand(addOrderButton);
insertOrderForm.addCommand(backButton);
insertOrderForm.addCommand(exitButton);
insertOrderForm.append(userId);
insertOrderForm.append(customerId);
insertOrderForm.append(productName);
insertOrderForm.append(orderQty);
insertOrderForm.setCommandListener(this);
display.setCurrent(insertOrderForm);
}
else if(c == addOrderButton){
Form orderIdForm = new Form("Order Information");
String orderId = insertRecord();
orderIdForm.append("Order successfully inserted.Order Id is "+orderId);
orderIdForm.addCommand(searchOrderButton);
orderIdForm.addCommand(exitButton);
orderIdForm.setCommandListener(this);
display.setCurrent(orderIdForm);
}
}
catch(Exception e){
System.out.println("Error:"+e);
errorMessage.setLabel("Error:");
errorMessage.setText(e.toString());
}
}
}
What could be the problem ?
Please help.
Thank You.
Stacktrace would really help. Do you get this exception every time? Can you go directly searchResultsForm?
The only possible problem I can guess from your code is that you add your fields to two different forms:
First, to insertOrderForm:
insertOrderForm.append(userId);
than, to searchResultsForm:
searchResultsForm.append(userId);
second attempt throws an exception, which is a part of the Form contract:
If the application attempts to place an item into a Form, and the item is already owned by this or another Form, an IllegalStateException is thrown.
Related
Note Data inside text file as below:
customer-1-Customer
coach-1-Sport Coach
coach2-1234-Sport Coach
customer2-1234-Customer
PROBLEM
1. Program can read data 1&2. But once it goes into the particular Menu, it also execute the else statement which will shows the pops up window.
2. Data 3&4 couldn't be read, it straight goes to else statement although Username & Password been entered correctly.
private void btn_ConfirmActionPerformed(java.awt.event.ActionEvent evt) {
Admin = txt_Username.getText();
Admin_Pass = txt_Password.getText();
try
{
BufferedReader br = new BufferedReader(new FileReader(("USER_Account.txt")));
String s;
String TOU;
String UIusername; //txt_Username.getText();
String UIpassword; //txt_Password.getText();
while((s = br.readLine()) != null)
{
String tmp [] = s.split("-");
UIusername = tmp[0];
UIpassword = tmp[1];
TOU = tmp[2];
if (txt_Username.getText().equals(UIusername) && txt_Password.getText().equals(UIpassword) && TOU.equals("Sport Coach"))
{ JOptionPane.showMessageDialog(null,"Logged in as Coach!","",JOptionPane.INFORMATION_MESSAGE);
SportCoach_Menu spMenu = new SportCoach_Menu();
this.hide();
spMenu.show();
}
else if (txt_Username.getText().equals(UIusername) && txt_Password.getText().equals(UIpassword) && TOU.equals("Customer"))
{ JOptionPane.showMessageDialog(null,"Logged in as Customer!","",JOptionPane.INFORMATION_MESSAGE);
Customer_Menu cMenu = new Customer_Menu();
this.hide();
cMenu.show();
}
else if (Admin.equals("admin") && Admin_Pass.equals("1234"))
{
JOptionPane.showMessageDialog(null,"Logged in as Admin!","",JOptionPane.INFORMATION_MESSAGE);
Staff_Menu sMenu = new Staff_Menu();
this.hide();
sMenu.show();
}
else
{
JOptionPane.showMessageDialog(null,"Invalid Username / Password, please retry!","",JOptionPane.ERROR_MESSAGE);
txt_Username.setText(null);
txt_Password.setText(null);
}
}
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Much thanks for helping out!!
This works. I made a few modifications. Ask if you don't understand anything.
Instead of reading the textfields I hardcoded the values. You should change this back.
import javax.swing.*;
import java.io.BufferedReader;
import java.io.FileReader;
public class Main {
public static void main(String[] args) {
String Admin = "coach2";
String Admin_Pass = "1234";
try {
BufferedReader br = new BufferedReader(new FileReader(("USER_Account.txt")));
String s;
String TOU;
String UIusername; //txt_Username.getText();
String UIpassword; //txt_Password.getText();
boolean loggedIn = false;
while ((s = br.readLine()) != null && !loggedIn) {
String tmp[] = s.split("-");
UIusername = tmp[0];
UIpassword = tmp[1];
TOU = tmp[2];
if (Admin.equals(UIusername) && Admin_Pass.equals(UIpassword) && TOU.equals("Sport Coach")) {
JOptionPane.showMessageDialog(null, "Logged in as Coach!", "", JOptionPane.INFORMATION_MESSAGE);
loggedIn = true;
} else if (Admin.equals(UIusername) && Admin_Pass.equals(UIpassword) && TOU.equals("Customer")) {
JOptionPane.showMessageDialog(null, "Logged in as Customer!", "", JOptionPane.INFORMATION_MESSAGE);
loggedIn = true;
} else if (Admin.equals("admin") && Admin_Pass.equals("1234")) {
JOptionPane.showMessageDialog(null, "Logged in as Admin!", "", JOptionPane.INFORMATION_MESSAGE);
loggedIn = true;
}
}
if (!loggedIn)JOptionPane.showMessageDialog(null, "Invalid Username / Password, please retry!", "", JOptionPane.ERROR_MESSAGE);
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
The purpose of the class below is to get text from different articles of different news websites. The version below is designed for Android, but it throws a NetworkOnMainThread Exception when run. When I used an earlier version of this class, made specifically to run on a computer, it worked fine, but I'm not really sure how network I/O works on Android. I've seen some other answers to questions about this topic, but I don't understand why in Android the program throws an exception but on a desktop it works fine. Can anyone explain?
package com.example.user.helloworld;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class ArticleReceiver {
private ArrayList<Article> newsArticles = new ArrayList<>();
private ArrayList<String> newsLinks = new ArrayList<>();
public ArticleReceiver(int numArticles, String link) {
if (numArticles != 0) {
receiveNewsArticles(numArticles, link);
}else{
System.out.println("ERROR: numArticles request for " + link + " cannot equal 0.");
}
}
private void receiveNewsArticles(int numArticles, String urlAddress) {
URL rssUrl = null;
// if connected to Internet
if (true){//isInternetAvailable()) {
try {
// gather links
rssUrl = new URL(urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
// fix bbc trash urls
if (urlAddress.equals(Main.BBC_URL)) {
numArticles++;
}
while ((line = in.readLine()) != null && newsLinks.size() <= numArticles) {
if (line.contains("<link>")) {
// find links through tags
int firstPos = line.indexOf("<link>");
String temp = line.substring(firstPos);
temp = temp.replace("<link>", "");
int lastPos = temp.indexOf("</link>");
temp = temp.substring(0, lastPos);
newsLinks.add(temp);
}
}
in.close();
// test if there are links and if there is remove first
// unnecessary
// link
if (!newsLinks.isEmpty()) {
if (urlAddress.equals(Main.BBC_URL)) {
newsLinks.remove(0);
newsLinks.remove(0);
}else if(urlAddress.equals(Main.CNN_URL) || urlAddress.equals(Main.FOX_URL) || urlAddress.equals(Main.ESPN_URL)){
newsLinks.remove(0);
}
} else {
System.out.println("ERROR: No Found Articles. Check If You Have Wifi.");
}
// gather articles from HTML "section" or "p" tag of article using Jsoup
for (String newsLink : newsLinks) {
// get webpage
Document doc = Jsoup.connect(newsLink).get();
// get article from different websites
String article = null;
if (urlAddress.equals(Main.FOX_URL)) {
Elements element = doc.select("p");
article = element.text();
} else if (urlAddress.equals(Main.CNN_URL)) {
Elements element = doc.select("section");
article = element.text();
} else if (urlAddress.equals(Main.BBC_URL)) {
Elements element = doc.select("p");
article = element.text();
}else if(urlAddress.equals(Main.ESPN_URL)){
Elements element = doc.select("p");
article = element.text();
}
newsArticles.add(new Article(article, Main.SUMMARY_SENTENCES));
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("ERROR: No internet connection established.");
return;
}
}
public ArrayList<Article> getArticles() {
return newsArticles;
}
public Article getArticle(int i) {
if (newsArticles.size() <= i) {
return null;
} else {
return newsArticles.get(i);
}
}
//The method below does not recognize the "getSystemService" method, and when the method is no longer present there is a NetworkOnMainThreadException
private boolean isInternetAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
You need to execute web service connections asynchronous.
What I use in my projects is have a class ApiConnection and with interface get response. Example:
Apiconnection class
public class APIConnection extends AsyncTask<Object, String, Void> {
private final String TAG = "API-CONNECTION";
private StringBuilder sbuilder;
private JSONObject json;
private APIConnectionInterface mInterface;
protected int httpResponseCode = 0;
private String entity = null, url;
private APIConnectionType mmode;
private boolean DEBUG = BuildConfig.DEBUG;
private String[][] headers;
/**
Constructor For APIConnection
*/
public APIConnection(APIConnectionInterface thisdelegate, APIConnectionType mode, String murl, String entity) {
this.mInterface = thisdelegate;
this.mmode = mode;
this.url = murl;
this.entity = entity;
initHeaders();
}
private void initHeaders(){
headers = new String[][]{
{"token", "MY_TOKEN"},
{"Content-Type", "application/json;charset=utf-8"},
{"user-agent", "android"},
{"Accept-Language", "es"}
};
}
#Override
protected Void doInBackground(Object... params) {
BufferedReader buffer = null;
InputStreamReader in = null;
OutputStream os = null;
int timeoutConnection = 30000, timeoutSocket = 20000;
try{
sbuilder = new StringBuilder();
url = convertURL(url);
if (entity==null)entity="{}";
URL u = new URL(url);
HttpURLConnection conn;
if (url.startsWith("https://"))
conn = (HttpsURLConnection) u.openConnection();
else
conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(timeoutConnection);
conn.setConnectTimeout(timeoutSocket);
for (String[] arr : headers){ conn.addRequestProperty(arr[0], arr[1]); }
/*GET*/if (mmode == APIConnectionType.GET) {
conn.setDoInput(true);
conn.setRequestMethod(mmode.toString());
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(),"UTF-8");
/*OTHER*/} else if (mmode == APIConnectionType.POST || mmode == APIConnectionType.PUT ||
mmode == APIConnectionType.PATCH || mmode == APIConnectionType.DELETE) {
conn.setRequestMethod(mmode.toString());
conn.setDoOutput(true);
byte[] outputInBytes = entity.getBytes("UTF-8");
os = conn.getOutputStream();
os.write( outputInBytes );
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(), "UTF-8");
}
if (in!=null){
buffer=new BufferedReader(in);
String line;
while ((line = buffer.readLine()) != null) {
sbuilder.append(line);
}
}else {
sbuilder.append("");
}
}
catch(IOException e) {
if (DEBUG)Log.d(TAG, "onBackground Exception " + e.getMessage());
sbuilder= new StringBuilder();
httpResponseCode = 0;
cancel(true);
return null;
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (os!=null){
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
try{
if (DEBUG) timelapse_e = System.currentTimeMillis();
if (sbuilder != null) {
json = new JSONObject(sbuilder.toString());
}
if (sbuilder != null){
sbuilder.setLength(0);
sbuilder.trimToSize();
}
sbuilder = null;
GoRunning();
hideDialog();
}
catch(RuntimeException e) {
if (DEBUG)Log.d(TAG, "PostExecute RuntimeException " + e.getMessage());
cancel(true);
}
catch(Exception e) {
if (DEBUG)Log.d(TAG, "PostExecute Exception " + e.getMessage());
cancel(true);
}
}
#Override protected void onCancelled() {
if (mInterface != null) mInterface.onCancelled(APIConnection.this);
super.onCancelled();
}
#Override protected void onPreExecute() {
super.onPreExecute();
if (DEBUG) timelapse_s = System.currentTimeMillis();
if (mInterface != null) mInterface.onStartLoading(APIConnection.this);
}
public void GoRunning(){
if (mInterface != null) try {
mInterface.onDataArrival(APIConnection.this, json, httpResponseCode);
} catch (JSONException e) {
onCancelled();
e.printStackTrace();
}
}
/**
* Hide Dialog (Progress dialog) if is showing and activity NOT Finishing
*/
private void hideDialog() {
if (mInterface != null) mInterface.onFinishedLoading(APIConnection.this);
}
/** <b>convertURL(String str);</b><br/>
* replaces any special characters to <b>%??</b><br/>
* Replacements actived:<br/>
* "{Space}" ==> "%20"
* #param str URL to encode
* #return url encoded
*/
public static String convertURL(String str) {
return str.trim().replace(" ", "%20");
// .replace("&", "%26")
// .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
// .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
// .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
// .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
// .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
// .replace(";", "%3B").replace("?", "%3F").replace("#", "%40")
// .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
// .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
// .replace("|", "%7C").replace("}", "%7D"));
}
public interface APIConnectionInterface {
void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) throws JSONException;
void onStartLoading(APIConnection apiConnection);
void onFinishedLoading(APIConnection apiConnection);
void onCancelled(APIConnection apiConnection);
}
public enum APIConnectionType {
GET("GET"),
POST("POST"),
PUT("PUT"),
PATCH("PATCH"),
DELETE("DELETE");
private String methodName;
APIConnectionType(String methodName){this.methodName = methodName;}
#Override public String toString() {return methodName;}
}
}
And then from any Activity or Fragment I can call the web service async
like this:
new APIConnection(new APIConnection.APIConnectionInterface() {
#Override public void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) {
try {
if (isHttpResponseOk(httpResponseCode, json)){//200 or 201
JSONObject obj = json.getJSONObject("results");
// do things with json
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override public void onStartLoading(APIConnection apiConnection) {showProgressDialog();}
#Override public void onFinishedLoading(APIConnection apiConnection) {hideProgressDialog();}
#Override public void onCancelled(APIConnection apiConnection) {hideProgressDialog();}
}, APIConnection.APIConnectionType.GET, MyApp.API_URL + "/master_data/", null).execute();
The only thing you need is to adapt the response to other object you need.
I hope that helps
I've created these two functions and added them into an action listener within a button . The aim is to create a serialized file and write what is in the Jlist to the file. When the program is closed , the jlist should be populated with what is in the serialized file. For some reason it isn't working. Can anyone see what is wrong?
Here is the code:
JButton btnAdd = new JButton("Add"); // Setting what is written on the button
btnAdd.addActionListener(new ActionListener() { // implementing an action listener
public void actionPerformed(ActionEvent arg0) {
patientname = textField.getText(); // Getting the patient name from the textfield
patientaddress = textField_1.getText();
patientphone = textField_2.getText();
textField.setText(""); // Setting the textfield to be blank so that the user can input there name address etc..
textField_1.setText("");
textField_2.setText("");
patientid = patientid + 1;//Implementing the id to add 1 every time another id is added
Patient patient = new Patient(patientname, patientaddress, patientphone, patientid); // Populating the array list patientlist with the users input
patientList.add(patient); // Adding the patient's details to the patientlist
patientListModel.addElement(patient); // adds the patient's details to the list model
}
public void onSave(List<Patient> PatientList) {
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File("PatientList.ser")));
out.writeObject(PatientList);
out.flush();
}
catch (IOException e) {
// handle exception
}
finally {
if (out != null) {
try {
out.close();
}
catch (IOException e) {
// handle exception
}
}
}
}
public List<Patient> onLoad() {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream(new File("PatientList.ser")));
return (List<Patient>) in.readObject();
}
catch (IOException e) {
// handle exception
}
catch (ClassNotFoundException e) {
// handle exception
}
finally {
if (in != null) {
try {
in.close();
}
catch (IOException e) {
// handle exception
}
}
}
return null;
}
});
btnAdd.setBounds(0, 86, 65, 23);
contentPane.add(btnAdd);
/////////////////
Here is my patient class :
public class Patient {
public String patientName;
public String patientAddress;
public String patientPhone;
public int patientID;
public Patient(String patientname, String patientaddress, String patientphone,int patientid){
patientName = patientname;
patientAddress = patientaddress;
patientPhone = patientphone;
patientID = patientid;
}
public String setName(String patientname){
return patientName = patientname;
}
public String getName(){
return patientName;
}
public String setAddress(String patientaddress){
return patientAddress = patientaddress;
}
public String getAddress(){
return patientAddress;
}
public String setPhoneNum(String patientphone){
return patientPhone = patientphone;
}
public String getPhoneNum(){
return patientPhone;
}
public int setID(int patientid){
return patientID = patientid;
}
public int getID(){
return patientID;
}
public String toString() { // Printing the patient's details to the scroll pane
return "Patient Name: " + patientName + ", PatientAddress: "
+ patientAddress + ", PatientPhone: " + patientPhone
+ ", patientID: " + patientID +"" ;
}
}
I have a text file that looks like this:
Person1 Name
Person1 age
Person1 Address
Person2 Name
Person2 age
Person2 Address
Person3 Name
Person2 age
Person3 Address
and I need to get the information to a database.
I have the database connection and know how to enter the info into the database once I have the lines put into the correct variables . . . but how do I get java to identify each new line and set the info to a variable.
Basically I need to take the textfile info and add to the following variables
$Name
$Age
$Address
I thought of using an Array but since I'm mixing strings and numbers, I can't use a String array.
Since I'm using Line per line there is no delimiter.
** Updated info **
I used name, age and address as example variables, and got some of the answers kind of working but I still can't get it completely working, so I should post the whole code . . .
I'm open to code cleanup as well (I'm really new to Java)
The answers given I kind of got to work, except the reader is separating the variables by spaces and in a situation like name and address both have spaces in them, the space delimiter isn't giving me the results I need.
Here is the textfile contents:
Ray Wade
200
American Foundation for Children with AIDS
Tom Hardy
125.50
American Red Cross
As you can see I call the LoadTextFile(); within the CreateTables() function
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.text.*;
import java.sql.*;
import javax.sql.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
public class Charity extends JFrame
{
JButton btnCalc = new JButton("Donate"), btnLoad = new JButton("Load File"), btnExit = new JButton("Exit");
JLabel name, amount, intro = new JLabel("Would You Like to Donate to a Charity Today? It Only Takes a Few Moments"), message1 = new JLabel(""), message2 = new JLabel("");
JTextField textName, textAmount;
// Create String Array to list charities in the combobox
String[] charities = { "Choose a Charity or Enter a New Charity",
"American Foundation for Children with AIDS",
"American Red Cross",
"Breast Cancer Research Foundation",
"Livestrong *Formerly Lance Armstrong Foundation*",
"Michael J. Fox Foundation for Parkinson's Research" };
JComboBox charityList = new JComboBox(charities);
String file ="Charity.txt";
// Variables used later
double dAmount;
String Charity = null;
int debug = 0; // change to 1 to turn debug mode on
// Variables initialized for Database Stuff
Object[][] databaseInfo;
Object[] columns = {"name", "charity", "amount"};
Connection conn = null;
ResultSet rows;
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
String DBname = "charity";
String DBusername = "root";
String DBpass = "password";
// Variables and Class for TableModel
DefaultTableModel dTableModel = new DefaultTableModel(databaseInfo, columns){
public Class getColumnClass(int column) {
Class returnValue;
// Verifying that the column exists (index > 0 && index < number of columns
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
// Returns the class for the item in the column
returnValue = Object.class;
}
return returnValue;
}
};
/**
Sets the title, size and layout of the JFrame.<!-- -->Also calls the methods to setup the panels.
*/
public Charity()
{
super("Donations to Charities"); // Title of frame
setLayout(new FlowLayout()); // Declare layout of frame
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Default close
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize(); // Get screen size
this.setResizable( false ); // turn off frame resize
this.setSize(600, dim.height-100); // set size of frame
CreatePanels();
GetAction(); // Call ActionListeners
CreateDatabase();
}
public void CreatePanels()
{
SetupCharityGroup(); // Call method to setup charity list panel
SetupDataPanel(); // Call method to setup data collection panel
SetupDisplayTable();
setVisible(true); // Make frame visible
}
/**
Method to setup the display panel containing a JTable that will show the information read from the database.
*/
private void SetupDisplayTable()
{
JTable table = new JTable(dTableModel); // Create a JTable using the custom DefaultTableModel
table.setFont(new Font("Serif", Font.PLAIN, 16)); // Increase the font size for the cells in the table
table.setRowHeight(table.getRowHeight()+5); // Increase the size of the cells to allow for bigger fonts
table.setAutoCreateRowSorter(true); // Allows the user to sort the data
// right justify amount column
TableColumn tc = table.getColumn("amount");
RightTableCellRenderer rightRenderer = new RightTableCellRenderer();
tc.setCellRenderer(rightRenderer);
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); // Disable auto resizing
// Set the width for the columns
TableColumn col1 = table.getColumnModel().getColumn(0);
col1.setPreferredWidth(200);
TableColumn col2 = table.getColumnModel().getColumn(1);
col2.setPreferredWidth(275);
TableColumn col3 = table.getColumnModel().getColumn(2);
col3.setPreferredWidth(75);
// Put the table in a scrollpane and add scrollpane to the frame
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(new Dimension(552, 400));
this.add(scrollPane, BorderLayout.CENTER);
}
/**
Method to setup the data panel containing textFields, Labels, and buttons.
*/
private void SetupDataPanel()
{
JPanel pan = new JPanel();
GridLayout grid = new GridLayout(0, 1, 5, 5);
pan.setLayout(grid);
// Setup TextFields and Labels for name of person donating
// and add them to the panel
name = new JLabel("Name");
textName = new JTextField("", 16);
textName.setHorizontalAlignment(JTextField.RIGHT);
pan.add(name);
pan.add(textName);
// Setup TextFields and Labels for amount being donated
// and add them to the panel
amount = new JLabel("Donation Amount");
textAmount = new JTextField("", 4);
textAmount.setHorizontalAlignment(JTextField.RIGHT);
pan.add(amount);
pan.add(textAmount);
// add buttons and message labels to panel
pan.add(intro);
pan.add(btnCalc);
pan.add(btnLoad);
pan.add(btnExit);
pan.add(message1);
pan.add(message2);
this.add(pan);
}
/**
Method to setup the charity panel with a border containing an editable combobox filled with a list of charities.
*/
private void SetupCharityGroup()
{
JPanel Boxpan=new JPanel();
Boxpan.setBorder(BorderFactory.createTitledBorder(
BorderFactory.createEtchedBorder(), "Charities"));
this.add(Boxpan);
charityList.setEditable(true);
Boxpan.add(charityList);
}
/**
Add ActionHandlers to interactive elements.
*/
private void GetAction()
{
ActionHandler handler = new ActionHandler();
btnLoad.addActionListener(handler);
btnCalc.addActionListener(handler);
btnExit.addActionListener(handler);
charityList.addActionListener( handler );
}
/**
Method to make ActionHandlers into ActionListeners.
*/
private class ActionHandler implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
String incmd = evt.getActionCommand();
if (incmd.equals("Donate")) // If Donate button is pressed
if (textName.getText().isEmpty())
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: Name of Donor missing!<font>");
} else
CheckDonate();
else if (incmd.equals("Load File")) // If Load File button is pressed
DatabaseLoad();
else if (incmd.equals("Exit")) // If Exit button is pressed
System.exit(0);
}
}
/**
Method to check if charity is selected in the combobox.<!-- -->If a charity is selected, call CharitySelected method, otherwise send error message to Frame.
*/
private void CheckCharity()
{
Object selectedCharity = charityList.getSelectedItem();
if (charityList.getSelectedIndex() == 0) // if charity is not selected
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Error: No Charity Selected!<font>");
} else CharityIsSelected();
}
/**
If charity is selected, set the selected value to "Charity" variable and call method to thank donator.
*/
private void CharityIsSelected()
{
Object selectedCharity = charityList.getSelectedItem();
Charity = selectedCharity.toString(); // selectedCharity Object converted to String
ThankYou();
}
/**
Thank the donator and call the databseAdd method.
*/
private void ThankYou()
{
message1.setText("Thank You! "+textName.getText());
message2.setText(" $"+textAmount.getText()+" Will be donated to "+Charity);
DatabaseAdd();
}
/**
Method that will check that donation amount is a number in a range between 1 and 1000000000.
*/
private void CheckDonate()
{ try
{
dAmount = Double.parseDouble(textAmount.getText());
if(dAmount <= 0.0 || dAmount > 1000000000 )
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount invalid</font>");
} else CheckCharity();
} catch (NumberFormatException ex) {
// Executes if the data entered is not a number
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
{
message1.setText("<html><font color='red'>Invalid Donation</font>");
message2.setText("<html><font color='red'>Amount Not Recognized</font>");
}
}
}
public void DBConnection()
{ try
{
// The driver allows you to query the database with Java
// forName dynamically loads the class for you
Class.forName(driver);
// DriverManager is used to handle a set of JDBC drivers
// getConnection establishes a connection to the database
// You must also pass the userid and password for the database
conn = DriverManager.getConnection (url, DBusername, DBpass);
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
} catch (ClassNotFoundException ex) {
// Executes if the driver can't be found
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
} else
message1.setText("Driver Error: contact admin");
message2.setText("");
}
}
/**
Method to add the entered information to the database.<!-- -->Once the information is added to the database, clear the form fields.
*/
private void DatabaseAdd()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// Prepare the query and values to be inserted into the database
String str="INSERT INTO donations(name,charity,amount) VALUES (?,?,?)";
java.sql.PreparedStatement statement = conn.prepareStatement(str);
statement.setString(1,textName.getText());
statement.setString(2,Charity);
statement.setDouble(3,dAmount);
statement.executeUpdate();
// Reset form after saved to database
textName.setText("");
textAmount.setText("");
charityList.setSelectedIndex(0);
s.close();
DatabaseLoad(); // Call the Database Info
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will load the database information and display it in Frame in a JTable.
*/
private void DatabaseLoad()
{ try
{
url = url+DBname;
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
// This is the query I'm sending to the database
String selectStuff = "SELECT `name`, `charity`, `amount` FROM `"+DBname+"`.`donations` ";
// A ResultSet contains a table of data representing the
// results of the query. It can not be changed and can
// only be read in one direction
rows = s.executeQuery(selectStuff);
// Set the table RowCount to 0
dTableModel.setRowCount(0);
// Temporarily holds the row results
Object[] tempRow;
// next is used to iterate through the results of a query
while(rows.next())
{
// Gets the column values based on class type expected
tempRow = new Object[]{rows.getString(1), rows.getString(2), rows.getDouble(3) };
dTableModel.addRow(tempRow); // Adds the row of data to the end of the model
}
// Successfully loaded, message the user
message1.setText("<html><font color='red'>Database Info Loaded</font>");
message2.setText("");
s.close();
} catch (SQLException ex) {
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
} else
message1.setText("Database Error: contact admin");
message2.setText("");
}
}
/**
Method will create the database if it does not exist.
*/
private void CreateDatabase()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String dbCreate = "CREATE DATABASE "+DBname;
s.executeUpdate(dbCreate);
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
CreateTables();
}
/**
Method will create the table needed in the database.
*/
private void CreateTables()
{ try
{
DBConnection();
// Statement objects executes a SQL query
// createStatement returns a Statement object
Statement s = conn.createStatement();
String tableCreate = "create table "+DBname+".donations " + "(`name` varchar(200), " + "`charity` varchar(200), " + "amount double)";
s.executeUpdate(tableCreate);
// After creating the tables
// Load the information from the textfile
LoadTextFile();
s.close();
} catch(SQLException ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("Error: "+ex.getErrorCode());
}
} catch(Exception ex){
// debug:
if (debug == 1)
{
message1.setText("Error: "+ex.getMessage());
message2.setText("");
}
}
}
public void LoadTextFile()
{
}
// To change justification to the right
class RightTableCellRenderer extends DefaultTableCellRenderer {
public RightTableCellRenderer() {
setHorizontalAlignment(JLabel.RIGHT);
}
}
// Main method calls the constructor
public static void main(String[] args)
{
new Charity();
}
}
Following code snippet will solve your problem.
public class Test {
public static void main( String[] args ) throws Exception
{
HashMap<String, Person> personMap = new HashMap<String, Person>();
try
{
BufferedReader in = new BufferedReader( new FileReader( "File Path" ) );
String str;
Person person = new Person();
int count = 0;
String key = "";
while( ( str = in.readLine() ) != null )
{
if ( null != str && str.trim().length() == 0 )
{
personMap.put( key, person );
count = -1;
person = new Person();
}
else {
String arr[] = str.split( " " );
key = arr[0];
if (count == 0) {
person.setName( arr[1] );
}
else if (count == 1) {
person.setAge( arr[1] );
}
else if (count == 2) {
person.setAddress( arr[1] );
}
}
count ++;
}
personMap.put( key, person );
in.close();
}
catch( IOException e )
{
System.out.println( "Exception" + e.getMessage() );
}
}
}
public class Person
{
private String name = null;
private String age = null;
private String Address = null;
public String getName()
{
return name;
}
public void setName( String name )
{
this.name = name;
}
public String getAge()
{
return age;
}
public void setAge( String age )
{
this.age = age;
}
public String getAddress()
{
return Address;
}
public void setAddress( String address )
{
Address = address;
}
}
I hope it helps
Use BufferedReader to read one line at a time, extract the required info from that line and assign it to the variables. In case you want to hold it in the memory, use a POJO with those 3 properties.
You may use regex to split the line and get the required value(s).
I wrote a set of functions that does something similar. I use a bufferedReader like the other user suggested.
public ArrayList<String> readFileToMemory(String filepath)
{
BufferedReader br = null;
String currentLine = null;
ArrayList<String> fileContents = new ArrayList<String>();
try
{
br = new BufferedReader(new FileReader(filepath));
while((currentLine = br.readLine()) != null)
{
//fileContents.add(br.readLine());
fileContents.add(currentLine);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
br.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
return fileContents;
}
This will just read in the each line of a file as a separate entry in a list. Just take the entries and do what you need.
If you're only doing this once, just do 3 replaces in notepad ++
Replace \r\n\r\n with "|||"
replace \r\n with ","
replace ||| with \r\n
then you've got a regular .csv file.
I'm trying to remove values of datatype properties of an instance through an interface which I created in java but it does not work. It gives me an
Exception in thread "AWT-EventQueue-0" java.util.ConcurrentModificationException.
I don't understand why. Can you please explain me what's wrong?
Here is my code for button remove:
//Button Remove
public class ActionRemove implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
StmtIterator iter = onto.model.listStatements();
while (iter.hasNext())
{
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
if(subject.toString().equals (onto.uriBase+"#"+tabTF[0].getText()))
{
onto.model.remove(stmt);
}
}
}
}
My complete code:
import java.util.*;
import com.hp.hpl.jena.rdf.model.*;
import com.hp.hpl.jena.ontology.*;
import com.hp.hpl.jena.ontology.impl.*;
import com.hp.hpl.jena.util.*;
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import com.hp.hpl.jena.vocabulary.RDF;
import com.hp.hpl.jena.vocabulary.XSD;
import com.hp.hpl.jena.util.iterator.ExtendedIterator;
public class FamilyModel extends Frame
{
TextField[]tabTF=new TextField[4];
Button bAjout, bModifier, bSupprimer, bPrecedent, bSuivant, bRemove; //buttons Add, Remove, Previous, Next
OntModel model;
Onto onto;
int indice=0;
int p=0;
Resource p1;
Button creerBouton(String S, int x, int y)
{
Button b=new Button(S);
add(b);
b.setBounds(x,y,120,30);
return b;
}
void creerLabel(String etiquette, int x, int y)
{
Label la=new Label(etiquette);
la.setBounds(x,y,100,25);
add(la);
}
public FamilyModel ()
{
setLayout (null);
setBackground (Color.pink);
setBounds (100,200,900,450);
addWindowListener(new FermerFenetre());
creerLabel("Prenom : ",10,50);
creerLabel("Nom : ",10,100);
creerLabel("Date de Naissance: ",10,145);
creerLabel("Genre (H ou F): ",10,190);
//TextFields
for(int i=0;i<4;i++)
{
tabTF[i]=new TextField("");
tabTF[i].setBackground(Color.white);
add(tabTF[i]);
}
tabTF[0].setBounds(120,45,150,25);
tabTF[1].setBounds(120,100,150,25);
tabTF[2].setBounds(120,145, 100,25);
tabTF[3].setBounds(120,190, 45,25);
bAjout=creerBouton("Ajouter",20,250);
setVisible(true);
bModifier=creerBouton("Modifier",138,250);
setVisible(true);
bSupprimer=creerBouton("Supprimer",250,250);
setVisible(true);
bPrecedent=creerBouton("Precedent",360,250);
bSuivant=creerBouton("Suivant",450,250);
bRemove=creerBouton("Supprimer",600,250);
setVisible(true);
onto = new Onto();
readRDFfile();
traitement(this);
}
void traitement(Frame fenetre)
{
bAjout.addActionListener(new ActionAjoutPersonne());
bModifier.addActionListener(new ActionRemove());
bSuivant.addActionListener(new ActionSuivant());
bPrecedent.addActionListener(new ActionPrecedent());
bRemove.addActionListener(new ActionRemove());
}
//Button Add
public class ActionAjoutPersonne implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
p1=onto.model.createResource(onto.uriBase+"#"+tabTF[0].getText());
p1.addProperty(onto.aPourPrenom, tabTF[0].getText());
p1.addProperty(onto.aPourNom, tabTF[1].getText());
p1.addProperty(onto.aDateNaiss, tabTF[2].getText());
if (tabTF[3].getText().equals("F"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.femme);
}
else if (tabTF[3].getText().equals("H"))
{
p1.addProperty(onto.aGenre, tabTF[3].getText());
p1.addProperty(RDF.type, onto.homme);
}
StringWriter sw = new StringWriter();
onto.model.write(sw, "RDF/XML-ABBREV");
String owlCode = sw.toString();
File file = new File("d:/Onto.rdf");
try{
FileWriter fw = new FileWriter(file);
fw.write(owlCode);
fw.close();
} catch(FileNotFoundException fnfe){
fnfe.printStackTrace();}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
//Button Remove
public class ActionRemove implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
StmtIterator iter = onto.model.listStatements();
while (iter.hasNext())
{
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
if(subject.toString().equals (onto.uriBase+"#"+tabTF[0].getText()))
{
onto.model.remove(stmt);
}
}
}
}
//Read Onto.rdf
public void readRDFfile()
{
String inputFile="D:/Onto.rdf";
try
{
InputStream in =new FileInputStream(inputFile);
if (in == null) {
System.out.println("File not found");
}
onto.model.read(in," ");
}catch(Exception e) {
System.out.println("model.read catched error: " + e);
}
}
//Button Next
class ActionSuivant implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
++indice;
ExtendedIterator instances = onto.personne.listInstances();
Individual instance = null;
Individual firstInstance = null;
for (p = 0; p < indice && instances.hasNext(); p++) {
instance = (Individual) instances.next();
if (firstInstance == null) {
firstInstance = instance;
}
}
if (p < indice) {
indice = 1;
instance = firstInstance;
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
//Button Previous
class ActionPrecedent implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
--indice;
//Instances de la Classe Personne
ExtendedIterator instances=onto.personne.listInstances();
Individual instance = null;
for(p = 0; p < indice && instances.hasNext(); p++)
{
instance = (Individual) instances.next();
}
tabTF[0].setText(instance.getPropertyValue(onto.aPourPrenom).toString());
tabTF[1].setText(instance.getPropertyValue(onto.aPourNom).toString());
tabTF[2].setText(instance.getPropertyValue(onto.aDateNaiss).toString());
tabTF[3].setText(instance.getPropertyValue(onto.aGenre).toString());
}
}
//Close window when X is pressed
public class FermerFenetre extends WindowAdapter
{
public void windowClosing(WindowEvent evt)
{
if(evt.getWindow().getName().equals("frame0"))
{
System.exit(0);
}
else
{
evt.getWindow().dispose();
}
}
}
//Ontology
public class Onto
{
OntClass personne, genre, homme, femme, feminin, masculin, evenement, deces, mariage, divorce;
OntModel model;
String uriBase;
ObjectProperty aPourFils, aPourFille, aGenre;
DatatypeProperty aPourNom, aPourPrenom, aDateNaiss;
public Onto (){
model = ModelFactory.createOntologyModel( OntModelSpec.OWL_MEM_MICRO_RULE_INF );
uriBase = "http://www.something.com/FAM";
model.createOntology(uriBase);
//Classes
personne = model.createClass(uriBase+"personne");
femme = model.createClass(uriBase+"femme");
homme = model.createClass(uriBase+"homme");
genre = model.createClass(uriBase+"genre");
feminin = model.createClass(uriBase+"feminin");
masculin = model.createClass(uriBase+"masculin");
evenement = model.createClass(uriBase+"evenement");
deces = model.createClass(uriBase+"deces");
mariage = model.createClass(uriBase+"mariage");
divorce = model.createClass(uriBase+"divorce");
//Sub-classes
genre.addSubClass(feminin);
genre.addSubClass(masculin);
personne.addSubClass(homme);
personne.addSubClass(femme);
evenement.addSubClass(deces);
evenement.addSubClass(mariage);
evenement.addSubClass(divorce);
aPourFils = model.createObjectProperty(uriBase+"aPourFils");
aPourFils.setDomain(personne);
aPourFils.setRange(homme);
aPourFille = model.createObjectProperty(uriBase+"aPourFille");
aPourFille.setDomain(personne);
aPourFille.setRange(femme);
aGenre = model.createObjectProperty(uriBase+"aGenre");
aGenre.setDomain(personne);
aGenre.setRange(genre);
aPourNom = model.createDatatypeProperty(uriBase+"aPourNom");
aPourNom.setDomain(personne);
aPourNom.setRange(XSD.xstring);
aPourPrenom = model.createDatatypeProperty(uriBase+"aPourPrenom");
aPourPrenom.setDomain(personne);
aPourPrenom.setRange(XSD.xstring);
aDateNaiss = model.createDatatypeProperty(uriBase+"aDateNaiss");
aDateNaiss.setDomain(personne);
aDateNaiss.setRange(XSD.xstring);
}
}
public static void main(String args[])
{
new FamilyModel();
}
}
You have removed an item from a collection and then continued to use a previous iterator on it.
Most of the java collection iterators have the "fail fast" property. Once they detect that the underlying collection has changed they will throw a ConcurrentModificationException.
Your solution is to do a two step removal process:
iterate and find the nodes that you need to remove
iterate the list of nodes you want removed (found in first step) and actually remove them from the original collection.
Code (assuming Java 5):
//Button Remove
public class ActionRemove implements ActionListener
{
public void actionPerformed(ActionEvent evt)
{
List<Statement> statementsToRemove = new ArrayList<Statement>();
// step 1
StmtIterator iter = onto.model.listStatements();
while (iter.hasNext())
{
Statement stmt = iter.nextStatement();
Resource subject = stmt.getSubject();
Property predicate = stmt.getPredicate();
RDFNode object = stmt.getObject();
if(subject.toString().equals (onto.uriBase+"#"+tabTF[0].getText()))
{
statementsToRemove.add(stmt);
}
}
// step 2
for( Statement stmt : statementsToRemove)
{
onto.model.remove(stmt);
}
}
}
There is another way (see http://download.oracle.com/javase/1.5.0/docs/api/java/util/concurrent/CopyOnWriteArrayList.html class) but since your collection is inside the Jena api you can't use it ;).