Blackberry APplication not rendering well on PORSCHE phones - user-interface

I have got a Blackberry native application I have been working on in the past few weeks.
Basically it consists of a few screens in which I get to draw the designs of my screen by overriding the paint method of the FieldManagers
I have tested on blackberry 4.5 and other blackberry's.
It has rendered well so far until I ran into a hitch testing on Blackberry's Porsche version
which does not render my designs well. What I experience is that on scrolling, my screen gets wiped off.
Pls does any one here experienced such issues in the past and what would be the cause. I would be willing to show sections of the code to give insight into the issues I am experiencing. Least I mention it displays well on the simulator without these issues.
I have posted a sample screen which is my login screen:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
final VerticalFieldManager spaceHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new Util().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),topSpaceHeight);
setExtent(Display.getWidth(), topSpaceHeight);
}
};
final VerticalFieldManager contentHolderPix = new VerticalFieldManager(VerticalFieldManager.VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
System.out.println(">>>>!!!!>>>>" + "img/icons/logo" + new Util().getResource() + ".png");
EncodedImage image_1 = EncodedImage.getEncodedImageResource("img/icons/icon" + new Util().getResource() + ".png");
setFont(util.initializeUtilFont("Arial", editFieldFontHeaderSize, Font.BOLD));
int startHere = topSpaceHeight - image_1.getHeight() - 5;
int imageWidth1 = (int)((Display.getWidth() - image_1.getWidth() - getFont().getAdvance("Sign In"))/2);
graphics.drawBitmap(new XYRect(imageWidth1 - 10 - whiteBgEdge.left - whiteBgEdge.right, startHere, image_1.getWidth(), image_1.getHeight()), image_1.getBitmap(), 0, 0);
int startfonty = startHere + ((image_1.getHeight() - getFont().getHeight())/2);
graphics.drawText("Sign In", imageWidth1, startfonty);
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(whiteBgWidth,topSpaceHeight);
setExtent(whiteBgWidth, topSpaceHeight);
setMargin(whiteBgEdge);
}
};
System.out.println("whiteBgWidth>>>>" + whiteBgWidth);
System.out.println("padExtWhiteBg>>>>" + padExtWhiteBg);
usernameField = utilNew.newEditTextField(editFieldWidth, editFont.getHeight(), 30,
EditField.NO_NEWLINE, "", editFieldPad, editFont, false, "Username");
passwordField = utilNew.newPasswordField(editFieldWidth, editFont.getHeight(), 30,
PasswordEditField.NO_NEWLINE, "Password", editFieldPad, editFont);
//usernameField.setMargin(holderPad1);
if(user_!=null && user_.getSignInUserName()!=null && user_.getSignInUserName().trim().length()>0)
usernameField.setText(user_.getSignInUserName());
final int edHt = editFont.getHeight() + editFieldPad.top + editFieldPad.bottom;
final int edWt = editFieldWidth + editFieldPad.left + editFieldPad.right;
System.out.println("edHt = " + edHt);
System.out.println("edWt = " + edWt);
System.out.println("HolderPad1 = " + holderPad1.top + ", " + holderPad1.bottom + ", " + holderPad1.left + ", " + holderPad1.right);
usernameFieldHolder = utilNew.generateEditTextField(usernameField, true, holderPad1, edHt, edWt, true);
passwordFieldHolder = utilNew.generateEditTextField(passwordField, true, holderPad2, edHt, edWt, false);
final int height_ = edHt + edHt + holderPad1.top + holderPad1.bottom + holderPad2.top + holderPad2.bottom + 20;
System.out.println("height___>>>>>" + height_);
final VerticalFieldManager contentHolder1 = new VerticalFieldManager()
{
public void paint(Graphics graphics)
{
//System.out.println(edHt + "," + edHt + "," + holderPad1.top + "," + holderPad1.bottom + "," + holderPad2.top + "," + holderPad2.bottom);
graphics.setBackgroundColor(util.ashbrand);//black
graphics.setColor(new Util().whitebrand);
graphics.drawRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.fillRoundRect(0, 0, whiteBgWidth, height_, 20, 20);
graphics.setColor(0x00808080);
//System.out.println("This is changed?");
//System.out.println("<<<<<<.." + usernameFieldHolder.getPreferredHeight() + "hfm.getPreferredHeight() = 0" + usernameFieldHolder.getWidth() );
//graphics.drawLine(40, usernameField.getPreferredHeight(), whiteBgWidth, usernameField.getPreferredHeight());/**/
super.paint(graphics);
}
public void sublayout(int width, int height){
System.out.println(Display.getHeight() + " - " + Display.getWidth());
System.out.println("Wdith & height = " + width + " && " + height);
System.out.println("Wdith & this.getPreferredHeight() = " + this.getWidth() + " && " + this.getHeight());
super.sublayout(whiteBgWidth,height_);
setExtent(whiteBgWidth, height_);
setMargin(whiteBgEdge);
}
};
int buttonHeight = 70;
/*CustomManager hfm_buttons = util.generateHFM1(
contentHolder1.getPreferredWidth(),
buttonHeight,
new Util().whitebrand,
0);*/
//submitButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "LOGIN", null);
//registerButton = new UtilNew().generateButtonField(0x333333, util.whitebrand, "REGISTER", null);
final LabelField loginButton = new LabelField("", Field.FOCUSABLE)
{
private int hColor;
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth())+2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Sign In"))/2;
g.drawText("Sign In", width, height);
setExtent(totalWidth+ 5,left.getHeight() + 10);
//setMargin(new XYEdges(20, 10, 0, whiteBgEdge.left));
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
String userName = usernameField.getText().toString().toLowerCase();
user_.setSignInUserName(userName);
String passWord = passwordField.getText().toString();
System.out.println("username = " + userName + " & password = " + passWord);
User user = User.getInstance();
System.out.println(">>instance of user from sign in: " + user);
Records record = new Records();
if(passWord.trim().length() < 2 || userName.trim().length() < 2){
Dialog.alert("Invalid username and/or password entered");
SignIn screen = new SignIn();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(screen);
}else{
System.out.println("else if data is calid");
String hashPassword = user.md5Java(passWord);
hashPassword = "e86e107b113b0f830b9b817b4a9addb8";
user_.setUserName(userName);
user_.setPassword(passWord);
System.out.println("Check data availability");
try
{
FileConnection fc = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION);
FileConnection fc1 = (FileConnection)Connector.open(utilNew.FOLDER_LOCATION_REF);
if (!fc.exists())
{
fc.mkdir();
if (!fc1.exists())
{
fc.mkdir();
}
}
fc.close();
}
catch (IOException ioe)
{
System.out.println(ioe.getMessage() );
}
if((record.isDataAvailable(record.userTable)==true))
{
System.out.println(">>>>### -1 ");
String[] allRecords = record.getAllRecords(record.userTable);
boolean proceedYes = true;
int count = 0;
while(proceedYes && count<allRecords.length)
{
System.out.println(">>>> Record = " + allRecords[count]);
//Dialog.alert(">>>> Record = " + allRecords[count]);
DataInputStream is = new DataInputStream(new ByteArrayInputStream(allRecords[count].getBytes()));
try {
System.out.println(">>>>555");
//System.out.println(">>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
String l = is.readUTF();
String u = is.readUTF();
String p = is.readUTF();
//System.out.println("e>>>>" + is.readUTF() + " && " + is.readUTF() + " && " + is.readUTF());
System.out.println("f>>>>" + l + " && " + u + " && " + p);
System.out.println("g>>>>" + userName + " && " + passWord + " && " + p);
if(u.equals(userName) && p.equals(passWord))
{
//Dialog.alert(">>>>12");
System.out.println(">>>889948444>");
proceedYes = false;
MenuLists screen = new MenuLists(10);
//UiApplication.getUiApplication().pushScreen(homeScreen);
ScreenController screenController = ScreenController.getInstance();
screenController.setCurrentScreen(SignIn.this);
screenController.addNewScreen(screen);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println(">>>>Error " + e.getMessage() + " && " + e.toString() );
}
count++;
}
if(proceedYes)
{
System.out.println(">>>>### 3 ");
Hashtable jj = new Hashtable();
boolean proceedNow = false;
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Setting up our account. Please Wait");
}
}
else
{
System.out.println(">>>>### o ");
Hashtable jj = new Hashtable();
boolean proceedNow=false;
System.out.println(">>>>### 4 ");
jj.put("username", userName);
jj.put("password", passWord);
jj.put("url", "https://localhost:8080/signinws/rest/account/login2");
System.out.println("object sent to server: "+jj);
proceedNow = true;
ProcessAction processAction = new ProcessAction(jj, 0, record);
PopUpScreen.showScreenAndWait(processAction, "Please Wait");
}
}
return super.navigationClick(status, time);
}
};
final LabelField registerButton = new LabelField("", Field.FOCUSABLE)
{
public boolean isFocusable() {
return true;
}
protected void drawFocus(Graphics g, boolean on){
XYRect rect = new XYRect();
getFocusRect(rect);
drawHighlightRegion(g, HIGHLIGHT_FOCUS, false, rect.x, rect.y, rect.width, rect.height);
}
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
EncodedImage center;
int hColor;
if(isFocus())
{
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/right.png");
g.setColor(util.green);
hColor = 0xcccccc;
}
else
{
left = EncodedImage.getEncodedImageResource("img/buttons/_left.png");
center = EncodedImage.getEncodedImageResource("img/buttons/_center.png");
right = EncodedImage.getEncodedImageResource("img/buttons/_right.png");
g.setColor(util.greenDark);
hColor = util.ashbrand;
}
//g.fillRect(0, 0, getPreferredWidth(), getPreferredHeight());
int totalWidth = whiteBgWidth + 4;
XYRect left_edge=new XYRect(2, 2, left.getWidth(), left.getHeight());
g.drawBitmap(left_edge, left.getBitmap(), 0, 0);
//invalidate();
int startX= (Display.getWidth() - totalWidth)/2;
int vount = (int)((totalWidth - left.getWidth() - right.getWidth())/center.getWidth()) - 3;
XYRect left_edgeH=new XYRect(0, 0, vount, left.getHeight()+2);
//System.out.println("vount = " + vount);
int widthbt = 0;
for(int c=0; c<vount; c++)
{
widthbt = left.getWidth() + (c*center.getWidth()) + 2;
XYRect center_edge=new XYRect(widthbt, 2, center.getWidth(), center.getHeight());
g.drawBitmap(center_edge, center.getBitmap(), 0, 0);
}
XYRect right_edge=new XYRect(widthbt,2, right.getWidth(), right.getHeight());
g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//invalidate();
//g.drawBitmap(right_edge, right.getBitmap(), 0, 0);
//g.fillRect(left_edge.getWidth(), 0, getPreferredWidth(), getPreferredHeight());
int colorOld = g.getColor();
g.setColor(hColor);
g.drawRoundRect(0, 0, totalWidth-4, left.getHeight()+4, 3, 3);
g.setColor(colorOld);
if(isFocus())
{
g.setColor(util.black);
}
else
{
g.setColor(util.whitebrand);
}
int height = (left.getHeight() - getFont().getHeight())/2;
int width = (totalWidth - getFont().getAdvance("Create An Account"))/2;
g.drawText("Create An Account", width, height);
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
public int getPreferredHeight() {
return getFont().getHeight() + 20;
}
public int getPreferredWidth() {
return (int)(whiteBgWidth);
}
protected boolean navigationClick(int status, int time) {
removeAllMenuItems();
RegisterScreen registerScreen = new RegisterScreen();
ScreenController screenController = ScreenController.getInstance();
screenController.addNewScreen(registerScreen);
return super.navigationClick(status, time);
}
};
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
spaceHolder2.add(loginButton);
spaceHolder2.add(registerButton);
//spaceHolder2.add(registerButton);
spaceHolder1.add(contentHolderPix);
everythingPanel.add(spaceHolder1);
contentHolder1.add(usernameFieldHolder);
contentHolder1.add(passwordFieldHolder);
/*passwordFieldDummyHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_GAINED)
{
contentHolder1.replace(passwordFieldDummyHolder, passwordFieldHolder);
}
}
});
passwordFieldHolder.setFocusListener(new FocusChangeListener(){
public void focusChanged(Field field, int eventType) {
// TODO Auto-generated method stub
if(eventType == FocusChangeListener.FOCUS_LOST)
{
System.out.println(">>>>>|>>>" + passwordFieldHolder.getIndex());
System.out.println(">>>>>|>>>" + passwordFieldDummyHolder.getIndex());
if(passwordField.getText().length()==0)
{
System.out.println(">>>>>1>>>");
passwordFieldDummyHolder = utilNew.generateEditTextField(passwordFieldDummy, true, holderPad2, edHt, edWt, false);
contentHolder1.replace(passwordFieldHolder, passwordFieldDummyHolder);
//loginButton.setFocus();
}
System.out.println(">>>>>2>>>");
System.out.println(">>>>>2>>>");
}
}
});*/
everythingPanel.add(contentHolder1);
everythingPanel.add(spaceHolder2);
add(everythingPanel);
}

