Data from HSQLDB table into two dimensional array using Java - java

I am trying to get data from LivEx table as list, and then save that data into two dimensional array called array. My method is returning object[][].
I made up this code from googling here and there and taking bits from every example, however I am doing something wrong which I can't quite seem to put my finger on. It gives me an exception which is a NullPointerException whenever I call getLivExList(currentPlan).
Here is my code:
public static Object[][] getLivExList(String currentPlan) throws Exception {
Session s = null;
try {
s = HibernateUtil.getSessionFactory().getCurrentSession();
s.beginTransaction();
String query = "select F.item, F.category, F.amount from LivEx F where F.planName=?";
Query q = s.createQuery(query);
System.out.println(query);
List fp = q.list();
s.getTransaction().commit();
Object array[][] = new Object[fp.size()][3];
for (int i = 0; i < fp.size(); i++) {
for (int j = 0; j < 3; j++) {
array[i][j] = fp.get(j +(3 * i));
}
}
System.out.println("getLivExdata in networthentitymanager OKAY");
return array;
} catch (Exception e) {
System.out.println("problem at getLivExdata in networthentitymanager");
throw e;
} finally {
if (s != null) {
HibernateUtil.closeSession();
}
}
Please help me find out where the problem is coming from.
This is the exception I am getting:
SEVERE: null
org.hibernate.QueryException: Expected positional parameter count: 1, actual parameters: [] [select F.item, F.category, F.amount from LivEx F where F.planName=?]
0 problem
at org.hibernate.impl.AbstractQueryImpl.verifyParameters(AbstractQueryImpl.java:319)
at org.hibernate.impl.AbstractQueryImpl.verifyParameters(AbstractQueryImpl.java:275)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:75)
at com.elitconsultancy.finplanner.entity.NetWorthEntityManager.getLivExList(NetWorthEntityManager.java:213)

You're not setting the plan name for the query, even 'though you've specified a positional parameter (?).
Put this before your call to list:
query.setString(0, currentPlan);

List fp = q.list();
s.getTransaction().commit();
Object array[][] = new Object[fp.size()][3];
you are getting size of list. If list returned by q.list() is null, that is no matching rows found then you will get Null pointer exception.
Thats the first thing i see that might be wrong in the code
before invoking methods on list, u can check whether it is null or not.

Related

Returning a different type than the parameter

