Fetch array of strings from ArrayList for JList Java - java

the task which I do is quite simple, but I faced one problem with JList component.
What i need is. I fetch data from DataBase, load it to String array, pack array into ArrayList (just because I duno how many records I have), return it from method as ArrayList.
Now at receiver side. I have a trouble, I cant fetch String array from ArrayList so that I can pass to JList.
Here is the code.
ArrayList<Object> fetch = new ArrayList<Object>();
public String[] data =new String[10];
listModel = new DefaultListModel();
myList = new JList(listModel);
//myList = new JList(data);
// So it works with simple array of strings.
fetch=DAO.loadPasswords();
//At this point it asks me to cast an object to smth which late cause null pointer exception.
myList = new JList(fetch.get(0));
And here is loadPasswords();
public static ArrayList<Object> loadPasswords(){
dbConnect();
boolean unswer = false;
String[] result=null;
String query1 = "select * from tblPasswordsStorage where "
+ "_user_id = ?";
String userId=Personal_Organizer.userProfile.getUserID();
ArrayList<Object> params = new ArrayList<Object>();
params.add(userId);
executeQueryP(query1, params);
ArrayList<Object> fetched=null;
try {
if (rs.next()) {
unswer = true;
//Personal_Organizer.userProfile.setUserID(rs.getString(1));
result[0]=rs.getString(1);
result[1]=rs.getString(2);
result[2]=rs.getString(3);
result[3]=rs.getString(4);
result[4]=rs.getString(5);
result[5]=rs.getString(6);
result[6]=rs.getString(7);
result[7]=rs.getString(8);
result[8]=rs.getString(9);
result[9]=rs.getString(10);
fetched.add(result);
}
if (unswer) {
while (rs.next()) {
Tools.print(rs.getString(1));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null,
"SQL Server connection issue.\n"
+ "Please, check Server address, user name and password.",
"Output",
JOptionPane.PLAIN_MESSAGE);
}
dbClose();
return fetched;
}
I tried to use multidimensional array but still JList require single dimensional array.

Either use a DefaultListModel and load it with your Strings using a simple for or for-each loop that loops through your ArrayList, adding each String item in the ArrayList into the model, or create your own ListModel class, one that extends AbstractListModel and that uses the ArrayList as its data nucleus.
Edit, since your data is held in an ArrayList of arrays, then perhaps you don't want to display it within an ArrayList after all, but rather in a JTable. Here your best bet would be to create your own TableModel, one based off of AbstractTableModel and that uses your ArrayList as its data nucleus. Also, perhaps better than loading your data into an array would be to create a custom class to hold each row of data from the ResultSet.
You state:
My problem is to simply load something to JList. The idea is to display application/website name in the list, then when you click on it, you get full data which contains in array. That's why I put fetch.get(0)...because. I need at least something.
Then
Create a custom class to hold each row of data.
Create items of this class from each row of the ResultSet
Fill your DefaultListModel with items of this class
Give your JList a custom ListCellRenderer, one that display's the application/website name
Then you can display the name and still have each list item hold all the pertinent information that it needs.

Related

Populating JComboBox using an MultiDimensional Array List

I have been trying to populate a Eclipse GUI Java JComboBox using an Array list using constructors without any luck. This is what I have tried thus far.
import item.Item;
import javax.swing.JComboBox;
import java.util.ArrayList;
public class SelectionScreen{
private JFrame frame;
static ArrayList< Item> list;
private String items;
public static void main (String[] args){
initialize();
}
public void initialize(){
list = new ArrayList< Item >();
list.add(new Item("Strawberry,200,.25,.75);
list.add(new Item("Banana,200,.25,1.00);
list.add(new Item("Oranges,200,.25,2.00);
JcomboBox comboBox = newJcomboBox();
ComboBox.setBounds(63,29,86,22)
frame.getContentPane().add(comboBox);
// here is where I tried to fill the combobox
//comboBox.setModel(new DefaultComboBoxModel(Item.getName()))); //Wrong
//comboBox.setModel(Item.getName); //Wrong
//the following only loads the last item in the list which is Oranges
for(Item i: list{
comboBox.setModel(new DefaultComboBoxModel(New String[] {
i.getName()}));
}
// tried making a different list to collect my fruits.
for(Item i: list){
list2[ i.getName()];
Item.length;
} //which was a complete fail.
I am at complete lost here and not very experienced with Java. I can load the items just fine using
comboBox.setModel(new DefaultComboBoxModel(new String[]{ "Strawberry","Banana","Oranges"}));
but I won't know what fruits are in the list when I import them from a text file.
Any help would be appreciated.
/*The following only loads the last item in the list which is Oranges.*/
for(Item i: list)
{
comboBox.setModel(new DefaultComboBoxModel(new String[] {
i.getName()}));
}
Don't keep creating a new ComboBoxModel inside the loop. You can't add more than one item to the model if you keep creating a new model. So you only see the last model created with the single item added to it. If you want to use this approach then you would create the model OUTSIDE of the loop and then just add items the model INSIDE the loop.
Actually you don't event need to create a combo box model. You can just add items directly to the combo box:
Something like:
for(Item i: list
{
comboBox.addItem( i.getName() );
}
Another option is to add the Item object directly to the combo box. Then you can use a custom renderer to control which property of the Item object is display in the combo box. Check out Combo Box With Custom Renderer for more information on this approach.
If you wish to show Item objects in a combobox then you should declare the JComboBox to store Item objects. That way you can easily add items without having to do any mucking around with models at all:
JComboBox<Item> itemsCombo = new JComboBox<>();
list.forEach(itemsCombo::add);
The value displayed in the combobox will be whatever is returned by Item.toString. If that's not what you want (because your toString returns a more complete description of the object - generally considered better practice) then it is fairly easy to write your own Custom Renderer.
The only hackish downside of the JComboBox API is that you've got to cast the selected item:
Item selectedItem = (Item)itemsCombo.getSelectedItem();
This is ugly and I wish the API didn't require it but it's a small price to pay to avoid having to define your own model.
You can, in fact, avoid the cast by:
Item selectedItem = itemsCombo.getItemAt(itemsCombo.getSelectedIndex());
But that's just about as ugly.
As an aside, this is one of several areas in which the standard Java tutorial and samples are quite out of date so there's no blame here at all for not knowing to use generics.

ParseQuery: convert from list of prices in database to strings android

​Hi All,
I am trying to build a scrolling custom listview that displays a list of products ordered by Price ascending. However I just realized I was storing the prices as strings which means $1000.00 comes before $2.01 because it is a character and not a number. I have converted my data to a "Number" on Parse and believe the best type to retrieve it is a double (can anyone comment on that for dollar amounts). The problem is I need to keep it as a number convert it to a string and then pass it to the listview for display on a text field. Initially i had
PPI.setProductprice((String) product.get("Price"));
like this:
// Locate the class table named "Products" in Parse.com
ParseQuery<ParseObject> query = new ParseQuery<ParseObject>(
"Products");
// Locate the column named "Price" in Parse.com and order list
// by ascending
query.orderByAscending("Price");
ob = query.find();
for (ParseObject product : ob) {
// Locate images in PrimaryPhoto column
ParseFile productimage = (ParseFile) product.get("PrimaryPhoto");
ProductPopulation PPI = new ProductPopulation();
PPI.setProductname((String) product.get("Name"));
PPI.setProductbrand((String) product.get("Brand"));
PPI.setProductprice((String) product.get("Price"));
PPI.setProductimage(productimage.getUrl());
productpopulationlist.add(PPI);
I then tried putting it into an array of doubles an iterating through it to convert to strings.
My last attempt which probably doesn't make sense was to change it like this:
PPI.setProductprice((Double) product.getDouble("Price"));
I am fairly knew to Android and any help you can give me would be appreciated.
Thanks in advance.
OK so i do not get the context here but what you can do is save the price as a string and when extracting it you could call Integer.parseInt(String intvalue); on the string to convert the value back to int then you can do all operations you ought to do. you can get a disordered array from the server and arrange it at device level that will save you some time and logic.
I don't know what is the ProductPopulation class you use to populate the list, so I can not say what exactly is the best way in your case, but in general a list can be ordered by means of the Collections.sort() method (see the method documentation).
You could sort the list before you add it to your list view. To sort a list the way you need, you must provide a comparator, than obtains the required values (fields or method results) from the objects that comprise your list, compares the obtained values and returns -1, 0, or 1, depending on the comparison result.
It could look somewhat like this:
for (...) {
ItemClass newObject = new ItemClass(); // new list item
// ...here add the values to the list item...
theList.add(newObject); // add the new item to the list
}
// now sort the list before adding it to the list viewer
Collections.sort(theList, new Comparator<ItemClass>() {
#Override
public int compare(ItemClass o1, ItemClass o2) {
// obtain and compare the values you need
return Double.compare(o1.getDouble(), o1.getDouble());
// you could also do something like
// Double.compare(
// Double.parseDouble(o1.getString()),
// Double.parseDouble(o2.getString()));
// but it would be much slower
}
});
// now add the sorted list to the viewer
listViewer.setList(theList);

Java OOP Array from one class to another

I would like to create an array that holds the information (in this case the ID) and then transfer this data into a drop down list.
The below code is where the data will be inputted and where I created the array list:
Person cons_save = new Person();
cons_save.setPersonfirstname(this.jTextField1.getText());
cons_save.setPersonlastname(this.jTextField2.getText());
cons_save.setPersonID(this.jTextField3.getText());
this.jTextField1.setText("");
this.jTextField2.setText("");
this.jTextField3.setText("");
cons_save.savecons();
ArrayList<String> idList = new ArrayList<String>();
idList.add(cons_save.PersonID);
I need that every time that I input the ID and save, the id will transfer to the array and go to a combo box in another field.
The code I am trying to input in the combo box is the following:
Object[] idList = Person.getidList();
JComboBox box = new JComboBox (idList);
But this keeps issuing multiple errors. I have got this code from other questions similar to mine but it is not working

add arraylist data to JTable

i hav a ArreayList which is contain PRIvariable(name of the class) class data. Below shows my part of the java code. So now i want to put this Arraylist data to Jtable. how can i do that. Here i already added pri.dateText , pri.sum , pri.count to ar(arraylist)
PRIvariable pri=new PRIvariable();
while (reader.ready()) {
String line = reader.readLine();
String[] values = line.split(",");
if(values[2].equals(pri.incDate)){
if(values[4].equals("KI")){
pri.dateText=values[2]+" "+values[4];
pri.count=pri.count+1;
pri.sum = pri.sum+Integer.parseInt(values[7]);
}
}
}
System.out.println(pri.dateText+" "+pri.sum+" "+pri.count);
ar.add(pri);
Like all Swing components, a JTable relies upon the MVC pattern (at multiple levels, but that's not the subject).
You have one view (the JTable), one model (I'll come back on it later), and a controller (implemented here as a set of event listeners : one controller for each kind of control).
The array you have could be a good model starting point. However, Swing provides far better way to inject your data in JTable. Indeed, a JTable uses as model an implementation of TableModel. Hopefully, there already exist an implementation : DefaultTableModel.
So, here is what I suggest to you : create DefaultTableModel, put in its rows/columns all the data you want to display in your table, then call JTable#setModel(TableModel) to have thze table display your data.
Obviously, you'll soon find various misfits between DefaultTableModel and what you want to do. It will then be time for you to create our very own table model. But that's another question.
Besides, don't forget to take a look at Swing tutorial, it's usually a good thing when dealing with Swing components.
I don't see where you have an ArrayList anywhere.
First you create a PRIvariable object. Then you keep looping as you read a line of data from the file. For each line of data you split it into individual tokens and then add some of the token data to the PRIvariable ojbect. The problem is that you only have a single PRIVariable object. So every time you read a new line of data you change the values of the PRIvariable object. After all the looping you add this single PRIvariable object to your ArrayList, but you will only ever have one object in the ArrayList.
The easier solution is to update the TableModel as you get the data. Something like:
DefaultTableModel model = new DefaultTableModel(...);
JTable table = new JTable( model );
...
...
while (reader.ready())
{
String line = reader.readLine();
String[] values = line.split(",");
String[] row = new String[3];
row[0] = values[?];
row[1] = values[?];
row[2] = values[?];
model.addRow( row );
}
Look into GlazedLists. They make it extremely easy to create a suitable TableModel object from your list.
ArrayList< PRIvariable> myList = new ArrayList<PRIvariable>();
... fill up the list ...
// This assumes your object has a getName() and getAge() methods
String[] propertyNames = {"name","age"};
String[] columnLabels = {"Name","Age"};
// Are these columns editable?
boolean[] writeable = {false, false};
EventList<PRIvariable> eventList = GlazedLists.eventList(myList);
EventTableModel<PRIvariable> tableModel = new EventTableModel<PRIvariable>(eventList,propertyNames,columnLabels,writable);
JTable table = new JTable(tableModel);

How we get the List objects in backward direction?

Hi i am getting List object that contains pojo class objects of the table. in my case i have to show the table data in reverse order. mean that, for ex
i am adding some rows to particular table in database when i am added recently, the data is storing at last row in table(in database). here i have to show whole content of the table in my jsp page in reverse order, mean that what i inserted recently have to display first row in my jsp page.
here my code was like,
List lst = tabledate.getAllData();//return List<Table> Object
Iterator it = lst.iterator();
MyTable mt = new MyTable();//pojo class
while(it.hasNext())
{
mt=(MyTable)it.next();
//getting data from getters.
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
System.out.println(mt.getxxx());
}
Use a ListIterator to iterate through the list using hasPrevious() and previous():
ListIterator it = lst.listIterator(lst.size());
while(it.hasPrevious()) {
System.out.println(it.previous());
}
You cannot use an iterator in this case. You will need to use index based access:
int size = lst.size();
for (int i=size - 1; i >= 0; i --)
{
MyTable mt = (MyTable)lst.get(i);
....
}
Btw: there is no need to create a new MyTable() before the loop. This is an instance that will be thrown away immediately and serves no purpose.

Categories