I don't know what your problem actually is, but from what I have seen in your sample code it is clear that you are using the UI framework in a way that is not correct. You need to fix these issues before proceeding further.
Here is an example:
final VerticalFieldManager everythingPanel = new VerticalFieldManager(VERTICAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
super.sublayout(Display.getWidth(),Display.getHeight());
setExtent(Display.getWidth(), Display.getHeight());
}
};
In this case you ask the parent Manager to lay itself out and give it specific sizes to do so. When doing this, you need to be sure that the sizes you are giving the parent class are not bigger than the size you have been given, So it is more correct to code something like:
super.sublayout(Math.min(Display.getWidth(), width),Math.min(Display.getHeight(), height));
What this will do is attempt to layout the Fields that are contained in the Manager, within the confines of the screen space you have told it to use (in this case the size of the screen). Having done this, it will set the actual size that it needs - in other words, at the end of the layout method, VerticalFieldManager will know how big it needs to be and will set that size. Then it returns. And then you do this:
setExtent(Display.getWidth(), Display.getHeight());
Effectively now you have a VerticalFieldManager that thinks it is working in a certain size, and will optimise its painting around that size, and you have potentially given it a different size. This could confuse!
The same comments apply within a Field's layout() method too.
In other words, if you are going to let the super class layout the Fields, then let the super class set the size, otherwise things can be confused.
Here is another, in fact worse, example:
final VerticalFieldManager spaceHolder2 = new VerticalFieldManager(NO_VERTICAL_SCROLL | NO_HORIZONTAL_SCROLL)
{
public void paint(Graphics graphics)
{
graphics.setBackgroundColor(utilNew.ashbrand);
graphics.clear();
super.paint(graphics);
}
public void sublayout(int width, int height){
int w = whiteBgWidth;
super.sublayout(w, (loginButton.getPreferredHeight() * 2) + 40);
setExtent(w, (loginButton.getPreferredHeight() * 2) + 40);
int startX = (int)((Display.getWidth() - whiteBgWidth)/2);
setMargin(new XYEdges(20, 0, 0, startX));
}
};
Why is this worse? Because of this line:
setMargin(new XYEdges(20, 0, 0, startX));
Remember the point of sublayout is to position all your Fields on the screen. You have invoked the super.sublayout() processing to do this, and then, once it has done it, you suddenly say actually, I want some margins on the Field. Again you are potentially confusing the processing - in the middle of laying out the Fields you are changing one of the factors that is related to laying the Fields out...
I suggest you review the documentation around creating Managers (and presumably Fields) and look to remove any code that is disrupting this process. To assist you in this investigation, I recommend that you start here:
http://supportforums.blackberry.com/t5/Java-Development/MainScreen-explained/ta-p/606644
and then look at these:
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/How-to-Extend-the-Screen/ta-p/446745
http://supportforums.blackberry.com/t5/Java-Development/Create-a-custom-layout-manager-for-a-screen/ta-p/442990
http://supportforums.blackberry.com/t5/Java-Development/Create-custom-fields/ta-p/444962
You do a similar sort of thing in your paint routine. Here is a snippet:
public void paint(Graphics g)
{
EncodedImage left;
EncodedImage right;
...
left = EncodedImage.getEncodedImageResource("img/buttons/left.png");
...
setExtent(totalWidth + 5,left.getHeight() + 10);
setPosition(0, getFont().getHeight() + 30);
invalidate();
super.paint(g);
}
paint()'s job is to paint, not to position. Your code is supposed to position Fields in your layout (or sublayout) processing. But in the code above, you potentially move and change the size of a Field while it is trying to paint it!!!! This is bound to cause the system some problems.
The general rule in paint() is you do NOT change the Field, you just paint its current contents.
Two other things I will comment on with respect to the paint() code given above.
1) paint() is called often. You really want to minimise the processing done in paint. So don't create an image (see the left image in the code included above) each time you go through it. Create this once and then use paint to paint() the image. Doing excessive work in paint causes performance problems as well as killing the battery. This is the sort of thing you will not notice on the Simulator because it is so fast compared to the device.
2) And be aware that idea when using invalidate() is to repaint the Field. So there is no point calling invalidate() in the middle of paint(). In fact by doing this, you are causing an infinite loop. Each time you call paint(), your code is then using invalidate() to ask the Field to repaint itself, which causes paint() to be invoked, which asks for a invalidate(), ... You get the picture!.
I have pointed out problems in your layout processing and your paint processing. I'm not saying that these problems are in fact directly giving you the issues you see. It might be something else. You have supplied far too much code for me to review it all looking for that needle. If you want us to review code in detail, then I suggest you recreate the problem with a smaller sample of code. In fact I recommend you try to do this, because by cutting out code until the problem disappears, you will find out what actually is causing the problem.
Finally a couple of other points:
A) There is no real difference between doing background painting in paint() or paintBackground(). And in fact the only background painting you seem to do is this:
graphics.setBackgroundColor(new UtilNew().ashbrand);
graphics.clear();
which is absolutely fine in paint(), and I wouldn't bother changing this to use paintBackground() or a Background class. The one issue I have with this code is that fact that you create a new class instance of UtilNew each time paint is invoked (which is a lot). That won't help performance.
B) I would avoid calling Screen.invalidate() in a scroll change listener until you are sure that there is no other way to get the screen painted correctly. As noted, there is a lot of other suspect code in what you have supplied. Correct that before you try Screen.invalidate().

