Passing ArrayList to separate class? - java

I have a code that reads from an SQL Database and saves each column of information into an ArrayList. I need to pass each ArrayList into a separate class where I can store the lists as single pieces of information (IE: Information in the first part of ArrayList1 goes with information in the first part of ArrayList2 etc...) and then sort them. I don't know how to pass that information to another class though. This is a section of my main method that stores the information into a list. I need this information passed to a separate class called List.java:
String SelectStatement1 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count++;
}
ps.close();
ps = conn.prepareStatement(SelectStatement1);
rs = ps.executeQuery();
ArrayList<String> InvoiceIDList = new ArrayList<String>();
String InvoiceID = null;
int p = 0;
while (p < count){
rs.next();
InvoiceID = rs.getString("InvoiceID");
InvoiceIDList.add(InvoiceID);
p++;
}
ps.close();
p = 0;
Edit: This is only a section of my code, I already have the code open and close the connections, I only need information on how to pass the ArrayList to another class for sorting.

Create a method in your other class like this:
public void receiveList (ArrayList<String> invoiceIDList) {
// Do something with invoiceIDList data
}
It may not be a bad idea to create a constructor in your "List" class, that accepts the ArrayList and creates the class instance with the required data
Also, please change the name of that class!! It will be confusing to others who read your code, as you are passing an ArrayList already!
EDIT:
You could also have your class implement the List interface, which would make things a lot easier for you, because you can insert data into your class based on the position of the data in the ArrayList.
public class yourClass implements List<String> {
// Your class methods and variables...
}
If you wanted to expand on this to allow more than just Strings, you can change to: List<T>, this would give you a more generic approach.

