I have saved values retrieved from a database in java to an arraylist.
I have used a class to save the data to the array list as shown below.
ArrayList<NewSms> details = new ArrayList<NewSms>();
try{
Statement query = conn.createStatement();
ResultSet result = query.executeQuery("Select `senderAddress,message,linkid from sdp_smsincoming where status=0 AND smsServiceActivationNumber =1234 ");`
while(result.next()){
String address = result.getString("senderAddress");
String message = result.getString("message");
String linkid = result.getString("linkid");
NewSms smsdetails = new NewSms();
smsdetails.set_address(address);
smsdetails.set_message(message);
smsdetails.set_linkid(linkid);
details.add(smsdetails);;
}
}
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?By individually i mean getting the address,message and linkid per row in the arraylist.
However i now want to retrieve the values individually per row,from another class in the program.How can i do this?
You just access each NewSms in the list. To access one by index, you could use:
NewSms sms = details.get(2); // Or whatever
// Now access the properties of sms
Or to access each of them in turn, use an enhanced for loop:
for (NewSms sms : details) {
// Now access the properties of sms
}
Note that to comply with Java naming conventions, your NewSms class should have methods such as getAddress, setAddress - not set_address.
Also note that you need to close your result set / statement / connection - if you're using Java 7, you can use a try-with-resources statement; otherwise you should use finally blocks.
EDIT: If your problem is actually just returning the list, that's easy:
public List<NewSms> loadSmsDetails() {
// Code as before...
return details;
}
Then just call it from your other class:
// Where repository is a reference to an instance of the class containing the above method
List<NewSms> allDetails = repository.loadSmsDetails();
for(NewSms smsdetails:details){
String address = smsdetails.get_address();
String message = smsdetails.get_message();
String linkId = smsdetails.get_linkid();
}
However i now want to retrieve the values individually per row,from
another class in the program
You need to pass the arraylist to the another class and iterate over it there to get the individual elements. The idea is to use a common araylist - to store the values from the resultset and in another class to iterate through them.
Related
am developing a java application and I want to populate a ComboBox with First name and Last name from a table in database. how can I concatenate the two columns to display as one Full Name
this is my code. I will greatly appreciate for any assistance.
private void fillcombo(){
try{
conn = DriverManager.getConnection(url, user, password);
String sql = "select * From Member_Reg" ;
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
while(rs.next()){
String name = rs.getString("First_name+""+Last_name");
jComboBoxMembername.addItem(name);
}
}catch(Exception ex){
JOptionPane.showMessageDialog(null,ex);
}
}
Get two Strings out of the ResultSet and concatenate them in your Java code.
String name = rs.getString("First_name") + " " + rs.getString("Last_name");
It'd also be a really good idea to break that method up into multiple different ones - database access should be done in a different place to UI generation.
At a minimum this should be a method constructing your jComboBoxMembername variable (which seems to be global in your code at the moment, and it almost certainly shouldn't be), and that method should call a different method that retrieves the name from the database. So one method responsible for constructing the UI, and one method responsible for accessing the database. As your application gets bigger you'll want to separate them into different classes as well - a presentation class (or classes) and a database access class (or classes).
Replace the first line inside the while loop with the following line:
String name = rs.getString("First_name") + " " + rs.getString("Last_name");
public static getset getdata(){
getset gs=new getset();
byte img[]=null;
ServletOutputStream sos=null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","admin");
PreparedStatement stmt=con.prepareStatement("select * from emp");
ResultSet rs=stmt.executeQuery();
while(rs.next()){
gs.setId(rs.getInt(1));
gs.setName(rs.getString(2));
gs.setCountry(rs.getString(3));
gs.setImg(rs.getBytes(4));
}
}catch(Exception e){System.out.print(e);}
return gs;
}
NewClass nc=new NewClass();
getset a=nc.getdata();
out.println(a.getId());
out.println(a.getName());
out.println(a.getCountry());
out.println("<img src="+a.getImg()+" width=300 height=300></img>");
above is my code for retriving data form database
when i rum the code it show me only one data i.e the last data from database
and when i use (if condition ) it shows me first column data why? i cannot understand while i searched but did not found any solution .
getset is the class for getter and setter.
You are creating only one object , and in the while loop overwriting it every time instead of creating a new object.
getset gs=new getset();
You should create a new object in the while loop every time, set the values and then add the object to a list for example. Then iterate and print that list to test how it goes.
So, this should be the first statement in the loop gs=new getset(); (if you have gs declared outside of the loop and set to null) and then add gs to a list at the end of the loop (inside, not outside).
You are setting/saving only one object inside while/if,
When using if, you are entering at the first time only
When entering while loop, you are overriding values until the last data update.
For getting multiple values add data to List for example
I have created web service in JAVA Netbeans and called MySQL data through rest web service.
Edited code:
For loop shows all areas in sorting order then why as json output all data are not displayed in ascending order???
my method is as follows :
#GET
#Path("/ShowAreasDup")
#Produces(MediaType.APPLICATION_JSON)
public List<EntityAreas> ShowAreasDup(){
ArrayList<EntityAreas> listSort;
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection(DB_URL,USER,PASSWORD);
String query = "SELECT * FROM Areas ORDER BY AreaName";
Statement statement = conn.createStatement();
ResultSet resultset = statement.executeQuery(query);
// iterate through the java resultset
while (resultset.next())
{
int id = resultset.getInt("AreaID");
String restroName = resultset.getString("AreaName");
EntityAreas anames=new EntityAreas();
anames.setAreaid(id);
anames.setAreaname(restroName);
ShowentityAreas.put(id, anames);
}
statement.close();
}
catch(HeadlessException | SQLException |ClassNotFoundException ee)
{
JOptionPane.showMessageDialog(null, ee);
}
listSort=new ArrayList<EntityAreas>(ShowentityAreas.values());
Collections.sort(listSort,new Comparator<EntityAreas>(){
#Override
public int compare(EntityAreas o1, EntityAreas o2) {
return o1.getAreaname().compareTo(o2.getAreaname());
}
});
for(EntityAreas entityarea:listSort){
System.out.println(entityarea);
}
return listSort;
}
thank you in advance for help
Edit :
Above code is works perfectly for me
thanks to all for giving me a direction to the answser :)
Given your code, there could be some hypothesis. The most probable is that ShowAreas stores the information in an non ordered data structure (for example an HashMap).
If you want to maintain your values in order , you have to use some additional data structure. For example, you can use a TreeSet for the values.
Another solution could be to sort the values immediatly before returning them (javadoc),
// Get the elements
List<Areas> areas = new ArrayList<Areas>(ShowAreas.values());
// Sort them
Collections.sort(areas);
// Return them
return areas;
Pay attention: if you want to use this method, the class Areas must implement Comparable.
A last advise: don't put the code that interacts with the database in the class that has the responsibility to receive external REST calls. You violates the single responsibility principle and your application will become unmaintainable very quickly. Try to use a structure Controller - Service - Repository.
What I am trying to do is retrieve an ArrayList from another database manager class. Unfortunately all I can do because the manager class cannot work statically is create an instance in another class, then call the method. Then I got myself into passing that same instance into the method which asked for an SQLiteDatabase object. Now I've worked myself into a bind of confusion, when all I really want is to do is retrieve the arraylist to display a listview of elements from an SQL column.
EDIT: My post lacked clarity, so I'll try to specify exactly what is going wrong and what I am trying to accomplish here:
In a display (output) activity, I am trying to use a ListView to display elements contained in an SQL database. Currently, I am only focusing on one column (Assignment Names). My approach involved using a get method built into the database manager class, but because you cannot reference that method statically, I tried to use the method by creating an instance of that manager class. This would return an ArrayList of Inputted objects (each containing a name). It seemed to have worked, but when running the program, the LogCat protested that I was calling getDatabase recursively. After looking online, people recommended that I fix the issue by changing the method to ask for (SQLiteDatabase db) as parameters so the same database gets tossed around in the manager. Now I get confused here-- I'm not sure what to pass into this method from the display activity. It also doesn't help that from what I've heard from the comments, my get method doesn't traverse the SQL database properly. If you can solve this puzzle THANK YOU!
I'll post my code for diagnosis, hopefully an outside view will show exactly what's wrong with everything I'm trying here.
public Cursor getAssignmentNames(SQLiteDatabase db) {
return db.query(false, ASSIGNMENT_TABLE, COLUMN_TITLES,
" WHERE " + ASSIGNMENT_NAME + " ", null, null, null, " ORDER BY "+ASSIGNMENT_URGENCY_RATING, null);
}
/
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
while (!cursorsAreAfterLast(names) ) {
int go = 0;
assList.add(new Inputted(names.getString(go))
names.moveToNext();
go++;
}
return assList;
}
/
DBRecordsLayer assignmentRecords = new DBRecordsLayer(this,
"assignment.db", null, 1);
ArrayList<Inputted> assList = DBRecordsLayer.getListOfAssignments(assignmentRecords);
Your code is a bit confusing... In each iteration of the while loop, you are incrementing the cursor (names.moveToNext()); You are also incrementing go.
The result would be:
1st iteration: You are taking the data from the first column of the first query
2nd iteration: You are taking the data from the second column of the second query
etc...
I'm assume that you want to be reading data from the same column of the database for each iteration.
try this:
public ArrayList<Inputted> getListOfAssignments (SQLiteDatabase db) {
Cursor names = getAssignmentNames(db);
ArrayList<Inputted> assList = new ArrayList<Inputted>();
names.moveToFirst();
columnContainingStringToSendToInputtedConstructor = x; //replace the x with column you need from your table
while (!names.isAfterLast()) {
assList.add(new Inputted(names.getString(columnContainingStringToSendToInputtedConstructor));
names.moveToNext();
}
}
I have the following code in java:
try {
SessionFactory sessionFactory=new Configuration().configure().buildSessionFactory();
session=sessionFactory.openSession();
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
List userList=userQuery.list();
for(int i=0;i<userList.size();i++){
System.out.println(userList.get(i));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
finally{
session.flush();
session.close();
}
I am trying to display the result of the query but only the object is displayed. Can you suggest me the way to display the contents of the objects. Currently i am getting result like:
[Ljava.lang.Object;#64bef361
for (Object o : userList) {
Object[] row = (Object[]) o;
System.out.println(Arrays.toString(row));
}
But you should probably use a debugger instead of cluttering your code with such loops.
whenever you try to print any object reference, it's toString() method is called. Now, suppose your userList is of type User. You have not overridden toString() method in your User class. So, what's happening currently is toString() method of object class is called.The Object class has implemented this method in such a way that it prints it's fully qualified package name and it's hashcode.
So, simply override this toString() method in your User class and it will start printing entire data as you have configured in this method. You can manually override this method, or if you have an IDE line netbeans or eclipse, just right click anywhere in the java file and select generate ToString method.
In Java, good programming practice is to override Object.toString() So that you avoid this problem. If you want more meaningful output then what you are getting, then adhere to the standards that are encouraged by the API.refer to the documentation when in doubt
I figured out the problem. I did not know the result of the query joining more than one tables will store the result as array of Objects class.
Query userQuery=session.createQuery("select u.userId, u.username,p.profileContent from User as u inner join u.profiles as p");//, p.profileContent
Iterator ite = userQuery.list().iterator();
while ( ite.hasNext() ) {
Object[] pair = (Object[]) ite.next();
Integer user = (Integer) pair[0];
String userName=(String) pair[1];
String profileContent=(String) pair[2];
System.out.println(user+" "+userName+" "+profileContent);
}