Related

Best way to handle awt.Image buffering in JavaFX

I have a class that takes a String parameter and performs a google search, then it gets the ten images and puts them in an array, that is then handled by another method in the same class. Using Javafx.scene.image would probably allow me to implement the buffering progress easily, but there is a bug with JavaFX Image, that misinterprets the color encoding of normal Images, and saves a weird looking image to the hard drive, so I just decided to use awt.Image.
This is the image search class:
public class GoogleCustomSearch {
static String key = //custom google id;
static String cx = // also a custom google id;
static String searchType = "image";
static java.awt.Image[] publicImageArray;
public static java.awt.Image[] Search(String searchParameter,int start) throws IOException, URISyntaxException{
String formatedText = URLEncoder.encode(searchParameter,"UTF-8");
URL url = new URL("https://www.googleapis.com/customsearch/v1?" + "key=" +key + "&cx=" +cx + "&q=" +formatedText + "&searchType=" +searchType +"&imgSize=medium" + "&start=" + start + "&num=10");
System.out.println(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader( ( conn.getInputStream() ) ) );
GResults results = new Gson().fromJson(br, GResults.class);
java.awt.Image [] imageArray = new java.awt.Image[10];
//JProgressBar prb = new JProgressBar();
//MediaTracker loadTracker = new MediaTracker(prb);
for(int i = 0; i<10; i++){
try {
imageArray[i] = ImageIO.read(new URL(results.getLink(i)));
}catch (java.io.IOException e){
imageArray[i] = ImageIO.read(new File("C:\\Users\\FILIP.D\\IdeaProjects\\Manual_Artwork\\src\\MAT - NoImage.jpg"));
}
}
conn.disconnect();
return imageArray;
}
public static BufferedImage getImage(String searchPar, int index, boolean newSearch) throws IOException, URISyntaxException {
int adaptedIndex;
int start;
BufferedImage bimage;
if(index<10){
adaptedIndex = index;
start = 1;
}else if (index<20){
start = 11;
adaptedIndex = index % 10;
if(index == 10){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else if(index < 30){
start = 21;
adaptedIndex = index % 10;
if (index == 20) {
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
}
}else{
adaptedIndex = index % 10;
start = 21; //ovo ce posle 30 da ga vrti u loop prvih 10
}
if(newSearch){
publicImageArray = new java.awt.Image[10];
publicImageArray = Search(searchPar,start);
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}else{
return bimage = (BufferedImage) publicImageArray[adaptedIndex];
}
}
public static RenderedImage getLiveImage (int index){
return (RenderedImage) publicImageArray[index % 10];
}
}
And this is the snippet of the main GUI class that just handles opening the new image in the array
private void nextImageResult() throws IOException, URISyntaxException {
if(imgNr == -1){
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,true),null));
}else{
imgNr++;
changeImage(SwingFXUtils.toFXImage(GoogleCustomSearch.getImage(oppenedTrack.getArtistName() + "+" + oppenedTrack.getTrackName(),imgNr,false),null));
}
}
To summarise, I need a proper way to show a progress bar in the place of the image before it loads, and it needs not to hang the UI, for which I can use Task. I can optimise the loading of the array with MediaTracker, so it can prioritize loading the first few images first.