This is hw and I am really stuck on how to get my code to return what I want it to return. I am trying to return a String value with a given index value. I thought all I had to do was return the string value at the given index but I am not getting the right answer.
public void add(String candidate){
if (candidate.equals(null)){
throw new RuntimeException();
}
String[] contenders = new String[candidates.length+1];
// copy the array manually because I'm restricted from ArrayLists
for (int i = 0; i < candidates.length; i++){
contenders[i] = this.candidates[i];
}
this.candidate = candidate;
contenders[contenders.length-1] = this.candidate;
this.candidates = new String [contenders.length];
After adding values to a newly constructed array the tester wants to get the string value at a given index
public String get(int index){
if (index < 0 || index > candidates.length) {
throw new RuntimeException("Your argument was not within bounds.");
}
for (int i = index; i < candidate.length(); i++){
candidate = candidates[index];
}
return candidate;
I have been working on it and I finally was able to have candidate stop pointing to null it is giving the wrong value for the given index so for example I want 'X' at candidate[3] but I am getting 'Y' because that is the last value that candidate keeps. I have tried just returning candidates[index] but then it tells me that the value at that index is null. As I have gone through the debugger it appears that my original array is not being copied over properly but I am not sure what I should try next. Thanks in advance.
This is my constructor:
public CandidateList(){
candidates = new String[0];
}
public CandidateList(String[] candidates){
this.candidates = new String[candidates.length];
CandidateList candidateList = new CandidateList();
There is a lot that can be improved in your code, let me add some comments
public void add(String candidate){
//if candidate is actually null you are calling null.equals
//which means this will always result in a NullPointerException
//you can remove this if if you want
if (candidate.equals(null)){
throw new RuntimeException();
}
...
//think about what you are doing here,
//you are setting this.candidates to a new empty array
//(is big contenders.length, but still empty)
this.candidates = new String [contenders.length];
Second part:
public String get(int index){
//you are missing an '=' in index >= candidates.length
if (index < 0 || index > candidates.length) {
throw new RuntimeException("Your argument was not within bounds.");
}
//this for loop is wrong, you are changing 'i' but never use it..
//just return candidates[index] like you said before.
//It was probably null because of the error above
for (int i = index; i < candidate.length(); i++){
candidate = candidates[index];
}
return candidate;
A note on the RuntimeException(RE): if you catch a NullPointerException (NPE) and throw a RE you are actually losing information (since NPE is a more specific error rather than RE). If you want to catch/throw put at least a significant message like "candidate cannot be null"
Let's now analyze the constructor:
public CandidateList(){
candidates = new String[0];
}
public CandidateList(String[] candidates){
// you are doing the same error as above here:
// when you do this you create an EMPTY list of size candidates.lenght
// correct code is this.candidates = candidates
this.candidates = new String[candidates.length];
// this is not necessary, constructors don't need to return anything,
//here you are just creating a new instance that will not be used anywhere
CandidateList candidateList = new CandidateList();
Constructors create objects, they don't return data. I suggest you to take a look at this question Does a Java constructor return the Object reference? and in general read a bit more about constructors

Getting values from object in java

How I can get those values from this object? I was trying to getFields, getDeclaredFields etc. but everything is empty.
The problem is that Field[] myField = o.getClass().getDeclaredFields(); always return an empty array.
I am getting those values from database this way:
Query reqDisplayResponse = em.createNativeQuery("Select * FROM pxds_displayResponse");
List<Object> displayResponseList = reqDisplayResponse.getResultList();
And I want to print those values:
for(Object o: displayResponseList) {
for(Field field: o.getClass().getDeclaredFields()) {
log.info(field.getName());
}
}
Unfortunately log.info is unreachable.
Ok, here is solution. In fact object is an array, getDeclaredFields() return empty table, in documentation we can read:
If this Class object represents an array type, a primitive type, or void, then this method returns an array of length 0.
So in this situation it is useless. All we have to do is iterate over this object this way:
for(Object o: displayResponseList) {
for(int i = 0; i < 7; i++) {
System.out.println(((Object[])o)[i].toString());
}
System.out.println("...............");
}
Hope this will help someone in future.
You should use getDeclaredField, and then use get on it, passing the object as parameter.
Like this:
Field myField = object.getClass().getDeclaredField("_myField");
myField.setAccessible(true);
return (Integer) myField.get(object);
Try to display the object 'o' like an array:
for(int index = 0 ; index < 10 ; index++){
Log.info(String.valueOf(o[index]));
}
I think those fields you are trying to access are private
So in order to access private fields you have to:-
for (Field f : object.getClass().getDeclaredFields()) {
f.setAccessible(true);
Object o;
try {
o = f.get(object);
} catch (Exception e) {
o = e;
}
System.out.println(f.getGenericType() + " " + f.getName() + " = " + o);
}
This is an ID given by the Eclipse debugger, not by Java. You cannot access it.
There is System.identityHashCode(Object) to get the Object identity. (not the same ID)
If you want an ID like the one shown in the Eclipse debugger, you'd have to allocate them yourself.
Here is some general direction how you could do something like that:
Elegant way to assign object id in Java
Gwozdz, I think I understand your question. If I understood correctly, you are having problemas to access the value from a list of objects, in your image code example I'm seeing that you are using List. Try to use List<Object[]> and then use a foreach to access every value of your matrix.
List<Object[]> displayResponseList = reqDisplayReponse.getResultList();
foreach(.....){
foreach(.....){
[manipulate you object value here]
}
}
Just for your information: Matrix is a list of lists. In that case a list of array.

NullPointerException java error

i'm still starting to Learn OOP and there is this error that keeps popping out in my code; says that Exception in thread "main" java.lang.NullPointerException
public class SlumbookDriver{
public static void main(String args[]){
Slumbook[] contacts = new Slumbook[19];
... // index is an int and is the value of the index of the array
... // i feed it to a function "void viewEntry" that just shows
// the other attributes of the class Slumbook
viewEntry(index, contacts);
}
}
then i have the function viewEntry
public static void viewEntry(int index, Slumbook[] contacts){
Scanner sc = new Scanner(System.in);
if(index == 0){
System.out.println("Array is empty");
}
else{
String id = contacts[index].getIdNo();
System.out.println("Please enter ID number");
String idNo = sc.next();
if(id != idNo){
while(id != idNo && index != -1){
index--;
id = contacts[index].getIdNo();
}
if(index == -1){
System.out.println("ID does not exist");
return; //terminate action since the ID number does not exist
}
}
System.out.println(contacts[index].viewDetails());
}
}
You are just initializing the array
Slumbook[] contacts = new Slumbook[19];
but not its elements hence you will get a NullPointerException when you access the array element in statements like this:
String id = contacts[index].getIdNo();
When you create an array of objects, the objects within the array are not initialized, you need to initialize them using new operator before using them. Something like this:
contacts[index] = new Slumbook();
The problem here is that you have initialized an array of SlumBook, however the contents of the array need to be initialized.
For starters, just initialize the contents:
for (int i = 0; i < contacts.length; i++)
{
contacts[i] = new SlumBook();
}
Do this before using contacts in the method viewEntry(int, SlumBook[])
A NullPointerException happens when you try to access a field or a method in a reference but that reference is null.
For instance
Slumbook a = null;
a.getIdNo(); // NullPointerException
Same happens if you have an array
Slumbook [] data = new Slumbook[N];
data[i].getIdNo(); /// NPE
The second example would throw NPE if the reference contained at position i happens to be null.
When you get an exception a stack trace is shown and it contains the file name and exact line number(most of the times) where the exception occurred

ArrayList in Session object seems to lose contents

I'm having a problem with retrieving and casting ArrayList from session. I get the following error:
javax.servlet.ServletException: java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
I stored the arrayList in the session:
List<UserApplication> userList = uaDAO.searchUser(eds);
if (!userList.isEmpty()) {
request.getSession().setAttribute("userList", userList);
action_forward = EDITSUCCESS;
and for casting the session object to ArrayList, did the following:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
I'm getting the error over here in the DAO class:
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
.
.
You are explicitly asking for 2nd (studtList.get(1)) and 3rd (studtList.get(2)) item in the list but never really make sure this list is big enough. Moreover your code apparently doesn't even compile:
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = ///...
}
try {
uaDAO.editUser(edt,studtList);
studtList is unaccessible in try block, also parenthesis in if statement are unmatched.
Check your studtList value.
From the error it seems your studtList only contain one item and you're try to get the second item with this code :
int stCode =Integer.parseInt(studtList.get(1).toString());
Change your code like this :
public void editUser(EditStudentForm edt,List studtList) throws Exception {
PreparedStatement pst = null;
StringBuilder sb = new StringBuilder();
if(studtList.size() > 1)
int stCode =Integer.parseInt(studtList.get(1).toString()); GETTING ERROR HERE
if (studtList.size() > 2 && edt.getTitle() != null && !edt.getTitle().equals(studtList.get(2).toString())) {
sb.append("title = '").append(edt.getTitle()).append("'");
}
}
In studtList there are no two elements and size of list maybe 1 or 0 elements, you should check it before try to call studtList.get(1). In ArrayList indexing start from 0 and if you want get first element you should call studtList.get(0).
In this code:
EditStudentForm edt = (EditStudentForm)form;
if ((session.getAttribute("userList")) instanceof List){
List <UserApplication> studtList = (ArrayList<UserApplication>)session.getAttribute("userList");
}
try {
uaDAO.editUser(edt,studtList);
action_forward = EDITSUCCESS;
}
You create a new variable 'studtList' that is never used. It's scope is only the { } pair around that one line.
There has to be another variable by that same name, studtList, in the outer scope so the 'editUser()' call can work.
Additional Note
As the other folks have answered, it looks like you may be doing a .get(1) and expecting the first element of the array list. Maybe. Maybe not.

Display Hibernate Query in JTable

I'm seeking an efficient way to display an SQL table queried via Hibernate in a JTable.
Query q = em.createNamedQuery("Files.findAll");
List rl = q.getResultList();
It would probably be preferable to use the List returned by that (In this case, that would make a list of Files objects (where Files is an internal class, not java.io.File)), but I won't be picky as long as it is neat.
I have one answer I worked up below, but that doesn't work very well. I'd going to end up having to write a TableModel for it if I keep going down this path.
There are a lots and lots of ways to do this, but are you looking for something that would automatically figure out the columns or what? If you used the java reflection pieces you can read the Hibernate annotations to find out the column names and populate the JTable that way...
Otherwise this is just a straight forward piece of code that a. creates a JTable and TableModel, and b. populates the display with the database data.
EDIT:
I think this example may cover walking the annotation tree and processing them. The specifics are the AnnotationProcessorFactory part iirc.
EDIT 2:
I also found this library which is built to help lookup annotations at runtime. One of their examples is looking up Entity classes in hibernate to build a resource list - I believe you could do something similar to find classes that that implement #column, or #basic etc. This should allow you via reflection to pretty easily do it, but as I said java's standard library already provides the ability to walk the annotation tree to find out the column names - at which point creating the JTable from that should be very easy to do in a programmatic way.
EDIT 3:
This code is all that and a bag of chips! From here you should easily be able to walk the list of maps and pull out all of the info you want, the value, its class type, the field name for the column headers... Note that it isn't particularly safe.. I've dropped out all of the error code I did while testing to keep it short...
List<Map> createTable(List queryResults) {
List<Map> r = new LinkedList<Map>();
for (Object o : queryResults) {
r.add(entityMap(o));
}
return r;
}
Map entityMap(Object obj) throws Throwable {
Map m = new HashMap();
for (Field field : getFields(obj.getClass())) {
Method method = getMethod(field);
Object value = method.invoke(obj);
m.put(field, value);
}
return m;
}
List<Field> getFields(Class<?> clazz) {
List<Field> fields = new LinkedList<Field>();
for (Field field : clazz.getDeclaredFields()) {
Column col = field.getAnnotation(Column.class);
if (col != null)
fields.add(field);
}
return fields;
}
Method getMethod(Field field) throws NoSuchMethodException {
Class<?> clazz = field.getDeclaringClass();
String name = "get" + uppercase(field.getName());
Method method = clazz.getMethod(name);
return method;
}
String uppercase(String str) {
return str.substring(0,1).toUpperCase() + str.substring(1);
}
Did you take a look at the org.hibernate.metadata classes. These provide you metadata information about classes and collections. You can also make calls to SessionFactory.getClassMetadata(Class) to get the metadata information for the class in question.
In the answer below I expect that your HQL returns not a list of objects, but a list of arrays of necessary properties that you wish to show in JTable (i.e. that you're using so calling report queries).
In that case you can write simple TableModelAdapter that will be used as a TableModel for JTable.
public class TableModelAdapter extends AbstractTableModel{
private List<Object[]> list;
public TableModelAdapter(List<Object[]> aList){
list = aList;
}
public int getColumnCount() {
if (list == null){
return 0;
}
if (list.size() == 0){
return 0;
}
return list.get(0).length;
}
public int getRowCount() {
if (list == null){
return 0;
}
return list.size();
}
public Object getValueAt(int row, int column) {
if (list == null){
return null;
}
return list.get(row)[column];
}
}
If you have to return list of objects we can change the example and path throw properties via reflection instead of array.
Well, here's what I ended up doing for now:
//client-side class
public String[][] getFilesArray() {
List<Files> files = remote.getFiles();
String[][] x = new String[files.size()][];
for (int i = 0; i < files.size(); i++) {
x[i] = files.get(i).getStringArray();
}
return x;
}
//DAO class
public String[] getStringArray() {
return new String[] {
fileid.toString(),
name,
DateFormat.getInstance().format(timestamp),
status,
hash
};
}
public static String[] getColumnNames() {
return new String[] {
"Id",
"Name",
"Timestamp",
"Status",
"Hash"
};
}
JIDE Data Grids provides a HibernateTableModel that could provide the functionality you are looking for if you are happy to buy a third party library.
private void DataRetrive() {
DefaultTableModel tbl = (DefaultTableModel) jtblDataRet.getModel();
tbl.setRowCount(0);
try {
// call local method which was opensession
opensession();
if (!session.isOpen()) {
session = Hibernate_ut.getSession().openSession();
tx = session.beginTransaction();
String hQ = "From Student";
Query que = session.createQuery(hQ, Student.class);
List<Student> list = (List) que.list();
for (int i = 0; i < list.size(); i++) {
Vector vt = new Vector();
vt.add(0, list.get(i).getStudentName().toString());
vt.add(1, list.get(i).getStudentAddr().toString());
vt.add(2, list.get(i).getGrade().toString());
vt.add(3, list.get(i).getContact().toString());
tbl.addRow(vt);
}
}
} catch (HibernateException e) {
System.out.println(e);
e.printStackTrace();
tx.rollback();
}
}

Categories

Resources