Add items to jList - java

I am trying to create a method that will update a list that has already been created. Im not sure why this is not working?
It throws a null pointer exception.
This is my code:
private void UpdateJList(){
String query = "SELECT * FROM names WHERE TYA=?";
String partialSearch = "Sales";
try{
connect.pst = connect.con.prepareStatement(query);
connect.pst.setString(1, partialSearch);
connect.pst.execute();
ArrayList<String> add = new ArrayList<String>();
String[] items = {};
while (connect.rs.next()){
String result = connect.rs.getString("ACNO");
add.add(result);
int length = add.size();
DefaultListModel<String> model;
model = new DefaultListModel<String>();
for (int i=0; i<length; i++){
model.add(i, result);
}
jList1.setModel(model);
jList1.setSelectedIndex(0);
}
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Thank you in advance!!

There are 2 major problems with that code:
In the while loop, you are creating many instances of DefaultListModel. That means, for each entry of the query result, you are restarting the list.
A nullpointer exception is produced by the line: connect.rs.next() because you didn't assign connect.rs with the query's resultset.

Related

How can i get the specific data from array

My question is when i store the data into array from sqlite database, how can i get it from specific position let say, my database contain "food, drinks,snack" how can i get the string "snack" from array.
String CatNameQuery = "SELECT * FROM Category";
db = new DBController(MainActivity.this);
SQLiteDatabase db3 = db.getReadableDatabase();
final Cursor cursor2 = db3.rawQuery(CatNameQuery, null);
{
List<String> array = new ArrayList<String>();
while(cursor2.moveToNext()){
String uname = cursor2.getString(cursor2.getColumnIndex("CategoryName"));
array.add(uname);
}
You need to iterate through the list in order to find the item you are looking for.
For example:
for (String s : array) {
if (s.equals("snack")) {
System.out.println("Found snack");
}
}
You can also use the contains method to check if the list contains "snack."
if (array.contains("snack")) {
System.out.println("Found snack");
}
Resource: ArrayList
Use the WHERE clause within your SELECT query. For example:
"SELECT * FROM Category WHERE CategoryName='snacks'"
This will fill your array with only items under the category 'snacks'.
List<String> array = new ArrayList<String>();
array.add("food");
array.add("drinks");
array.add("snack");
String result="";
if (array.contains("snack")) // avoid null pointer exception
{
int index =array.indexOf("snack") //find the index of arraylist
result=array.get(index);
}
You can find it by looping the array
List<String> arrobj= new ArrayList<String>();
arrobj.add("food");
arrobj.add("drinks");
arrobj.add("snack");
for (String value : arrobj) {
if (value.equals("snack")) {
System.out.println("Here is the snack");
}
}
if (array.size() > 0) {
int index = 0;
if (array.contains("Snacks")) {
index = array.indexOf("Snacks");
System.out.println(array.get(index));
}
}

getting values from Database to JLabel

i have a table in the database of 4rows and 4columns. each column holds a different data.
now i want to retrieve all the data in the database and put them on JLabel on another form. i.e
in my Database i have.
packageName.....monthlyFee..... YearlyFee....... TotalFee
Regular......................150..................300....................450
Gold.........................300...................400..................700
..... ..... .... ....
now i have a form that i have put 4 empty JLabels in four rows but how do i retrieve the values from the database and place each value in the appropriate Label?.
This is what i've done but i still cant get around it. im stuck.
Thank you anyone.
public void getPrices()
{
String srt ="SELECT * FROM program_tbl";
try
{
con.connect();
ps = con.con.prepareStatement(srt);
rs = ps.executeQuery();
ResultSetMetaData data = rs.getMetaData();
int colums = data.getColumnCount();
while(rs.next())
{
Vector rows = new Vector();
for (int i = 1; i < colums; i++)
{
rows.addElement(rs.getObject(i));
}
.....................................................................
If you want to get this data as a string then you could probably try something like:
Vector<String> rows = new Vector<String>();
while(rs.next()) {
String rowEntry = rs.getString("packageName") +
rs.getString("monthlyFee") +
rs.getString("yearlyFee") +
rs.getString("totalFee") +
rows.add(rowEntry);
}
If not String, but an object to use later, then you can create a class:
public class MyObject {
private String packageName;
private int monthlyFee;
private int yearlyFee;
private int totalFee;
public MyObject (String name, int monthlyFee, int yearlyFee, int totalFee) {
this.packageName = name;
this.monthlyFee = monthlyFee;
this.yearlyFee = yearlyFee;
this.totalFee = totalFee;
}
/*Setters
*And
*Getters*/
}
And then use it as:
Vector<MyObject> rows = new Vector<MyObject>();
while (rs.next()) {
MyObject obj = new MyObject(rs.getString("packageName")
, rs.getInt("montlyFee")
, rs.getInt("yearlyFee")
, rs.getInt("totalFee")
);
rows.add(obj)
}
So say we now have a vector with String values - Vector<String> rows;
now i would like to create those JLabels.
JLabel[] myLabels = new JLabel[v.size()];
for(int i=0; i<rows.size(); i++) {
as[i] = new JLabel(rows.get(i));
}
And now we have an array of JLabels ready to be put to applet.
Don't use a JLabel. There is no way you can easily format the data so that you get tabular data.
Instead you should be using a JTable. Read the section from the Swing tutorial on How to Use Tables for more information. You can also search the forum for examples of using a JTable with a ResultSet.

ResultSet into generic List of Lists

I need to add a ResultSet to a list of lists. The string passed to the method is an SQL select statement. The DB connection methods work perfectly with all other methods in this class so that's not the problem here. I know I can replace some of the ArrayList declarations with List but I don't think that matters in this case.
public static ArrayList<ArrayList> selectStatement(String string) throws SQLException {
ArrayList<ArrayList> listOfLists = null;
ArrayList list;
String[] record = null;
try {
rs = null;
dBConnectionOpen();
rs = st.executeQuery(string);
ResultSetMetaData metaData = rs.getMetaData();
int columns = metaData.getColumnCount();
while (rs.next()) {
list = null;
record = new String[columns];
for (int i = 1; i < columns; i++) {
record[i - 1] = rs.getString(i);
}
list = new ArrayList(Arrays.asList(record));
listOfLists.add(list);
}
} catch (Exception e) {
} finally {
dBConnectionClose();
}
return listOfLists;
}
I have done this before, but for some reason it just won't work this time. What am I missing here?
You initialize listOfLists with null value. Try instantiating it from the beginning:
ArrayList<ArrayList> listOfLists = new ArrayList<ArrayList>();
Also, it would be better:
Use List interface instead of plain ArrayList class implementation
Use List<String> instead of raw List.
Instead of using String[] record, save the data directly in the List<String>.
Keep the variable scope as short as possible. List<String> list can be directly inside the while loop.
Knowing this, the code can change to:
List<List<String>> listOfLists = new ArrayList<List<String>>();
...
while (rs.next()) {
List<String> list = new ArrayList<String>();
for (int i = 1; i < columns; i++) {
list.add(rs.getString(i));
}
listOfLists.add(list);
}
More info:
What does it mean to "program to an interface"?

Adding multiple values form database into RichList Blackberry

I am using Blackberry Plug-in and i am using Rich Lists of blackberry.
I want to make lists appear the same number of times as there are entries in the database table.
I m using the below code but it shows only one name in list view.
I need to show all the entries in database into list view...Kindly help me..
I have already used list.add(); inside the for loop but it is showing Exception: java.lang.IllegalStateException: Field added to a manager while it is already parented.
public static void richlistshow(){
String name = null;
list = new RichList(mainManager, true, 2, 0);
Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
for (int c = 0; c < target_list.size();c++){
City tar_city = new City();
tar_city = (City)target_list.elementAt(c);
name = tar_city.get_city_name().toString();
}
//adding lists to the screen
list.add(new Object[] {delete,name,"time-date"});
}
You didn't posted full codes you are working with. But following code may help you to get rid of IllegalStateException. You were adding same BitmapField instance for every list entries, which caused the exception.
public static void richlistshow() {
final Bitmap logoBitmap = Bitmap.getBitmapResource("delete.png");
list = new RichList(mainManager, true, 2, 0);
for (int c = 0; c < target_list.size(); c++) {
// create a new BitmapField for every entry.
// An UI Field can't have more than one parent.
final BitmapField delete = new BitmapField(logoBitmap, Field.FIELD_HCENTER);
City tar_city = (City) target_list.elementAt(c);
final String name = tar_city.get_city_name().toString();
// add to list
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
list.add(new Object[] { delete, name, "time-date" });
}
});
}
}

Variable g may not have been initialized

I have many questions about this project that I'm working on. It's a virtual database for films. I have a small MovieEntry class (to process individual entries) and a large MovieDatabase class that keeps track of all 10k+ entries. In my second searchYear method as well as subsequent methods I get the error "variable g (or d or whatever) might not have been initialized."
I also get a pop-up error that says Warnings from last compilation: unreachable catch clause. thrown type java.io.FileNotFoundException has already been caught. I'm positively stumped on both. Here's the code:
public class MovieDatabase
{
private ArrayList<MovieEntry> Database = new ArrayList<MovieEntry>();
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
public int countTitles() throws IOException{
Scanner fileScan;
fileScan = new Scanner (new File("movies.txt"));
int count = 0;
String movieCount;
while(fileScan.hasNext()){
movieCount = fileScan.nextLine();
count++;
}
return count;
}
public void addMovie(MovieEntry m){
Database.add(m);
}
public ArrayList<MovieEntry> searchTitle(String substring){
for (MovieEntry title : Database)
System.out.println(title);
return null;
}
public ArrayList<MovieEntry> searchGenre(String substring){
for (MovieEntry genre : Database)
System.out.println(genre);
return null;
}
public ArrayList<MovieEntry> searchDirector (String str){
for (MovieEntry director : Database)
System.out.println(director);
return null;
}
public ArrayList<String> searchYear (int yr){
ArrayList <String> yearMatches = new ArrayList<String>();
for (MovieEntry m : Database)
m.getYear(yr);
if(yearMatches.contains(yr) == false){
String sYr = Integer.toString(yr);
yearMatches.add(sYr);
}
return yearMatches;
}
public ArrayList<MovieEntry> searchYear(int from, int to){
ArrayList <String> Matches = new ArrayList<String>();
for(MovieEntry m : Database);
m.getYear();
Matches.add();
return Matches;
}
public void readMovieData(String movies){
String info;
try{
Scanner fileReader = new Scanner(new File("movies"));
Scanner lineReader;
while(fileReader.hasNext()){
info = fileReader.nextLine();
lineReader = new Scanner(info);
lineReader.useDelimiter(":");
String title = lineReader.next();
String director = lineReader.next();
String genre = lineReader.next();
int year = lineReader.nextInt();
}
}catch(FileNotFoundException error){
System.out.println("File not found.");
}catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
}
public int countGenres(){
ArrayList <String> gList = new ArrayList<String>();
for(MovieEntry m : Database){
String g = m.getGenre(g);
if(gList.contains(g) == false){
gList.add(g);
}
return gList.size();
}
}
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d);
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
}
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
}
catch(IOException error){
System.out.println("Oops! Something went wrong.");
}
Its telling you that the FileNotFoundException will deal with what the IOException is catching, so the IOException becomes unreachable as in it will never catch an IO exceltion, why just not catch an Exception instead
As for the initialization
public int countDirectors(){
ArrayList <String> dList = new ArrayList<String>();
for(MovieEntry m : Database){
String d = m.getDirector(d); //THIS LINE
if(dList.contains(d) == false){
dList.add(d);
}
return dList.size();
}
The line String d = m.getDirector(d); might be the problem, d wont be initialised unless there is something in the MovieEntry and as far as i can see there will never be anything because you are initialising it to an empty array list
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
Maybe you should be passing a array of movies to the constructor and then add these movies to the Database variable ?
Seems like there are a number of issues with this code.
What parameter does MovieEntry.getGenre() expect? You may not use g in that case because it has not been defined yet.
The exception issue you mentioned means that the exception was already caught, or possibly never thrown. I believe that in this case the IOException is never thrown out from the code within the try block.
There are a number of methods that are supposed to return a value but do not, example:
public String listGenres(){
ArrayList <String> genreList = new ArrayList<String>();
}
Also, it is a java naming convention to use lower case first characters (camel case) for values:
private ArrayList<MovieEntry> database = new ArrayList<MovieEntry>();
Oh, and do you need to re-initialize the database variable in the constructor?:
public MovieDatabase(){
ArrayList<MovieDatabase> Database = new ArrayList<MovieDatabase>(0);
}
Hope this is helpful.

Categories