How to show a arraylist of string on jlabel? - java

Hi I have an arraylist of strings, I want to show the content of the arraylist on JLabel separated by a space or comma. But it shows me only one String, the last one.
public void ShowMovie(int idMovie) throws SQLException, IOException {
int ID = idMovie;
String IDMOVIE = Integer.toString(ID);
IDMovieLabel.setText(IDMOVIE);
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(Cover.class.getName()).log(Level.SEVERE, null, ex);
}
con = DriverManager.getConnection("jdbc:mysql://localhost/whichmovie", "Asis", "dekrayat24");
String sql = "SELECT Title,Year,Country,recomendacion,Cover,Rating,NameDirec,Name FROM movie "
+ "Inner join direction on (movie.idMovie=direction.idMovie5)"
+ "Inner join director on (direction.idDirector=director.idDirector)"
+ "Inner join cast on (movie.idMovie=cast.idMovie4)"
+ "Inner join actor on (cast.idActor=actor.idActor)"
+ "where idMovie= '" + ID + "'";
st = con.prepareStatement(sql);
rs = st.executeQuery(sql);
while (rs.next()) {
String titulo = rs.getString(1);
int añoInt = rs.getInt(2);
String año = Integer.toString(añoInt);
byte[] imagedataCover = rs.getBytes("Country");
byte[] imagedataCover1 = rs.getBytes("Cover");
format = new ImageIcon(imagedataCover);
format2 = new ImageIcon(imagedataCover1);
TituloLabel.setText(titulo);
AñoLabel.setText(año);
CountryLabel.setIcon(format);
DirectorLabel.setText(rs.getString(7));
int Recomend = rs.getInt(4);
String Recom = Integer.toString(Recomend);
RecommendLabel.setText(Recom);
int Rating = rs.getInt(6);
String Rat = Integer.toString(Rating);
RatingLabel.setText(Rat);
starRater1.setSelection(Rating);
starRater1.setEnabled(false);
Image imgEscalada = format2.getImage().getScaledInstance(CoverLabel.getWidth(),
CoverLabel.getHeight(), Image.SCALE_SMOOTH);
Icon iconoEscalado = new ImageIcon(imgEscalada);
CoverLabel.setIcon(iconoEscalado);
ArrayList<String> actors = new ArrayList<>();
actors.add(rs.getString(8));
System.out.println(actors);// Here i can see i get 9 actors.
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first) {
sb.append(' ');
}
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
}
rs.close();
st.close();
con.close();
}
Any help ?
Edit:unfortunately no solution has helped me, maybe I'm doing something wrong in the method, I post the full method.

String text = "";
for(int i = 0; i < actors.size(); i++){
text = text + actors.get(i);
if(i < actors.size() - 2){
text = text + ", ";
}
}
CastLabel1.setText(text);

The problem is you are resetting the label for each step in the for loop, and not creating a cumulative result. See below:
StringBuilder buf = new StringBuilder();
for(int i = 0; i < actors.size(); i++){
buf.append(actors.get(i));
if(i < actors.size() -1){
buf.append(" ");
}
}
CastLabel1.setText(buf.toString())

You should build the string you want to show first then set it to the text of the label:
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String s : actors) {
if (!first)
sb.append(' ');
sb.append(s);
first = false;
}
CastLabel1.setText(sb.toString());
What you're currently doing is changing the entire label text during each iteration, so the final text is that of the last element in the list.

Related

How getSet of Text from row in cassandra

