How to change String Array to ArrayList in java - java

Here is the original code which has defined String-Array (25). It is working perfectly. But I don't need to define it as 25. Instead, I used arraylist. Please check my code.
Using String of array:
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
String[] emailAddress = new String[25];
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Here, I need to change String-Array to Arraylist. I tried something like this,
public String[] getemailAddr(String strAccountnbr) throws Exception {
String strQuery2 = null;
ResultSet rs = null;
PreparedStatement ps = null;
//Newly tried //
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
//Newly tried //
int i=0;
strQuery2 = "SELECT c.EmailAddress AS EmailAddress" +
" FROM customeremailid c " +
"WHERE c.AccountNbr = ? " ;
logMsg("strQuery2: "+strQuery2);
ps = getDBConn().prepareStatement(strQuery2);
ps.setString(1, strAccountnbr);
rs = ps.executeQuery();
while(rs.next())
{
emailAddress[i]=(rs.getString("EmailAddress"));
logMsg("emailAddress[i]"+" "+i+": "+emailAddress[i]);
i=i+1;
}
return emailAddress;
}
Email ids are get from database instead of example.com.
But I am getting
java.lang.ArrayIndexOutOfBoundsException: 0 error
in this line.
emailAddress[i]=(rs.getString("EmailAddress"));
Please help!

This is not how you use an ArrayList.
First, you need to write:
List<String> strArrEmailIds = new ArrayList<>();
So, program to the interface and use the Java 7 diamond operator.
Next, remove the index i. You don't need this.
Finally, just do:
emailAddress.add(rs.getString("EmailAddress"));
To convert it back to an String[] you can then do:
String[] arr = emailAddress.toArray(new String[emailAddress.size()]);
Here is my suggestion for you final code:
public String[] getemailAddr(String strAccountnbr) throws Exception {
final List<String> emailAddress = new ArrayList<>();
final String strQuery2 = "SELECT c.EmailAddress AS EmailAddress"
+ " FROM customeremailid c "
+ "WHERE c.AccountNbr = ? ";
try (final PreparedStatement ps = getDBConn().prepareStatement(strQuery2)) {
ps.setString(1, strAccountnbr);
try (final ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
emailAddress.add(rs.getString("EmailAddress"));
}
}
}
return emailAddress.toArray(new String[emailAddress.size()]);
}
I have removed your pointless assignments to null. I have added try-with-resources blocks to close your external resources, you code was one massive memory leak.