First, I suggest you perform a SELECT COUNT() instead of iterating your rows in your first query. Then remember to close() both the PreparedStatement and ResultSet. Finally, I would suggest you program to the List<String> interface. Putting it all together like,
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
Connect to your database and initialize conn.
int count = 0;
try {
String query1 = "SELECT COUNT(InvoiceID) FROM Invoice;";
ps = conn.prepareStatement(query1);
rs = ps.executeQuery();
if (rs.next()) {
count = rs.getInt(1);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
The above block of code is necessary to close() both rs and ps in the correct order with the finally Block.
List<String> invoiceIdList = new ArrayList<>();
try {
String query2 = "SELECT InvoiceID FROM Invoice;";
ps = conn.prepareStatement(query2);
rs = ps.executeQuery();
while (rs.next()) {
invoiceIdList.add(rs.getString("InvoiceID"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally { // <-- it's identical to the finally block above.
try {
rs.close();
} catch (Exception ignored) {
}
try {
ps.close();
} catch (Exception ignored) {
}
}
// now you can pass invoiceIdList elsewhere...
if (!invoiceIdList.isEmpty()) {
doSomething(invoiceIdList);
}

Related

Java and Kotlin interoperability, managing data using Koltin Lambda?

So essentially, I am using java to obtain information, and then I am using Kotlin to manage the information. So what I have done so far is, I have stored my information into a ArrayList called tableData in java, I store all my elements into this list (I should have used a better name here) and then returned the list. My java code:
public static ArrayList<String> readAllData () {
//Connecting to database
Connection con = DbConnection.connect();
//Preparing statement
PreparedStatement ps = null;
//result set declaration
ResultSet rs = null;
//tableData String array
ArrayList<String> tableData = new ArrayList<String>();
try {
//Database initialization
String sql = "SELECT * FROM ProjectInfo";
ps = con.prepareStatement(sql);
rs = ps.executeQuery();
while (rs.next()) {
//for each iteration store the data into variable a from column projectName
String a = rs.getString("projectName");
//print out each element
//System.out.println("a = " + a);
tableData.add(a);
}
//other catch exceptions
} catch (SQLException e) {
System.out.println(e.toString());
} finally {
try {
rs.close();
ps.close();
con.close();
} catch (SQLException e){
System.out.println(e.toString());
}
}
//System.out.println(tableData);
//return all the data that has been stored into this array
return tableData;
}
In Kotlin, I created a property class called GettingData and passed one parameter projectName: ArrayList<String>. Then i moved onto actually printing out the data
class GettingData(var projectName: ArrayList<String>) {
}
fun ManageData() {
var arrayData = listOf<GettingData>(GettingData(DbConnection.readAllData()))
var projectNameData = arrayData.map {it.projectName}
for (projectName in projectNameData) {
println(projectName)
}
}
All my elements are printed out, however I cannot use the filter functions to call specific elements from the arrayList? I want to be able to call every element and print them out in a alphabetical order? I tried filter, sortedWith and find functions but I cannot seem to get it working. How can I achieve this?
I think your question boils down to wanting to print a list of strings in alphabetical order.
You can use the sorted() function:
for (projectName in projectNameData.sorted()) {
println(projectName)
}

ResultSet to HashMap

I am trying to pass the output of a ResultSet to Java HashMap.
Map<Integer, String> sIDpNumberHashMap = new HashMap<Integer, String>();
while (DBresult.next()) {
int sID = DBresult.getInt("slrid");
String pNumber = DBresult.getString("pNumber");
sIDpNumberHashMap.put(sID , pNumber );
System.out.println("Output1"+ sID + "\t" + pNumber + "\n");
}
System.out.println("Output2" + "\n" + sIDpNumberHashMap);
While the Output1 is showing all the records(from the DB). The put command only takes the last value from the ResultSet in.
Output1:
502332262 101E2571G103
502332262 101E2571G103
502332262 116E3139P001
502332262 117E3640G025
502332262 314B7159G003
502332262 117E3640G025
Output2:
{502332262=117E3640G025}
How do I make the put command to iterate over the results from the ResultSet?
All your IDs are identical (502332262), and HashMap doesn't allow duplicate keys. That's the reason you see only one entry in the HashMap (containing the last value you put in the Map).
If you want to allow duplicates, consider a different collection to hold the data. For example, you can use an ArrayList<SomeClass> where SomeClass contains the two properties you read from the DB.
I might be late but I believe someone can get an idea from what I did.
Recently I had an almost similar challenge where I wanted to build dynamic query results (whatever select query just returns its JSON list and question would vary a lot and I can't write method per query so I had to come up with something everyone will be calling).
Below is my sample code:
public <T> List<T> findWithDynamicQuery(String query){
Connection conn = null;
PreparedStatement statement = null;
List<Object> mResults = new ArrayList<>();
try {
conn = //use your connection parameters;
} catch (SQLException e) {
e.printStackTrace(out);
return (List<T>) mResults;
}
try {
statement = conn.prepareStatement(query);
ResultSet result = statement.executeQuery();
ResultSetMetaData metaData = result.getMetaData();
int column = metaData.getColumnCount();
while (result.next()) {
HashMap<Object, Object> rows = new HashMap<>();
for(int i = 1; i <= column; i++){
rows.put(metaData.getColumnLabel(i), result.getObject(i));
}
mResults.add(rows);
}
result.close();
return (List<T>) mResults;
} catch (SQLException e) {
e.printStackTrace(out);
}finally{
if(statement != null){
try {
statement.close();
} catch (SQLException e) {
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
}
}
}
return (List<T>) mResults;
}

null pointer exception java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
I am new so bear with me. But I am getting a NullPointerException somewhere in here. Any ideas? Thanks!
private void loadInstructors()
{
// get all account numbers from database
try
{
//myResultSet = myStatement.executeQuery( "SELECT DISTINCT lastname FROM InstEval" );
myResultSet = myStatement.executeQuery( "SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL" );
// add account numbers to accountNumberJComboBox
while ( myResultSet.next() )
{
//instructorComboBox.addItem( myResultSet.getString( "lastname" ) );
TeamsComboBox.addItem( myResultSet.getString( "TEAMNAME" ) );
}
myResultSet.close(); // close myResultSet
} // end try
catch ( SQLException exception )
{
exception.printStackTrace();
}
}
Here is one way to do what you seem to want; note, I've attempted to generalize a few things here. Firstly, you should use descriptive method names (if you want team names, mention team names). Secondly, you should return appropriate types (and you're doing a distinct query) so we should return a Set - I picked a sorted set, but that's not in anyway mandatory. Next, I chose to pass the Connection object into the method. It's a good idea to close resources in the block that opens them, and thusly I only close the PreparedStatement and ResultSet objects. Finally, if you don't keep your comments updated with your code they are worse then useless.
// I think sorting the team names is good idea, and they're distinct...
private SortedSet<String> getTeamNames(Connection conn) {
// Let's use a Set!
SortedSet<String> teamNames = new TreeSet<String>();
// get all team names from database, at least store the query in a local
// String variable. You should probably extract it to a properties file.
final String query = "SELECT DISTINCT TEAMNAME FROM APP.TEAMEVAL";
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
// add team names to teamNames
while (rs.next()) {
teamNames.add(rs.getString("TEAMNAME"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return teamNames;
}

Printing a query from a database

I am trying to access a database and print off a query.
I am trying to access a DEVICE table and print off the DEVICE_ID, but i am unsuccessful so far.
Here is my code at the moment;
public static void main(String[] args) throws FileNotFoundException {
try {
Class.forName("org.hsqldb.jdbc.JDBCDriver");
Preferences sysRoot = Preferences.systemRoot();
Preferences prefs = sysRoot.node("com/davranetworks/zebu");
url = prefs.get("dburl", "jdbc:hsqldb:E:\\eem\\eemdb");
} catch (Exception e) {
e.printStackTrace();
}
Connection c = getConnection();
try {
c.setAutoCommit(true);
Statement s = c.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = s.executeQuery("SELECT * FROM eem_db.device");
ResultSet deviceId = s.executeQuery("select device_id from eem_db.device");
System.out.println(deviceId);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection c = null;
try {
c = DriverManager.getConnection(url);
} catch (SQLException e) {
System.out.println("Error initialising connection" + e);
}
return c;
}
The returned value is org.hsqldb.jdbc.JDBCResultSet#1d3d68df.
I don't know what this value relates to as I was expecting 3 integer values.
Can anyone help me on this?
You have to iterate over the rows contained in the ResultSet and for each row get the column you want:
ResultSet deviceIdRS = s.executeQuery("select device_id from eem_db.device");
while(deviceIdRS.next()) {
System.out.println(deviceIdRS.getString("device_id"));
}
You must use the ResultSet getXXX method that correspond with your column type, for example, getInt, getString, getDate...
That ResultSet deviceId is actually an object contains rows of result from your sql, so you only can see the memory address when you print it out.
You need something like:
while(deviceId.next()){
System.out.print(deviceId.getInt(1));
}
s.executeQuery("select device_id from eem_db.device"); is returning a resultSet, you must find out the value from result set.
like
int device_id = resultset["deviceId"];
while (deviceId.next())
{
// Printing results to the console
System.out.println("device_id- "+ deviceId.getInt("device_id");
}
iterate object using resultset.
You are printing object of ResultSet, it won't give you the right values.
You need to iterate the loop like below
while(deviceId.next()) {
int integerValue = deviceId.getInt(1);
System.out.println("content" + integerValue)
}
deviceId.close();
s.close();

Store rows of resultset in array of strings

I want to count the numbers of entries in resultset and then store these values in an array and pass this array to create a graph.
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename"); // this statement will select the unique entries in a
particular column provided by jtextfield
int count=0;
while(rs.next())
{ ++count; } // This will count the number of entries in the result set.
Now I want to store the values of result set in an array of string. I used the following code
String[] row = new String[count];
while(rs.next())
{
for (int i=0; i <columnCount ; i++)
{
row[i] = rs.getString(i + 1);
}
}
Error : Invalid Descriptor Index.
Please suggest how to copy the result of resultset in array.
For example if I enter priority in jTextField , the result set will contain
priority1
priority2
priority3
In your first while loop you read all the entries in the ResultSet, so when executing the second while loop there's nothing else to read. Also, the index of ResultSet#getXxx starts at 1, not at 0. Also, since you don't know the amount of rows that you will read, it will be better using a List backed by ArrayList instead.
Considering these, your code should look like:
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+
" as call from tablename");
List<String> results = new ArrayList<String>();
while(rs.next()) {
results.add(rs.getString(1));
}
Based in your comment, I extended the sample:
public List<String> yourRandomQuery(String columnName) {
Connection con = null;
ResultSet rs = null;
List<String> results = new ArrayList<String>();
try {
String baseQuery = "SELECT DISTINCT %s AS call FROM tablename";
con = ...; //retrieve your connection
ResultSet rs = stmt.executeQuery(String.format(baseQuery, columnName));
while(rs.next()) {
results.add(rs.getString(1));
}
} catch (SQLException e) {
//handle your exception
e.printStacktrace(System.out);
} finally {
closeResource(rs);
closeResource(con);
}
return results;
}
//both Connection and ResultSet interfaces extends from AutoCloseable interface
public void closeResource(AutoCloseable ac) {
try {
if (ac != null) {
ac.close();
}
} catch (Exception e) {
//handle this exception as well...
}
}
public void someMethod() {
//retrieve the results from database
List<String> results = yourRandomQuery(jTextField.getText());
//consume the results as you wish
//basic example: printing them in the console
for(String result : results) {
System.out.println(result);
}
}
Try this
ResultSet rs = stmt.executeQuery( "SELECT distinct "+jTextField.getText()+" as
call from tablename");
List<String> list=new ArrayList<>();
while(rs.next())
{
list.add(rs.getString(1));
}
Why not just create a HashSet<String> and write into that. Note that HashSet is unordered, just like your query. By using a collection that is of arbitrary size you don't need to determine the require dsize in advance.

Categories