I have a table with < frozen < set < text > > > , column. I can't understand how I may read a column value from a row.Trying below but not able to get pass through.
else if (key.getType() == DataType.frozenSet(text))
{
str = row.getSet( , )
}
I tried the below , but i see nothing is printing out from that frozen set column.
public static void main(String[] args) throws FileNotFoundException {
long startTime = System.currentTimeMillis();
PrintWriter pw = new PrintWriter(new File("test.csv"));
String keyspace = "xxxxx";
String table = "xxxxxx";
String username = "xxxx";
String password = "xxxx";
String host = "xxxxxxx";
double count = 0;
Cluster.Builder clusterBuilder = Cluster.builder()
.addContactPoints(host)
.withCredentials(username, password);
Cluster cluster = clusterBuilder.build();
Session session = cluster.connect(keyspace);
Statement stmt = new SimpleStatement("SELECT * FROM " + table);
stmt.setFetchSize(2000);
ResultSet rs = session.execute(stmt);
Iterator<Row> iter = rs.iterator();
while ( !rs.isFullyFetched()) {
if (rs.getAvailableWithoutFetching() == 120 )
rs.fetchMoreResults();
Row row = iter.next();
if ( rs != null )
{
StringBuilder line = new StringBuilder();
for (Definition key : row.getColumnDefinitions().asList())
{
String val = myGetValue(key, row);
line.append("\"");
line.append(val);
line.append("\"");
line.append(',');
}
line.deleteCharAt(line.length()-1);
line.append('\n');
pw.write(line.toString());
System.out.println(line.toString());
++count;
}
}
pw.close();
session.close();
cluster.close();
System.out.println(count + "\t rows copied into csv");
long endTime = System.currentTimeMillis();
System.out.println("Took "+(endTime - startTime) + " ms");
}
public static String myGetValue(Definition key, Row row)
{
String str = "";
if (key != null)
{
String col = key.getName();
try
{
if (key.getType() == DataType.cdouble())
{
str = new Double(row.getDouble(col)).toString();
}
else if (key.getType() == DataType.cint())
{
str = new Integer(row.getInt(col)).toString();
}
else if (key.getType() == DataType.uuid())
{
str = row.getUUID(col).toString();
}
else if (key.getType() == DataType.cfloat())
{
str = new Float(row.getFloat(col)).toString();
}
else if (key.getType() == DataType.timestamp())
{
str = row.getDate(col).toString();
SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ssZ");
str = fmt.format(row.getDate(col));
}
else if (key.getType().equals(DataType.set(DataType.text()) ))
{
Set<String> st1 = row.getSet(i, String.class);
str = st1.toString();
++i;
}
else
{
str = row.getString(col);
}
} catch (Exception e)
{
str = "";
}
}
return str;
}
}
schema:
create table view_page_details(
clickid uuid,
view text,
clickin int,
names frozen <set<text>>,
msg_view text,
number_of_times int,
primary key ((clickid, view, clickin), names);
cqlsh output for that specific 'names' column in that table:
| {').'{'2', 'STOP', 'williams', 'The', 'appts:', 'at', 'family''s', 'first', 'of', 'one', 'reminder', 'starts', 'to', 'your'}
| {'2'{'2', 'STOP', 'shane', 'The', 'appts:', 'at', 'family''s', 'first', 'of'}
| {'1', '2/1/15.'{'2', 'STOP', 'brete', 'The', 'appts:', 'at', 'family''s', 'first', 'of', 'one', 'reminder', 'starts', 'to', 'your'}
My program output for that specific 'names'column in that table:
,,
,,
,,
,,
From what i observed by debugging line by line , String val = myGetValue(key, row); gets the entire row value correctly from cluster, when returns value from that function its not giving out the specified column value. Not sure if something wrong inside the function logic for that specific column.
The first argument is index of the column in the ResultSet.
By accessing this way you need to get get columns by their index not by name or key.
Set<String> mySet = row.getSet(index, String.class);
If you don't have the index, then you will need keep a counter as you iterate the keys.
You can find out more from the javadoc
https://docs.datastax.com/en/latest-java-driver-api/com/datastax/driver/core/GettableByIndexData.html#getSet-int-java.lang.Class-
longer answer:
I'm really guessing what most of your code does, but with the given schema I can output the set using this code:
Row row = rs.one();
String str = "";
int i = 0;
Iterator<ColumnDefinitions.Definition> it = rs.getColumnDefinitions().iterator();
while (it.hasNext()) {
ColumnDefinitions.Definition key = it.next();
if (key.getType().equals(DataType.set(DataType.varchar()))) {
Set<String> st1 = row.getSet(i, String.class);
str = st1.toString();
System.out.println(str);
}
i++;
}

remove last word continuously and check in database table java

i have a small translation program to develop. The user input a sentence and the sentence is then check in a table in my database. if the sentence to sentence match is found. it displays the result else it removes the last word of the sentence and rechecks until a match is found or until one word is left( to be developed) . i have a small implementation for the handling of sentence to sentence match but i am having a small problem with my loop. i cannot figure out out to make it work. I know the problem is the the else part of loop i cannot figure out how to do it. I am not sure if the compiler will even loop back for the truncated sentence.
String sentence = "i am a good boy";
for(int j=0;j<sentence.length();j++)
{
if(sentence.length()>1)
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
else
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
}
}
public String lookUpSentencePart(String sentence)
{
sentence = sentence.substring(0, sentence.lastIndexOf(" "));
return sentence;
}
public ResultSet sentenceDBQuery(String sentence, String source, String target)
{
ResultSet rs = null;
Statement stmt;
myConnection db = new myConnection();
try
{
Connection myConn = db.theconnect();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + target + " from sentence WHERE " + source + " = '" + sentence+"'");
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
Probably you need smth like that :) You still need to add some boundary checks
String[] sentence = "i am a good boy".split(" ");
for(int j=0;j<sentence.length;j++)
{
String realSentence = buildSentence(sentence, j);
rs2 = sentenceDBQuery(realSentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
public String buildSentence(String[] parts, int index) {
StringBuilder result = new StringBuilder();
for (int j = 0; j < (parts.length - index); j++) {
sb.append(parts[j]).append(" ");
}
sb.setLength(sb.length() - 1);
return result.toString();
}

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException UNKNOWN COLUMN

I am currently trying to scan and parse the file that is not in sql format. I am trying to input all the data into the SQL table but for some reason every time i run the program, i get the error saying unknown column 'what' in 'field list.' So the neither of the data goes through. 'what' is one of the names that is on the text. The table currently has 11 columns. I know I am parsing or scanning it wrong but I cannot figure out where. Here is my code:
public class parseTable {
public parseTable (String name) throws FileNotFoundException
{
File file = new File(name);
parse(file);
}
private void parse(File file) throws FileNotFoundException
{
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/";
String connectionUser = "";
String connectionPassword = "";
conn = DriverManager.getConnection(connectionUrl, connectionUser, connectionPassword);
stmt = conn.createStatement();
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
String query = "";
for(int i = 0; i < rowInfo.length; i++)
{
if(query.equals(""))
{
query = rowInfo[i];
}
else if(i == 9){
query = query + "," + rowInfo[i];
}
else if(rowInfo[i].equals(null)){
query = query + ", " + "NULL";
}
else
query = query + ", " + "'" + rowInfo[i] + "'";
}
stmt.executeUpdate("INSERT INTO dup VALUES(" + query + ")");
count = 0;
rowInfo = new String[11];
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (stmt != null) stmt.close(); } catch (SQLException e) { e.printStackTrace(); }
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
}
And this is the data I'm trying to input:
1 hello cheese 1111 what#yahoo.com user adm street zip what USA
2 Alex cheese 1111 what#yahoo.com user adm street zip what USA
So this is my new code now, using PrepareStatement. However I still get an error and I looked online for the solution on where I'm making a mistake, but I cant seem to figure out where.
String query = "INSERT INTO mil_table (UserName, NameFirst, NameLast, supportID, EmailAddress, Password,
IDQ, AddressCity, AddressState, AddressZip, AddressCountry) VALUES(?,?,?,?,?,?,?,?,?,?,?)";
pstmt = conn.prepareStatement(query);
Scanner scan = new Scanner(file);
String[] rowInfo = new String[11];
int count = 0;
while(scan.hasNextLine()){
//String data = scan.nextLine();
Scanner lineScan = new Scanner(scan.nextLine());
while(lineScan.hasNext()){
String words = lineScan.next();
if(count < 11){
rowInfo[count] = words;
count++;
}
else if(count == 11 && words.equals("States")){
rowInfo[count - 1] = rowInfo[count - 1] + " " + words;
}
else{
for(int i = 0; i <rowInfo.length; i++)
{
pstmt.setString(i + 1, rowInfo[i]);
}
//stmt.executeUpdate("INSERT INTO mil_table VALUES(" + query + ")");
//System.out.println("#" + query + "#");
pstmt.executeUpdate();
count = 0;
rowInfo = new String[11];
}
}
As you are using MySQL, you will need to enclose the text inputs with quotes. Try enclosing the String values that you are inserting in quotes and then execute your code.

How to Make a cursor Type scroll insensitive in jdbc usin sqlite

Hey im attempting to to make an invoice program that uses Java and Sqlite as a database. I know that sqlite is a forward only language, but is there a way to scroll backwards or make it type scroll insensitive here is the class that im trying to use. I am attempting to put all of my information extracted from my database into an array.
public String[] getRow(int rowID)
{
String id =("");
String name = ("");
String day = ("");
String location = ("");
String price = ("");
String timestart= ("");
String Timeend = ("");
String Showtype = ("");
String[] row= new String[8];
try
{
Class.forName("org.sqlite.JDBC");
Connection x=DriverManager.getConnection("jdbc:sqlite:test.db");
Statement stmt = x.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery ("SELECT ID, NAME, day, Location, price, timestart, Timeend, Showtype FROM Showinformation ORDER BY ID LIMIT 5 OFFSET:index;");
rs.step(rowID);
while(rs.next())
{
for(int i=0; i<8; i++)
{
id = rs.getString("ID");
row[0]=id;
name = rs.getString("NAME");
row[1]=name;
day = rs.getString("day");
row[2]=day;
location = rs.getString("Location");
row[3]=location;
price = rs.getString("price");
row[4]=price;
timestart= rs.getString("timestart");
row[5]=timestart;
Timeend= rs.getString("Timeend");
row[6]=Timeend;
Showtype= rs.getString("Showtype");
row[7]=Showtype;
}
//String potato =(i+1+id+""+name+""+day+""+location+""+price+""+timestart+""+Timeend+""+Showtype);
//System.out.println("ID = " + id +"\nNAME = " + name+"\nDAY = " + day+"\nADDRESS = " + location+"\nPRICE = " + price+"\nTIME START = " + timestart+"\nTIME END = " + Timeend+"\nSHOWTYPE = " + Showtype );
}
}
catch(Exception er)
{
System.err.println(er.getClass().getName()+":"+er.getMessage() );
}
return row;
}
any help would be appreciated.

Java/SQL result-stack error

Here is a method that I am writing for a class. It is supposed to refresh a table with data obtained from quering a database. I get an error when trying to scan through the line newResult.next().
I tried debugging, but that doesn't show me anything. the code prints out the line "In while loop", so I know that the problem is the in the line right after it. I constantly get the error, "After start of result set". I tried looking at my code, but it doesn't look like I am calling that method anywhere else either. thanks.
public void refresh()
{
try
{
Statement statement = gtPort.getConnection().createStatement();
//this query is also not working, not really sure how it works.
String query = "SELECT CRN, Title, Instructor, Time, Day, Location, Letter"
+ "FROM Section S WHERE CRN NOT IN "
+ "(SELECT CRN FROM Registers R WHERE Username = \""
+ gtPort.userName + "\")";
System.out.println(query);
statement.executeQuery(query);
System.out.println("Statemetne execute ");
// String[] columns = {"Select", "CRN", "Title", "Instructor", "Time",
// "Days", "location", "Course Code*", "Section"*,"Mode of Grading*"};
ResultSet result = statement.getResultSet();
System.out.println("created result");
data = new Object[10][10];
System.out.println("created data");
Object[] values = new Object[10];
System.out.println("created values");
// values[0] = null;
if (result == null)
{
System.out.println("result is null");
}
String[] titles = new String[100];
//for (int i = 1; i< table.getColumnCount(); i++)
//model.removeRow(i);
//table.removeAll();
//table.repaint()
model.setRowCount(0);
table = new JTable(model);
model.setRowCount(35);
for (int i = 1; result.next(); i++)
{
values[1] = Boolean.FALSE;
for (int j = 2; j< 8; j++)
values[j] = result.getString(j);
titles[i] = result.getString(2);
model.insertRow(i, values);
}
String[] codes = new String[table.getColumnCount()];
System.out.println("count: " + titles.length);
for (int i = 1; I < titles.length; i++)
{
query = new String("SELECT C.Code FROM Code C WHERE C.Title = \""
+ titles[i] + "\"");
//this is a different query to check for titles.
statement.executeQuery(query);
System.out.println(query);
ResultSet newResult = statement.getResultSet();
// codes[i] = newResult.getString(1);
if (newResult == null)
{
System.out.println("it is null");
break;
}
//this is the loop where it breaks.
while(newResult.next());
{
System.out.println("in while loop");
//this line prints, so the next line must be the problem.
model.setValueAt(newResult.getString(1), i, 8);
}
System.out.println("nr: \t" +newResult.getString(1));
}
System.out.println("before table");
table = new JTable(model);
System.out.println("created table");
}
catch (Exception exe)
{
System.out.println("errored in course selection");
System.out.println(exe);
}
}
Write ResultSet rs = statement.executeQuery(query); instead. getResultSet() is called when you have got more then one result sets from executed statement.
Don't use constructor new String() for creating String. Simply write:
String new = "content";
You cannot predict how much your first query will return so don't create arrays with stated size but use better ArrayList:
Code:
//creation
List<Object> values = new ArrayList<Object>();
List<String> titles = new ArrayList<String>();
//usage - adding
values.add(someObject);
//usage - getting
for (String title : titles)
//or
titles.get(byIndex);

Categories

Resources