If you have a ArrayList, then you dont need a array again, indeed a ArrayList is backed by Array itself and its dynamic in size.
List<String> emailAddress= new ArrayList<String>(); // dynamic array
...
while(rs.next()){
emailAddress.add((rs.getString("EmailAddress"));
...
}
return emailAddress.toArray(new String[emailAddress.size()]); // creating array of String type
And ArrayList#toArray converts List to Array which has done at last in the code.

declare it as
ArrayList<String> emailAddress= new ArrayList<String>();
...
emailAddress.add((rs.getString("EmailAddress"));
convert it to String[]:
return emailAddress.toArray(new String[emailAddress.size()]);

You use ArrayList here wrongly in your code. When you define
ArrayList<String> strArrEmailIds = new ArrayList<String>();
String[] emailAddress= new String[strArrEmailIds.size()];
strArrEmailIds.toArray(emailAddress);
strArrEmailIds by default has a size of 0, so the generated emailAddress array also gets a length of 0. Later in the while loop, you are trying to assign the value to the emailAddress[0], it will throw ArrayIndexOutOfBoundsException.
Instead, the correct way is :
ArrayList<String> strArrEmailIds = new ArrayList<String>();
//....
while(rs.next()){
//....
strArrEmailIds.add(rs.getString("EmailAddress"));
}
//....
String[] emailAddress = strArrEmailIds.toArray(new String[strArrEmailIds.size()]);

java.lang.ArrayIndexOutOfBoundsException: 0 if your result set goes beyond 25 itteration.
How to convert array to ArrayList ?
Arrays.asList(myArray)
in your case you can have a list and in the resulset itteration you can add them to the list like
List<String> emails = new ArrayList<String>();
while(...){
emails.add(rs.getString("EmailAddress"));
}

Related

Iterate 2D array of ResultSet to JTable

I have a resultset class that all of the query operations are stored. My problem is thatI am trying to fill a jtable with resultset data but I am only able to display the data in one column where I have three. This is the snippet of the resultset class:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
List<String> id = new ArrayList<>();
List<String> item = new ArrayList<>();
List<String> supplier = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
//metaData = rs.getMetaData();
//int columnNum = metaData.getColumnCount();
while(rs.next()){
id.add(String.valueOf(rs.getInt("id")));
item.add(rs.getString("ItemDesc"));
supplier.add(rs.getString("Supplier"));
}
values.add(id);
values.add(item);
values.add(supplier);
return values;
}
and this is the jtable method that I am trying for hours to solve:
public static DefaultTableModel loadTable(){
ModelDB model = null;
DefaultTableModel tableModel = new DefaultTableModel();
tableModel.addColumn("ID");
tableModel.addColumn("Fabric");
tableModel.addColumn("Supplier");
try{
List<String> id = model.getAllFabrics().get(0);
List<String> item = model.getAllFabrics().get(1);
List<String> supplier = model.getAllFabrics().get(2);
//System.out.println(model.getAllFabrics().size()); tableModel.addRow(new Object[]{subRow});
for(List<String> row:model.getAllFabrics()){
tableModel.addRow(new Object[]{id,item,supplier});
}
}catch(SQLException ex){
ex.printStackTrace();
}
return tableModel;
}
I can't find a way to iterate the values to display in their respective column.
Original answer
You are almost there! You only need to change the loop:
for(int i = 0; i < id.size(); i++) {
tableModel.addRow(new Object[] {id.get(i),item.get(i),supplier.get(i)});
}
But as said in the comments, you should consider changing to an array of rows, not columns.
Edit
This is one approach. It is basically same as your code except the rows/columns are interchanged so the method returns a List of rows, not columns:
public static List<List<String>> getAllFabrics() throws SQLException{
sql = "SELECT * FROM fabric";
List<List<String>> values = new ArrayList<>();
stmt = con.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next()){
List<String> row = new ArrayList<>();
row.add(String.valueOf(rs.getInt("id")));
row.add(rs.getString("ItemDesc"));
row.add(rs.getString("Supplier"));
// Now row contains {id, item, supplier}
values.add(row);
}
return values;
}
Then in your loadTable() method change to:
...
try{
for(List<String> row: model.getAllFabrics()){
tableModel.addRow(row.toArray(new String[row.size()]);
}
...
In your original code you call model.getAllFabrics() multiple times to get the return value. This is not good because every time you do that the method gets called and it needs to make the SQL-request again etc. Store the return value in a variable instead. In this case though as the return value is only accessed once you can equally just do as I described above.
Hope this helps :)

Storing values inside while loop using JDBC

ResultSet rs = dbmd.getSchemas();
while(rs.next()) {
String DbNames = rs.getString("TABLE_SCHEM");
}
I'm trying to store the value of DbNames and use it later. I tried using ArrayList
ResultSet rs = dbmd.getSchemas();
ArrayList<String> dbs = new ArrayList<>();
while(rs.next()) {
dbs.add(rs.getString("TABLE_SCHEM"));
}
for(String[] s : dbs)
{
System.out.println(Arrays.toString(s));
}
I'm new to programming and used StackOverflow resources to fix my problem, but I'm still having problems. Please help me figure this out.
Currently, your ArrayList is a raw type because you have not specified a data type for the ArrayList. Change your ArrayList declaration to a generic type by using
ArrayList<String> dbs = new ArrayList<>();
That way, when you try to access the values later, they will be String instead of Object.
Your new code will be
ResultSet rs = dbmd.getSchemas();
ArrayList<String> dbs = new ArrayList<>();
while(rs.next()) {
dbs.add(rs.getString("TABLE_SCHEM"));
}
for(String s : dbs) {
System.out.println(s);
}
Create ArrayList to save your data retrieved from the result set as below:
ResultSet resultset = ;
ArrayList<String> arrayList = new ArrayList<String>();
while (resultset.next()) {
arrayList.add(resultset.getString('TABLE_SCHEM'));
}

ResultSet to Array

I have a Result set returned using a query:
String query = "select Bookname, SubjectName from books join Subjects on Subjects.SubjectID = Books.subjectID where classID = '1a'";
ResultSet temp = null;
try
{
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
temp = rs;
}
I was just wondering is it possible to turn the Resultset into two seperate arrays: eg BookName[] and BookSubject[] so I can show them in a list view later on? Relatively new to resultset and this concept in android
You should be able to easily iterate through the results on the result set, populating each array with the results as you interate.
Something like this:
...
ResultSet rs = st.executeQuery(query);
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> subjects = new ArrayList<String>();
while (rs.next()) {
names.add(rs.getString(1));
subjects.add(rs.getString(2));
}
// finally turn the array lists into arrays - if really needed
String[] nameArr = new String[names.size()];
nameArr = names.toArray(nameArr);
String[] subjectArr = new String[subjects.size()];
subjectArr = subjects.toArray(subjectArr);
Hope that helps!

Need a consolidated object value out of the while loop

I am trying to get the values from the database using servlet and it retrieving fine inside the while loop only i can accessing the values retrieved from the database but i need to consolidatre all values into a single object. here is my code,
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
/*fos = new FileOutputStream(filename);
out = new ObjectOutputStream(fos);
System.out.println("****"+out.TC_OBJECT);
out.writeObject(testCase);
out.close();*/
}
you can simply store your data in a List...
String moduleId = request.getParameter("moduleId").trim();
String temp[] = moduleId.split("/");
for(String s:temp){
String modId[]=s.split("/");
PreparedStatement ps = null;
Connection connection=DatabaseConnection.getConnection();
ps=connection.prepareStatement("select * from testcase_sahi where module_id=?");
ps.setString(1,modId[0]);
ResultSet rs=ps.executeQuery();
List temporaryList = new ArrayList(); //HERE
while(rs.next()){
System.out.println(".............TC ID...."+rs.getString("testcase_id"));
System.out.println(".............TC Name...."+rs.getString("testcase_name"));
testCase=rs.getString("testcase_name");
temporaryList.add(testCase); //HERE
}
serializeData(temporaryList) //and HERE
}

