We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › arraylist with mysql
Page Index Toggle Pages: 1
arraylist with mysql (Read 1337 times)
arraylist with mysql
Mar 16th, 2009, 2:34pm
 
Hi,

im trying to populate an ArrayList with information from a mysql database i have the connection etc working and i think i have the ArrayList being populated by the data from the mysql connection.

how would i then display the info from the ArrayList with the text function?

i have a basic thing working that just reads the info in and then just displays. But im using sms messages to populate the database and only want to display new messages and not have to churn out all the info again
Re: arraylist with mysql
Reply #1 - Mar 16th, 2009, 4:05pm
 
This seems strongly related to mysql strings and text, no
Did you succeed in making a request fetching only the newest data
Where are you stuck exactly Getting the data Displaying a list of strings
Re: arraylist with mysql
Reply #2 - Mar 16th, 2009, 4:20pm
 
yeah its not much further along i thought re-phrasing might help me out.

i can get at the information easy enough but when i tried to put it into an array it said i couldn't convert String to string[]

the only way i got it to fetch new data was to put a delay in the draw function and then got it to query the db again which just re-outputed the data plus the new stuff

so i have the data and can display but how should i be storing the info once i have it? and yes i am stuck just getting it to print out the newest data.

Once i have the basic framework i want to be able to scan the text for specific words to prompt certain functions is that possible ?
Re: arraylist with mysql
Reply #3 - Mar 16th, 2009, 5:18pm
 
Well, you can re-phrase in the old thread, at least it provides some context on the topic.

Anyway, without code it is hard to tell what is your problem on conversion. Perhaps you need to split a string, perhaps that's something else.

For storing the new data, I updated my answer in the old thread. If there is something unclear in my pseudo-code, just ask.

And yes, you can scan the stored data to find some strings.
Re: arraylist with mysql
Reply #4 - Mar 17th, 2009, 9:06am
 
given you use a primary id (int) on the table with the messages. then "new" in terms of mysql does not mean you automatically have a higher id for new ones, some databases are set to reuse discarded ids. so looking for a higher entry than the last one read might not be perfect. what you want to do is add a timestamp (use unix timestamp as int) to each entry. then keep the highest last read timestamp and integrate that into the select-query:

SELECT * FROM messages WHERE timestamp < last_timestamp

ok, now you have a resultset to iterate over. depending on your setup it might be ok to just have a String[] array and use append to add the messeges to the end.

String[] messeges; // somewhere global

// ..

while (dbconnection.next())
{
 String msg = dbconnection.getString("message");
 messages = append( messages, msg );

 int ts = dbconnection.getInt("timestamp");
 if ( last>_timestamp < ts )
    last_timestamp = ts; // keep for next select
}


let me know if you have questions ..
F
Re: arraylist with mysql
Reply #5 - Mar 20th, 2009, 5:40pm
 
Ok have tried to implement using the row id, not exactly what you said to do but i am going to use the time stamp once i get my head round how to do this.

first problem i have is when i try to append the arrays it come up with the local variable messages may not have been initalized ...how do i fix that

the other issue is that using the where search in the sql still churns out all of the table and not just the new stuff

Re: arraylist with mysql
Reply #6 - Mar 21st, 2009, 2:05pm
 
I'm currently crapping myself because i cant get this stupid thing to work.

I have tried to initialize the append function but either comes up with a nullpointerexception, or local variable not initialized or cannot convert object to string.

String[] msg ;//which is set globally

msg = append(msg,s);

i think i have got some sort of query function working but all it is doing at the moment is just spitting out the entire db again i was kind of expecting it to churn out everything at first then add the new additions....i was wrong  

msql.query("select * from inbound where id > 'last_id' ")

have i phrased the query correct or am i just not seeing something





Re: arraylist with mysql
Reply #7 - Mar 21st, 2009, 5:48pm
 
ilikebagels wrote on Mar 21st, 2009, 2:05pm:
msql.query("select * from inbound where id > 'last_id' ")

have i phrased the query correct or am i just not seeing something


what is last_id in that query because the way you've written it it's a string literal, the word 'last_id'. if it's a processing variable then you'll need

"select * from inbound where id > '" + last_id + "'"