How to correct loop counters for maze algorithm?

I have figured out how to move my character around the maze using the algorithm I have written, but the count is not figuring correctly. At the end of each row my character moves up and down several times until the count reaches the specified number to exit the loop, then the character moves along the next row down until it reaches the other side and repeats the moving up and down until the count reaches the specified number again. Can anyone help me find why my count keeps getting off? The algorithm and the maze class I am calling from is listed below.
public class P4 {
public static void main(String[] args) {
// Create maze
String fileName = args[3];
Maze maze = new Maze(fileName);
System.out.println("Maze name: " + fileName);
// Get dimensions
int mazeWidth = maze.getWidth();
int mazeHeight = maze.getHeight();
// Print maze size
System.out.println("Maze width: " + mazeWidth);
System.out.println("Maze height: " + mazeHeight);
int r = 0;
int c = 0;
// Move commands
while (true){
for (c = 0; c <= mazeWidth; c++){
if (maze.moveRight()){
maze.isDone();
c++;
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveRight() == false && c != mazeWidth){
maze.moveDown();
maze.moveRight();
maze.moveRight();
maze.moveUp();
c++;
}
}
for (r = 0; r % 2 == 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
for (c = mazeWidth; c >= 0; c--){
if (maze.moveLeft()){
c--;
maze.isDone();
System.out.println(c);
}
if (maze.isDone() == true){
System.exit(1);
}
if (maze.moveLeft() == false && c != 0){
maze.moveDown();
maze.moveLeft();
maze.moveLeft();
maze.moveUp();
c--;
}
}
for (r = 1; r % 2 != 0; r++){
maze.moveDown();
maze.isDone();
if (maze.isDone() == true){
System.exit(1);
}
}
}
}
}
public class Maze {
// Maze variables
private char mazeData[][];
private int mazeHeight, mazeWidth;
private int finalRow, finalCol;
int currRow;
private int currCol;
private int prevRow = -1;
private int prevCol = -1;
// User interface
private JFrame frame;
private JPanel panel;
private Image java, student, success, donotpass;
private ArrayList<JButton> buttons;
// Maze constructor
public Maze(String fileName) {
// Read maze
readMaze(fileName);
// Graphics setup
setupGraphics();
}
// Get height
public int getHeight() {
return mazeHeight;
}
// Get width
public int getWidth() {
return mazeWidth;
}
// Move right
public boolean moveRight() {
// Legal move?
if (currCol + 1 < mazeWidth) {
// Do not pass?
if (mazeData[currRow][currCol + 1] != 'D')
{
currCol++;
redraw(true);
return true;
}
}
return false;
}
// Move left
public boolean moveLeft() {
// Legal move?
if (currCol - 1 >= 0) {
// Do not pass?
if (mazeData[currRow][currCol - 1] != 'D')
{
currCol--;
redraw(true);
return true;
}
}
return false;
}
// Move up
public boolean moveUp() {
// Legal move?
if (currRow - 1 >= 0) {
// Do not pass?
if (mazeData[currRow - 1][currCol] != 'D')
{
currRow--;
redraw(true);
return true;
}
}
return false;
}
// Move down
public boolean moveDown() {
// Legal move?
if (currRow + 1 < mazeHeight) {
// Do not pass?
if (mazeData[currRow + 1][currCol] != 'D')
{
currRow++;
redraw(true);
return true;
}
}
return false;
}
public boolean isDone() {
// Maze solved?
if ((currRow == finalRow) && (currCol == finalCol))
return true;
else
return false;
}
private void redraw(boolean print) {
// Wait for awhile
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
if (print)
System.out.println("Moved to row " + currRow + ", column " + currCol);
// Compute index and remove icon
int index = (prevRow * mazeWidth) + prevCol;
if ((prevRow >= 0) && (prevCol >= 0)) {
buttons.get(index).setIcon(null);
}
// Compute index and add icon
index = (currRow * mazeWidth) + currCol;
if ((currRow == finalRow) && (currCol == finalCol))
buttons.get(index).setIcon(new ImageIcon(success));
else
buttons.get(index).setIcon(new ImageIcon(student));
// Store previous location
prevRow = currRow;
prevCol = currCol;
}
// Set button
private void setButton(JButton button, int row, int col) {
if (mazeData[row][col] == 'S') {
button.setIcon(new ImageIcon(student));
currRow = row;
currCol = col;
} else if (mazeData[row][col] == 'J') {
button.setIcon(new ImageIcon(java));
finalRow = row;
finalCol = col;
} else if (mazeData[row][col] == 'D') {
button.setIcon(new ImageIcon(donotpass));
}
}
// Read maze
private void readMaze(String filename) {
try {
// Open file
Scanner scan = new Scanner(new File(filename));
// Read numbers
mazeHeight = scan.nextInt();
mazeWidth = scan.nextInt();
// Allocate maze
mazeData = new char[mazeHeight][mazeWidth];
// Read maze
for (int row = 0; row < mazeHeight; row++) {
// Read line
String line = scan.next();
for (int col = 0; col < mazeWidth; col++) {
mazeData[row][col] = line.charAt(col);
}
}
// Close file
scan.close();
} catch (IOException e) {
System.out.println("Cannot read maze: " + filename);
System.exit(0);
}
}
// Setup graphics
private void setupGraphics() {
// Create grid
frame = new JFrame();
panel = new JPanel();
panel.setLayout(new GridLayout(mazeHeight, mazeWidth, 0, 0));
frame.add(Box.createRigidArea(new Dimension(0, 5)), BorderLayout.NORTH);
frame.add(panel, BorderLayout.CENTER);
// Look and feel
try {
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
} catch (Exception e) {
e.printStackTrace();
}
// Configure window
frame.setSize(mazeWidth * 100, mazeHeight * 100);
frame.setTitle("Maze");
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setAlwaysOnTop(true);
// Load and scale images
ImageIcon icon0 = new ImageIcon("Java.jpg");
Image image0 = icon0.getImage();
java = image0.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon1 = new ImageIcon("Student.jpg");
Image image1 = icon1.getImage();
student = image1.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon2 = new ImageIcon("Success.jpg");
Image image2 = icon2.getImage();
success = image2.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
ImageIcon icon3 = new ImageIcon("DoNotPass.jpg");
Image image3 = icon3.getImage();
donotpass = image3.getScaledInstance(100, 100, Image.SCALE_DEFAULT);
// Build panel of buttons
buttons = new ArrayList<JButton>();
for (int row = 0; row < mazeHeight; row++) {
for (int col = 0; col < mazeWidth; col++) {
// Initialize and add button
JButton button = new JButton();
Border border = new LineBorder(Color.darkGray, 4);
button.setOpaque(true);
button.setBackground(Color.gray);
button.setBorder(border);
setButton(button, row, col);
panel.add(button);
buttons.add(button);
}
}
// Show window
redraw(false);
frame.setVisible(true);
}
}
One error I can see in your code is that you're incrementing your c counter more often than you should. You start with it managed by your for loop, which means that it will be incremented (or decremented, for the leftward moving version) at the end of each pass through the loop. However, you also increment it an additional time in two of your if statements. That means that c might increase by two or three on a single pass through the loop, which is probably not what you intend.
Furthermore, the count doesn't necessarily have anything obvious to do with the number of moves you make. The loop code will always increase it by one, even if you're repeatedly trying to move through an impassible wall.
I don't really understand what your algorithm is supposed to be, so I don't have any detailed advice for how to fix your code.
One suggestion I have though is that you probably don't ever want to be calling methods on your Maze class without paying attention to their return values. You have a bunch of places where you call isDone but ignore the return value, which doesn't make any sense. Similarly, you should always be checking the return values from your moveX calls, to see if the move was successful or not. Otherwise you may just blunder around a bunch, without your code having any clue where you are in the maze.

Binding Scene size properties to Stage JavaFX

I need to adjust the size of a Scene to the current size of the Stage/Window.
Currently when I resize the Stage/Window the Scene resizes as well, but not to the same size. The Scene contains a StackPane.
I looked for a way to bind but didn't find anything, setters for the size parameters of the Scene also aren't available it seems. Does anyone know a way to get this done?
EDIT: Here's the Code of my Class atm.
public class SimpleSun extends Application {
// Controls
Label lblPos = new Label();
Stage primaryStage;
List<Visibility> vislist;
Scene scene;
Rectangle rect;
Circle circle;
Line line1;
Line line2;
// Variables
private double sunDiameter = 700;
private Integer center = 400;
int fovrad = 80;
int fovpxl = calculatePixelsFromRad(fovrad);
/**
* #param args
* the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
#SuppressWarnings("static-access")
#Override
public void start(final Stage stage) {
// Initialize Containers
this.primaryStage = stage;
primaryStage.setTitle("0.1-alpha -- Sun Simulation");
BorderPane root = new BorderPane();
scene = new Scene(root, 800, 800);
StackPane sp = new StackPane();
// Paint Graphics
rect = new Rectangle(center - fovpxl / 2, center - fovpxl / 2, fovpxl,
fovpxl);
circle = new Circle(400, 400, 350);
line1 = new Line(0, 0, 0, scene.getHeight());
line2 = new Line(0, 0, scene.getHeight(), 0);
// Insert Controls
sp.getChildren().addAll(circle, line1, line2, lblPos, rect);
sp.setAlignment(lblPos, Pos.TOP_LEFT);
lblPos.setStyle("margin-top:10px");
root.setCenter(sp);
primaryStage.setScene(scene);
// Binding Circle size to stage & Scene size to Stage
circle.radiusProperty().bind(
primaryStage.widthProperty().divide(2).subtract(50));
circle.centerXProperty().bind(primaryStage.widthProperty().divide(2));
circle.centerYProperty().bind(primaryStage.widthProperty().divide(2));
// Assign Handlers
line1.setOnMouseClicked(mouseHandler);
line1.setOnMouseMoved(mouseHandler);
line2.setOnMouseClicked(mouseHandler);
line2.setOnMouseMoved(mouseHandler);
circle.setOnMouseClicked(mouseHandler);
circle.setOnMouseMoved(mouseHandler);
rect.setOnMouseClicked(mouseHandler);
rect.setOnMouseMoved(mouseHandler);
scene.widthProperty().addListener(cListener);
scene.heightProperty().addListener(cListener);
// Properties
circle.setFill(Color.YELLOW);
circle.setStroke(Color.BLACK);
rect.setFill(null);
rect.setStroke(Color.BLACK);
primaryStage.show();
}
EventHandler<MouseEvent> mouseHandler = new EventHandler<MouseEvent>() {
public void handle(MouseEvent mouseEvent) {
if (mouseEvent.getEventType() == MouseEvent.MOUSE_CLICKED) {
int x = (int) mouseEvent.getSceneX();
int y = (int) mouseEvent.getSceneY();
DoubleMatrix1D pCoords = calculateXYRad(x, y);
final ISource p = new GaussianRadialSource(pCoords.get(0),
pCoords.get(1), 1, 1, 0);
MainSimulation.runSim(p, fovrad);
// DEBUG
// String message = "Source Position: " + mouseEvent.getSceneX()
// + " / " + mouseEvent.getSceneY();
// System.out.println(message);
} else if (mouseEvent.getEventType() == MouseEvent.MOUSE_MOVED) {
int x = (int) mouseEvent.getSceneX();
int y = (int) mouseEvent.getSceneY();
if (mouseEvent.getSource().getClass().equals(Circle.class)) {
((Circle) mouseEvent.getSource())
.setCursor(Cursor.CROSSHAIR);
} else if (mouseEvent.getSource().getClass().equals(Line.class)) {
((Line) mouseEvent.getSource()).setCursor(Cursor.CROSSHAIR);
} else if (mouseEvent.getSource().getClass()
.equals(Rectangle.class)) {
((Rectangle) mouseEvent.getSource())
.setCursor(Cursor.CROSSHAIR);
}
DoubleMatrix1D pCoords = calculateXYRad(x, y);
// Adjust label to new cursor position
lblPos.setText((pCoords.get(0) + " :: " + pCoords.get(1)));
// DEBUG
System.out.println("x: " + pCoords.get(0) + ", y: "
+ pCoords.get(1));
}
}
};
ChangeListener<? super Number> cListener = new ChangeListener<Number>() {
public void changed(ObservableValue<? extends Number> scenewidth,
Number oldValue, Number newValue) {
// System.out.println(primaryStage.getHeight());
// Adjust Size of Window instead of binding
if (primaryStage.getHeight() < primaryStage.getWidth()) {
primaryStage.setWidth(primaryStage.getHeight());
center = (int) (primaryStage.getHeight() / 2);
sunDiameter = primaryStage.getHeight() - 100;
}
if (primaryStage.getWidth() < primaryStage.getHeight()) {
primaryStage.setHeight(primaryStage.getWidth());
center = (int) (primaryStage.getWidth() / 2);
sunDiameter = primaryStage.getWidth() - 100;
}
// Adjust Center and Sun Diameter to new Window Size
repaintSimpleSun();
System.out.println(primaryStage.getWidth() + " " + primaryStage.getHeight());
System.out.println(scene.getWidth() + " " + scene.getHeight());
System.out.println(center + " " + sunDiameter);
}
};
private DoubleMatrix1D calculateXYRad(int x, int y) {
double X = ((x - center) * (Units.SUN_HALF_DIAMETER_RAD * 2.0) / sunDiameter);
double Y = ((y - center) * (Units.SUN_HALF_DIAMETER_RAD * 2.0) / sunDiameter);
return DoubleFactory1D.dense.make(new double[] { X, Y });
}
private int calculatePixelsFromRad(int rad) {
int pixels = (int) ((sunDiameter) / (Units.SUN_HALF_DIAMETER_RAD * 2) * rad);
// System.out.println(pixels);
return pixels;
}
private void repaintSimpleSun() {
fovpxl = calculatePixelsFromRad(fovrad);
rect.setHeight(fovpxl);
rect.setWidth(fovpxl);
rect.setX(center - (fovpxl / 2));
rect.setY(center - (fovpxl / 2));
line1.setEndY(primaryStage.getWidth());
line2.setEndX(primaryStage.getHeight());
}
}

How to run processing script on multiple frames in a folder

Using processing I am trying to run a script that will process a folder full of frames.
The script is a combination of PixelSortFrames and SortThroughSeamCarving.
I am new to processing and what I want does not seems to be working. I would like the script to run back through and choose the following file in the folder to be processed. At the moment it stops at the end and does not return to start on next file (there are three other modules also involved).
Any help would be much appreciated. :(
/* ASDFPixelSort for video frames v1.0
Original ASDFPixelSort by Kim Asendorf <http://kimasendorf.com>
https://github.com/kimasendorf/ASDFPixelSort
Fork by dx <http://dequis.org> and chinatsu <http://360nosco.pe>
// Main configuration
String basedir = ".../Images/Seq_002"; // Specify the directory in which the frames are located. Use forward slashes.
String fileext = ".jpg"; // Change to the format your images are in.
int resumeprocess = 0; // If you wish to resume a previously stopped process, change this value.
boolean reverseIt = true;
boolean saveIt = true;
int mode = 2; // MODE: 0 = black, 1 = bright, 2 = white
int blackValue = -10000000;
int brightnessValue = -1;
int whiteValue = -6000000;
// -------
PImage img, original;
float[][] sums;
int bottomIndex = 0;
String[] filenames;
int row = 0;
int column = 0;
int i = 0;
java.io.File folder = new java.io.File(dataPath(basedir));
java.io.FilenameFilter extfilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(fileext);
}
};
void setup() {
if (resumeprocess > 0) {i = resumeprocess - 1;frameCount = i;}
size(1504, 1000); // Resolution of the frames. It's likely there's a better way of doing this..
filenames = folder.list(extfilter);
size(1504, 1000);
println(" " + width + " x " + height + " px");
println("Creating buffer images...");
PImage hImg = createImage(1504, 1000, RGB);
PImage vImg = createImage(1504, 1000, RGB);
// draw image and convert to grayscale
if (i +1 > filenames.length) {println("Uh.. Done!"); System.exit(0);}
img = loadImage(basedir+"/"+filenames[i]);
original = loadImage(basedir+"/"+filenames[i]);
image(img, 0, 0);
filter(GRAY);
img.loadPixels(); // updatePixels is in the 'runKernals'
// run kernels to create "energy map"
println("Running kernals on image...");
runKernels(hImg, vImg);
image(img, 0, 0);
// sum pathways through the image
println("Getting sums through image...");
sums = getSumsThroughImage();
image(img, 0, 0);
loadPixels();
// get start point (smallest value) - this is used to find the
// best seam (starting at the lowest energy)
bottomIndex = width/2;
// bottomIndex = findStartPoint(sums, 50);
println("Bottom index: " + bottomIndex);
// find the pathway with the lowest information
int[] path = new int[height];
path = findPath(bottomIndex, sums, path);
for (int bi=0; bi<width; bi++) {
// get the pixels of the path from the original image
original.loadPixels();
color[] c = new color[path.length]; // create array of the seam's color values
for (int i=0; i<c.length; i++) {
try {
c[i] = original.pixels[i*width + path[i] + bi]; // set color array to values from original image
}
catch (Exception e) {
// when we run out of pixels, just ignore
}
}
println(" " + bi);
c = sort(c); // sort (use better algorithm later)
if (reverseIt) {
c = reverse(c);
}
for (int i=0; i<c.length; i++) {
try {
original.pixels[i*width + path[i] + bi] = c[i]; // reverse! set the pixels of the original from sorted array
}
catch (Exception e) {
// when we run out of pixels, just ignore
}
}
original.updatePixels();
}
// when done, update pixels to display
updatePixels();
// display the result!
image(original, 0, 0);
if (saveIt) {
println("Saving file...");
//filenames = stripFileExtension(filenames);
save("results/SeamSort_" + filenames + ".tiff");
}
println("DONE!");
}
// strip file extension for saving and renaming
String stripFileExtension(String s) {
s = s.substring(s.lastIndexOf('/')+1, s.length());
s = s.substring(s.lastIndexOf('\\')+1, s.length());
s = s.substring(0, s.lastIndexOf('.'));
return s;
}
This code works by processing all images in the selected folder
String basedir = "D:/things/pixelsortframes"; // Specify the directory in which the frames are located. Use forward slashes.
String fileext = ".png"; // Change to the format your images are in.
int resumeprocess = 0; // If you wish to resume a previously stopped process, change this value.
int mode = 1; // MODE: 0 = black, 1 = bright, 2 = white
int blackValue = -10000000;
int brightnessValue = -1;
int whiteValue = -6000000;
PImage img;
String[] filenames;
int row = 0;
int column = 0;
int i = 0;
java.io.File folder = new java.io.File(dataPath(basedir));
java.io.FilenameFilter extfilter = new java.io.FilenameFilter() {
boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(fileext);
}
};
void setup() {
if (resumeprocess > 0) {i = resumeprocess - 1;frameCount = i;}
size(1920, 1080); // Resolution of the frames. It's likely there's a better way of doing this..
filenames = folder.list(extfilter);
}
void draw() {
if (i +1 > filenames.length) {println("Uh.. Done!"); System.exit(0);}
row = 0;
column = 0;
img = loadImage(basedir+"/"+filenames[i]);
image(img,0,0);
while(column < width-1) {
img.loadPixels();
sortColumn();
column++;
img.updatePixels();
}
while(row < height-1) {
img.loadPixels();
sortRow();
row++;
img.updatePixels();
}
image(img,0,0);
saveFrame(basedir+"/out/"+filenames[i]);
println("Frames processed: "+frameCount+"/"+filenames.length);
i++;
}
essentially I want to do the same thing only with a different image process but my code is not doing this to all with in the folder... just one file.
You seem to be confused about what the setup() function does. It runs once, and only once, at the beginning of your code's execution. You don't have any looping structure for processing the other files, so it's no wonder that it only processes the first one. Perhaps wrap the entire thing in a for loop? It looks like you kind of thought about this, judging by the global variable i, but you never increment it to go to the next image and you overwrite its value in several for loops later anyway.

Processing and Twitter4j, problems searching for tweets

I have processing 2.0 and twitter4j 3.0.3; when I try to run the program I get the error message
"The function "getTweet() does not exist".
I have tried getStatuses instead to no avail, I get the same error message that the function does not exist.
Help?
ArrayList<String> words = new ArrayList();
TwitterFactory twitterFactory;
Twitter twitter;
void setup() {
size(500, 500);
background(0);
smooth();
connectTwitter();
}
void draw() {
//draw fade rectangle
fill(0, 1);
rect(0, 0, width, height);
//draw arraylist words
int i = (frameCount % words.size());
String word = words.get(i);
fill(255, random(50, 150));
textSize(random(10, 30));
text(word, random(width), random(height));
}
// Initial connection
void connectTwitter() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey("FvnrJfRMsMUCEhL0xxPegQ");
cb.setOAuthConsumerSecret("ZSnKgo6EQmq9wVd5gCMbufcMP5ztFuQhVwKpJvDhAY");
cb.setOAuthAccessToken("274686457-ZiYxpWchtcwHod7UXPjLCj18djl9CyNrk1HMqtQx");
cb.setOAuthAccessTokenSecret("kafd2QHznAu4Mu0R9x5HNyeyA4J3UwCOpETQYeDU");
twitterFactory = new TwitterFactory(cb.build());
twitter = twitterFactory.getInstance();
Query query = new Query("#BioshockInfinite");
query.setCount(100);
try {
QueryResult result = twitter.search(query);
ArrayList Status = (ArrayList) result.getTweet();
for (int i = 0; i < tweet.size(); i++) {
Status s = (Status) tweet.get(i);
User user = s.getUser;
String name = user.getName();
String msg = s.getText();
Date d = s.getCreatedAt();
println("Tweet by" + user + "at" + d + ":" + msg);
}
}
catch (TwitterException te) {
println("Couldn't connect:" + te);
}
}
I changed the line
ArrayList Status = (ArrayList) result.getTweet();
(which looks a bit odd anyway) to
List<Status> tweets = result.getTweets();
and I get Results now.
Eclipse showed an error that getTweet() wants a List to store the Tweets.

Resources