Inserting individual values of arrary list in table

I have an arraylist of strings
ArrayList myList = new ArrayList();
myList = [url1,url2,url3];
I need to insert these urls in 3 different rows in the database.This is how I am doing it.
while(myList.size()!=0)
{
//get individual values in the array list
int idx=0;
String url= myList.get(idx++).toString() ;
String insert="INSERT into test (url) values (?)";
prepstmt = conn.prepareStatement(insert);
prepstmt .setString(r++, url);
prepstmt.executeUpdate();
}
This goes to infinite loop.
Can someone please help me correct my code? Insert part of code is fine. But I am failing to get the individual urls.
Thanks!
Try this:
String insert = "INSERT into test (url) values (?)";
for (String url : myList) {
prepstmt = conn.prepareStatement(insert);
prepstmt.setString(1, url);
prepstmt.executeUpdate();
}
#niculare give the best way you need to change your code.
but if you don't want to to use for-loop you need to change your if-statement like this:
int idx=0;
while(idx < myList.size())
{
String url= myList.get(idx).toString() ;
String insert="INSERT into test (url) values (?)";
prepstmt = conn.prepareStatement(insert);
prepstmt .setString(r++, myURL);
idx++;
}
or if you not need this list any more use remove method:
while(myList.size()!=0)
{
//get individual values in the array list
int idx=0;
String url= myList.remove(idx++).toString() ;
String insert="INSERT into test (url) values (?)";
prepstmt = conn.prepareStatement(insert);
prepstmt .setString(r++, myURL);
}
you can use listIterator:
ListIterator<String> iter = myList.listIterator();
while(iter.hasNext()){
String url = (String) iter.next();
String insert="INSERT into test (url) values (?)";
prepstmt = conn.prepareStatement(insert);
prepstmt .setString(r++, myURL);
}
but I repeat once more: the best way is to use for-loop.
And one more advice. create you list like this:
List<String> myList = new ArrayList<String>();
UPDATE
this is one of my examples:
public class test2 {
public static void main(String ... args) {
ArrayList<String> myList = new ArrayList<String>();
myList.add("123");
myList.add("245");
myList.add("678");
ListIterator<String> iter = myList.listIterator();
while(iter.hasNext()){
String url = (String) iter.next();
System.out.println(url);
}
}
Posting full stack trace:
[3/30/13 2:35:00:241 GMT-06:00] 00000251 SystemOut O
com.ibm.dw.register.PubHandler handleMessage(String promoter,
String topic, String message) com.ibm.db2.jcc.am.eo: The value of a
host variable in the EXECUTE or OPEN statement is out of range for its
corresponding use.. SQLCODE=-302, SQLSTATE=22001, DRIVER=3.57.110

Categories

Resources