if it's an mysql variable then you'll need to make it look like one (with an @)
Re: arraylist with mysql
Reply #8 - Mar 21st, 2009, 7:38pm
 
you have to initialize the msg array before you can append something to it.

String[] msg = new String[0]; // emtpy String array (length 0)
Re: arraylist with mysql
Reply #9 - Mar 21st, 2009, 9:56pm
 
OK, I finally found some time to experiment. I wanted to try SQL connection with Processing, so it was a good opportunity.

First, I created a test table in the default test base of my local MySQL base:
Code:
CREATE TABLE p5_messages
(
id int(11) NOT NULL auto_increment,
creator varchar(32) default NULL,
message varchar(160) default NULL,
date_added datetime default NULL,
PRIMARY KEY (id)
) ENGINE=MyISAM CHARSET=latin1;


Then I wrote a little PHP script to enter data there:
Code:
<body>

<h1>Filling Database Fields</h1>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST">
<fieldset><legend>Message Input</legend>
<label for="author">Author:</label><input type="text" name="author" id="author"/><br/>
<label for="message">Message:</label><input type="text" name="message" id="message" size="160"/><br/>
<input type="submit"/>
</fieldset>
</form>

</body>
</html>

<?php
if (!isset($_POST['message']))
return; // Just display the page
$author = htmlspecialchars(@$_POST['author']);
$message = htmlspecialchars(@$_POST['message']);
AddData($author, $message);
?>

<?php
function AddData($author, $message)
{
$cnx = mysql_connect('localhost', 'PhiLho', 'Foo#Bar') or die('Could not connect: ' . mysql_error());
mysql_select_db('tests', $cnx) or die('Could not select DB "tests": ' . mysql_error());

mysql_query("INSERT INTO p5_messages (creator, message, date_added)
VALUES ('$author', '$message', now())");

mysql_close($cnx);
}
?>


And finally I wrote a sketch to display this data.
I had some difficulty to find a good strategy so each message is displayed a minimum time, even if there are bursts of new messages.
Mmm, the latter code is a bit long, continuing on next message.
Re: arraylist with mysql
Reply #10 - Mar 21st, 2009, 9:56pm
 
Code:
import de.bezier.data.sql.*;
import java.sql.Timestamp;

static final String TABLE_NAME = "p5_messages";

static final int CHECK_INTERVAL = 5; // seconds
int lastCheck = - CHECK_INTERVAL - 1;
Timestamp lastTimestamp = new Timestamp(0L);
static final int MESSAGE_DISPLAY_DURATON = 10; // seconds
int lastMessageDisplayedIndex;
int lastMessageDisplayDuration = MESSAGE_DISPLAY_DURATON;
static final int MESSAGE_DISPLAY_NB = 4;

MySQL mysql;
PFont fontHeader;
PFont fontMessage;

ArrayList messageList = new ArrayList();

void setup()
{
 size(400, 700);
 smooth();
 fontHeader = createFont("Arial", 30);
 fontMessage = createFont("Verdana", 16);

 Connect();
//~   Message m = GetMessage(2);
//~   ShowMessage(m);
}

void stop()
{
 println("Stopping connection");
 mysql.close();
}

void draw()
{
 int time = millis() / 1000;
 if (time - lastCheck > CHECK_INTERVAL)
 {
   lastCheck = time;
   // On second though, no need for this!
//~     int newMessageNb = CheckNewMessages(lastTimestamp);
   int newMessageNb = GetNewMessages(lastTimestamp);
   int totalMessageNb = messageList.size();
   println("New messages: " + newMessageNb + ", total: " + totalMessageNb);
   if (newMessageNb > 0)
   {
     Message lastMessage = (Message) messageList.get(totalMessageNb - 1);
     lastTimestamp = lastMessage.m_date;
   }

   background(#225577);
   textFont(fontHeader, 36);
   fill(#FFCC88);
   text("Message Board", 10, 36);
   ShowCount();
   if (totalMessageNb == 0)
     return;

   lastMessageDisplayDuration -= CHECK_INTERVAL;
   if (lastMessageDisplayDuration <= 0 && lastMessageDisplayedIndex < totalMessageNb - 1)
   {
     lastMessageDisplayedIndex++;
   }
   for (int i = 0; i < MESSAGE_DISPLAY_NB; i++)
   {
     int idx = 1 + lastMessageDisplayedIndex - MESSAGE_DISPLAY_NB + i;
     if (idx < 0)
       continue;
     Message m = (Message) messageList.get(idx);
     ShowMessage(m, i);
   }
 }
}

void ShowCount()
{
 textFont(fontHeader, 20);
 fill(#AACC88);
 text("Number of messages: " + GetCount(), 10, 60);
}

void ShowMessage(Message m, int pos)
{
 int yPos = 100 + pos * 150;
 textFont(fontMessage);
 fill(#FF8855);
 text(m.m_author, 10, yPos);
 fill(#8855FF);
 text(FormatHour(m.m_date), 100, yPos);
 fill(#00EE77);
 text(m.m_message, 10, yPos + 10, width - 2, 200);
}

/*=== Message Class ===*/

class Message
{
 String m_author;
 String m_message;
 Timestamp m_date;
 int rank;

 Message(String author, String message, Timestamp date)
 {
   m_author = author;
   m_message = message;
   m_date = date;
   rank = messageList.size();
 }
}

/*=== MySQL Section ===*/

void Connect()
{
 mysql = new MySQL(this, "localhost", "tests", "PhiLho", "Foo#Bar");
 if (!mysql.connect())
 {
   println("Cannot connect to database!");
   exit();
 }
}

int GetCount()
{
 mysql.query("SELECT COUNT(*) FROM " + TABLE_NAME);
 mysql.next();
 return mysql.getInt(1);
}

int CheckNewMessages(Timestamp previousDate)
{
 mysql.query("SELECT COUNT(*) FROM " + TABLE_NAME +
     " WHERE date_added > '" + FormatTimestamp(previousDate) + "'"
 );
 mysql.next();
 return mysql.getInt(1);
}

int GetNewMessages(Timestamp previousDate)
{
 String query = "SELECT creator, message, date_added FROM " + TABLE_NAME +
     " WHERE date_added > '" + FormatTimestamp(previousDate) + "'";
 println(query);
 mysql.query(query);
 int newMessageNb = 0;
 while (mysql.next())
 {
   String a = mysql.getString(1);
   String m = mysql.getString(2);
   Timestamp d = mysql.getTimestamp(3);
   Message msg = new Message(a, m, d);
   messageList.add(msg);
   newMessageNb++;
 }
 return newMessageNb;
}

Message GetMessage(int idx)
{
 mysql.query("SELECT creator, message, date_added FROM " + TABLE_NAME +
     " WHERE id=" + idx
 );
 mysql.next();
 String a = mysql.getString(1);
 String m = mysql.getString(2);
 Timestamp d = mysql.getTimestamp(3);
 return new Message(a, m, d);
}

String FormatHour(Timestamp ts)
{
 DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
 return formatter.format(ts);
}

String FormatTimestamp(Timestamp ts)
{
 DateFormat formatter = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
 return formatter.format(ts);
}

Some code there isn't used but can be interesting to see.
Re: arraylist with mysql
Reply #11 - Mar 22nd, 2009, 4:29pm
 
last_id is a processing variable that is declared globally, just tried it out there still not luck it still just churns out everything in the database :(

to explain a bit further im trying to use the row numbers which  auto increment as new data is put in. So im reading in the db storing the row number and then using that to check to see for new data and only want to select the new data

 if ( msql.connect() )
   {  
     
       msql.query( "select * from inbound where id > '" + last_id + "'"  );
     
       
       while (msql.next())
       {
         
         String s = msql.getString("message");
           int n = msql.getInt("id");
           println(s + "   " + n);
           fill(0);
           textFont(f);
           textAlign(CENTER);
           if ((linePos<= 100) || (linePos>=100)){
             linePos = linePos + 20;
           }
           //rotate(PI/1.0);
           text(s,150,linePos);
           if(last_id < id){
             last_id = id;
           }
           
         
         
           
       }
Re: arraylist with mysql
Reply #12 - Mar 26th, 2009, 7:17am
 
what is the value of last_id at the beginning?
Page Index Toggle Pages: 1