Search Results

Search found 5671 results on 227 pages for 'final'.

Page 12/227 | < Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >

  • LibGDX Box2D Body and Sprite AND DebugRenderer out of sync

    - by Free Lancer
    I am having a couple issues with Box2D bodies. I have a GameObject holding a Sprite and Body. I use a ShapeRenderer to draw an outline of the Body's and Sprite's bounding boxes. I also added a Box2DDebugRenderer to make sure everything's lining up properly. My problem is the Sprite and Body at first overlap perfectly, but as I turn the Body moves a bit off the sprite then comes back when the Car is facing either North or South. Here's an image of what I mean: (Not sure what that line is, first time to show up) BLUE is the Body, RED is the Sprite, PURPLE is the Box2DDebugRenderer. Also, you probably noticed a purple square in the top right corner. Well that's the Car drawn by the Box2D Debug Renderer. I thought it might be the camera but I've been playing with the Cameras for hours and nothing seems to work. All give me weird results. Here's my code: Screen: public void show() { // --------------------- SETUP ALL THE CAMERA STUFF ------------------------------ // battleStage = new Stage( 720, 480, false ); // Setup the camera. In Box2D we operate on a meter scale, pixels won't do it. So we use // an Orthographic camera with a Viewport of 24 meters in width and 16 meters in height. battleStage.setCamera( new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT ) ); battleStage.getCamera().position.set( CAM_METER_WIDTH / 2, CAM_METER_HEIGHT / 2, 0 ); // The Box2D Debug Renderer will handle rendering all physics objects for debugging debugger = new Box2DDebugRenderer( true, true, true, true ); //debugCam = new OrthographicCamera( CAM_METER_WIDTH, CAM_METER_HEIGHT ); } public void render(float delta) { // Update the Physics World, use 1/45 for something around 45 Frames/Second for mobile devices physicsWorld.step( 1/45.0f, 8, 3 ); // 1/45 for devices // Set the Camera matrices and clear the screen Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT); battleStage.getCamera().update(); // Draw game objects here battleStage.act(delta); battleStage.draw(); // Again update the Camera matrices and call the debug renderer debugCam.update(); debugger.render( physicsWorld, debugCam.combined); // Vehicle handles its own interaction with the HUD // update all Actors movements in the game Stage hudStage.act( delta ); // Draw each Actor onto the Scene at their new positions hudStage.draw(); } Car: (extends Actor) public Car( Texture texture, float posX, float posY, World world ) { super( "Car" ); mSprite = new Sprite( texture ); mSprite.setSize( WIDTH * Consts.PIXEL_METER_RATIO, HEIGHT * Consts.PIXEL_METER_RATIO ); mSprite.setOrigin( mSprite.getWidth()/2, mSprite.getHeight()/2); // set the origin to be at the center of the body mSprite.setPosition( posX * Consts.PIXEL_METER_RATIO, posY * Consts.PIXEL_METER_RATIO ); // place the car in the center of the game map FixtureDef carFixtureDef = new FixtureDef(); mBody = Physics.createBoxBody( BodyType.DynamicBody, carFixtureDef, mSprite ); } public void draw() { mSprite.setPosition( mBody.getPosition().x * Consts.PIXEL_METER_RATIO, mBody.getPosition().y * Consts.PIXEL_METER_RATIO ); mSprite.setRotation( MathUtils.radiansToDegrees * mBody.getAngle() ); // draw the sprite mSprite.draw( batch ); } Physics: (Create the Body) public static Body createBoxBody( final BodyType pBodyType, final FixtureDef pFixtureDef, Sprite pSprite ) { float pRotation = 0; float pWidth = pSprite.getWidth(); float pHeight = pSprite.getHeight(); final BodyDef boxBodyDef = new BodyDef(); boxBodyDef.type = pBodyType; boxBodyDef.position.x = pSprite.getX() / Consts.PIXEL_METER_RATIO; boxBodyDef.position.y = pSprite.getY() / Consts.PIXEL_METER_RATIO; // Temporary Box shape of the Body final PolygonShape boxPoly = new PolygonShape(); final float halfWidth = pWidth * 0.5f / Consts.PIXEL_METER_RATIO; final float halfHeight = pHeight * 0.5f / Consts.PIXEL_METER_RATIO; boxPoly.setAsBox( halfWidth, halfHeight ); // set the anchor point to be the center of the sprite pFixtureDef.shape = boxPoly; final Body boxBody = BattleScreen.getPhysicsWorld().createBody(boxBodyDef); boxBody.createFixture(pFixtureDef); } Sorry for all the code and long description but it's hard to pin down what exactly might be causing the problem.

    Read the article

  • How handle nifty initialization in a Slick2D state based game?

    - by nathan
    I'm using Slick2D and Nifty GUI. I decided to use a state based approach for my game and since i want to use Nifty GUI, i use the classes NiftyStateBasedGame for the main and NiftyOverlayBasicGameState for the states. As the description say, i'm suppose to initialize the GUI in the method initGameAndGUI on my states, no problem: @Override protected void initGameAndGUI(GameContainer gc, StateBasedGame sbg) throws SlickException { initNifty(gc, sbg) } It works great when i have only one state but if i'm doing a call to initNifty several times from different states, it will raise the following exception: org.bushe.swing.event.EventServiceExistsException: An event service by the name NiftyEventBusalready exists. Perhaps multiple threads tried to create a service about the same time? at org.bushe.swing.event.EventServiceLocator.setEventService(EventServiceLocator.java:123) at de.lessvoid.nifty.Nifty.initalizeEventBus(Nifty.java:221) at de.lessvoid.nifty.Nifty.initialize(Nifty.java:201) at de.lessvoid.nifty.Nifty.<init>(Nifty.java:142) at de.lessvoid.nifty.slick2d.NiftyCarrier.initNifty(NiftyCarrier.java:94) at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:332) at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:299) at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:280) at de.lessvoid.nifty.slick2d.NiftyOverlayBasicGameState.initNifty(NiftyOverlayBasicGameState.java:264) The initializeEventBus that raise the exception is called from the Nifty constructor and a new Nifty object is created within the initNifty method: public void initNifty( final SlickRenderDevice renderDevice, final SlickSoundDevice soundDevice, final SlickInputSystem inputSystem, final TimeProvider timeProvider) { if (isInitialized()) { throw new IllegalStateException("The Nifty-GUI was already initialized. Its illegal to do so twice."); } final InputSystem activeInputSystem; if (relayInputSystem == null) { activeInputSystem = inputSystem; } else { activeInputSystem = relayInputSystem; relayInputSystem.setTargetInputSystem(inputSystem); } nifty = new Nifty(renderDevice, soundDevice, activeInputSystem, timeProvider); } Is this a bug in the nifty for slick2d implementation or am i missing something? How am i supposed to handle nifty initialization over multiple states?

    Read the article

  • How to scroll in the physical world AndEngine?

    - by Esteban Quintero
    I am using andengine to make a game where a sprite (player) is going up across the stage, this is my world. final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); /* Create two sprits and add it to the scene. */ this.mScene.setBackground(autoParallaxBackground); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); The problem is that if the sprite reaches up and hits the wall, as I scroll here?

    Read the article

  • How do I scroll to follow my sprite in the physical world?

    - by Esteban Quintero
    I am using andengine to make a game where a sprite (player) is going up across the stage, and I want the camera to stay centred on the sprite the entire time. This is my world so far: final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); /* Create two sprits and add it to the scene. */ this.mScene.setBackground(autoParallaxBackground); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); The problem is that when the sprite reaches the top wall, it crashes. How can I fix this?

    Read the article

  • Java regex patterns - compile time constants or instance members?

    - by KepaniHaole
    Currently, I have a couple of singleton objects where I'm doing matching on regular expressions, and my Patterns are defined like so: class Foobar { private final Pattern firstPattern = Pattern.compile("some regex"); private final Pattern secondPattern = Pattern.compile("some other regex"); // more Patterns, etc. private Foobar() {} public static Foobar create() { /* singleton stuff */ } } But I was told by someone the other day that this is bad style, and Patterns should always be defined at the class level, and look something like this instead: class Foobar { private static final Pattern FIRST_PATTERN = Pattern.compile("some regex"); private static final Pattern SECOND_PATTERN = Pattern.compile("some other regex"); // more Patterns, etc. private Foobar() {} public static Foobar create() { /* singleton stuff */ } } The lifetime of this particular object isn't that long, and my main reason for using the first approach is because it doesn't make sense to me to hold on to the Patterns once the object gets GC'd. Any suggestions / thoughts?

    Read the article

  • Java: how to do fast copy of a BufferedImage's pixels? (include unit test)

    - by WizardOfOdds
    I want to do a copy (of a rectangle area) of the ARGB values from a source BufferedImage into a destination BufferedImage. No compositing should be done: if I copy a pixel with an ARGB value of 0x8000BE50 (alpha value at 128), then the destination pixel must be exactly 0x8000BE50, totally overriding the destination pixel. I've got a very precise question and I made a unit test to show what I need. The unit test is fully functional and self-contained and is passing fine and is doing precisely what I want. However, I want a faster and more memory efficient method to replace copySrcIntoDstAt(...). That's the whole point of my question: I'm not after how to "fill" the image in a faster way (what I did is just an example to have a unit test). All I want is to know what would be a fast and memory efficient way to do it (ie fast and not creating needless objects). The proof-of-concept implementation I've made is obviously very memory efficient, but it is slow (doing one getRGB and one setRGB for every pixel). Schematically, I've got this: (where A indicates corresponding pixels from the destination image before the copy) AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA And I want to have this: AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAABBBBAAA AAAAAAAAAAAAABBBBAAA AAAAAAAAAAAAAAAAAAAA where 'B' represents the pixels from the src image. I'm looking for an exact replacement of the method, not for an API link/quote. import org.junit.Test; import java.awt.image.BufferedImage; import static org.junit.Assert.*; public class TestCopy { private static final int COL1 = 0x8000BE50; // alpha at 128 private static final int COL2 = 0x1732FE87; // alpha at 23 @Test public void testPixelsCopy() { final BufferedImage src = new BufferedImage( 5, 5, BufferedImage.TYPE_INT_ARGB ); final BufferedImage dst = new BufferedImage( 20, 20, BufferedImage.TYPE_INT_ARGB ); convenienceFill( src, COL1 ); convenienceFill( dst, COL2 ); copySrcIntoDstAt( src, dst, 3, 4 ); for (int x = 0; x < dst.getWidth(); x++) { for (int y = 0; y < dst.getHeight(); y++) { if ( x >= 3 && x <= 7 && y >= 4 && y <= 8 ) { assertEquals( COL1, dst.getRGB(x,y) ); } else { assertEquals( COL2, dst.getRGB(x,y) ); } } } } // clipping is unnecessary private static void copySrcIntoDstAt( final BufferedImage src, final BufferedImage dst, final int dx, final int dy ) { // TODO: replace this by a much more efficient method for (int x = 0; x < src.getWidth(); x++) { for (int y = 0; y < src.getHeight(); y++) { dst.setRGB( dx + x, dy + y, src.getRGB(x,y) ); } } } // This method is just a convenience method, there's // no point in optimizing this method, this is not what // this question is about private static void convenienceFill( final BufferedImage bi, final int color ) { for (int x = 0; x < bi.getWidth(); x++) { for (int y = 0; y < bi.getHeight(); y++) { bi.setRGB( x, y, color ); } } } }

    Read the article

  • handling filename* parameters with spaces via RFC 5987 results in '+' in filenames

    - by Peter Friend
    I have some legacy code I am dealing with (so no I can't just use a URL with an encoded filename component) that allows a user to download a file from our website. Since our filenames are often in many different languages they are all stored as UTF-8. I wrote some code to handle the RFC5987 conversion to a proper filename* parameter. This works great until I have a filename with non-ascii characters and spaces. Per RFC, the space character is not part of attr_char so it gets encoded as %20. I have new versions of Chrome as well as Firefox and they are all converting to %20 to + on download. I have tried not encoding the space and putting the encoded filename in quotes and get the same result. I have sniffed the response coming from the server to verify that the servlet container wasn't mucking with my headers and they look correct to me. The RFC even has examples that contain %20. Am I missing something, or do all of these browsers have a bug related to this? Many thanks in advance. The code I use to encode the filename is below. Peter public static boolean bcsrch(final char[] chars, final char c) { final int len = chars.length; int base = 0; int last = len - 1; /* Last element in table */ int p; while (last >= base) { p = base + ((last - base) >> 1); if (c == chars[p]) return true; /* Key found */ else if (c < chars[p]) last = p - 1; else base = p + 1; } return false; /* Key not found */ } public static String rfc5987_encode(final String s) { final int len = s.length(); final StringBuilder sb = new StringBuilder(len << 1); final char[] digits = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'}; final char[] attr_char = {'!','#','$','&','\'','+','-','.','0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','^','_','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','|', '~'}; for (int i = 0; i < len; ++i) { final char c = s.charAt(i); if (bcsrch(attr_char, c)) sb.append(c); else { final char[] encoded = {'%', 0, 0}; encoded[1] = digits[0x0f & (c >>> 4)]; encoded[2] = digits[c & 0x0f]; sb.append(encoded); } } return sb.toString(); } Update Here is a screen shot of the download dialog I get for a file with Chinese characters with spaces as mentioned in my comment.

    Read the article

  • Tinkerforge Rotation/LCD & JavaFX Plans

    - by Geertjan
    The first time I integrated two Tinkerforge bricklets, the day before yesterday, was pretty cool: import com.tinkerforge.BrickMaster; import com.tinkerforge.BrickletLCD20x4; import com.tinkerforge.BrickletRotaryPoti; import com.tinkerforge.IPConnection; import java.util.Calendar; public class TFConnectionDemo { private static final String HOST = "localhost"; private static final int PORT = 4223; private static final String MASTERBRICKUID = "somethingabc"; private static final String LCDUID = "somethingabc"; private static final String ROTIUID = "somethingabc"; private static IPConnection ipc; private static BrickMaster master = new BrickMaster(MASTERBRICKUID); private static BrickletLCD20x4 lcd = new BrickletLCD20x4(LCDUID); private static BrickletRotaryPoti poti = new BrickletRotaryPoti(ROTIUID); public static void main(String[] args) { try { ipc = new IPConnection(HOST, PORT); ipc.addDevice(master); ipc.addDevice(lcd); ipc.addDevice(poti); poti.setPositionCallbackPeriod(50); poti.addListener(new BrickletRotaryPoti.PositionListener() { @Override public void position(short position) { lcd.clearDisplay(); Calendar cal = Calendar.getInstance(); lcd.writeLine((short) 0, (short) 0, cal.getTime().toString()); lcd.writeLine((short) 1, (short) 0, "Rotation: " + position); } }); } catch (Exception e) { } } } The result is that the display text in the LCD bricklet changes while I turn the rotation bricklet: Now imagine that you have some JavaFX charts and, while you turn the rotation bricklet (i.e., the dial thing that I'm turning above), the values of the charts change. That would be pretty cool because you'd be able to animate the JavaFX charts by rotating an object externally, i.e., without even touching the keyboard. That would be pretty cool to see and shouldn't be hard to implement.

    Read the article

  • Unit testing time-bound code

    - by maasg
    I'm currently working on an application that does a lot of time-bound operations. That is, based on long now = System.currentTimeMillis();, and combined with an scheduler, it will calculate periods of time that parametrize the execution of some operations. e.g.: public void execute(...) { // executed by an scheduler each x minutes final int now = (int) TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()); final int alignedTime = now - now % getFrequency() ; final int startTime = alignedTime - 2 * getFrequency(); final int endTimeSecs = alignedTime - getFrequency(); uploadData(target, startTime, endTimeSecs); } Most parts of the application are unit-tested independently of time (in this case, uploadData has a natural unit test), but I was wondering about best practices for testing time-bound parts that rely on System.currentTimeMillis() ?

    Read the article

  • Android sqlight problem always null

    - by yoav.str
    every time i am using the db its null and i just dont get it i use this code for the SQL when I have quarry : public class GameSQLHelper { static final String[] COUNTRIES = new String[] { "Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra" }; private static final String DB_PATH = "/countryCityGame/databases/"; private static final String DATABASE_NAME = "events.db"; private static final int DATABASE_VERSION = 1; private final Context mCtx; // Table name public static final String TABLE = "myDataBase"; // Columns public static final String LETTER = "letter"; public static final String TYPE = "type"; public static final String VALUE = "value"; //my database SQLiteDatabase myDataBase; private static class DatabaseHelper extends SQLiteOpenHelper { private static final String TAG = null; DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String sql = "create table " + TABLE + "( " + BaseColumns._ID + " integer primary key autoincrement, " + LETTER + " text not null, " + TYPE + " text not null," + VALUE + " text not null );"; Log.d("EventsData", "onCreate: " + sql); db.execSQL(sql); insertValuesToDB(db); } private void insertValuesToDB(SQLiteDatabase db) { if (db == null){ } else{ db.execSQL("INSERT INTO " + TABLE + " ("+LETTER+","+ TYPE +"," + VALUE +")" + " VALUES ('A', 'country', 'Angola');"); ContentValues initialValues = new ContentValues(); for (int i = 0 ; i < COUNTRIES.length ; i++){ Character tmp = (Character)COUNTRIES[i].charAt(0); initialValues.put(VALUE, COUNTRIES[i]); initialValues.put(TYPE, "country"); initialValues.put(LETTER,tmp.toString(tmp)); db.insert(TABLE, null, initialValues); } } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS notes"); onCreate(db); } } /** * Constructor - takes the context to allow the database to be * opened/created * * @param ctx the Context within which to work */ public GameSQLHelper(Context ctx) { this.mCtx = ctx; } public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { if (oldVersion >= newVersion) return; String sql = null; if (oldVersion == 1) sql = "alter table " + TABLE + " add note text;"; if (oldVersion == 2) sql = ""; Log.d("EventsData", "onUpgrade : " + sql); if (sql != null) db.execSQL(sql); } public void openDataBase() throws SQLException{ //Open the database String myPath = DB_PATH + DATABASE_NAME; myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE); } public boolean existInDataBase(String serchStr ){ Cursor c = null ; try{ openDataBase(); c = myDataBase.query(true, TABLE, new String[] {TYPE }, VALUE + "=" + serchStr, null, null, null, null, null); } catch(Exception e){ Log.d("sqlExacption", e.getMessage()); } if (c == null) return false; return true; } } whenever i call this class (i hold an instace of him initialized : mDbHelper = new GameSQLHelper(this); where this is an activity ) i always get my mDbHelper as null how can i change it , its my first time working with sql outside of mysql platform so i am kind of having problmes understanding tje concept , and the android notepad example didnt help me .

    Read the article

  • How do I scroll in the physical world?

    - by Esteban Quintero
    I am using andengine to make a game where a sprite (player) is going up across the stage, this is my world. final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2, vertexBufferObjectManager); final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2, CAMERA_HEIGHT, vertexBufferObjectManager); final FixtureDef wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.5f, 0.5f); PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, left, BodyType.StaticBody, wallFixtureDef); PhysicsFactory.createBoxBody(this.mPhysicsWorld, right, BodyType.StaticBody, wallFixtureDef); /* Create two sprits and add it to the scene. */ this.mScene.setBackground(autoParallaxBackground); this.mScene.attachChild(ground); this.mScene.attachChild(roof); this.mScene.attachChild(left); this.mScene.attachChild(right); this.mScene.registerUpdateHandler(this.mPhysicsWorld); The problem is that if the sprite reaches up and hits the wall, as I scroll here?

    Read the article

  • Smooth Camera Zoom Factor Change

    - by Siddharth
    I have game play scene in which user can zoom in and out. For which I used smooth camera in the following manner. public static final int CAMERA_WIDTH = 1024; public static final int CAMERA_HEIGHT = 600; public static final float MAXIMUM_VELOCITY_X = 400f; public static final float MAXIMUM_VELOCITY_Y = 400f; public static final float ZOOM_FACTOR_CHANGE = 1f; mSmoothCamera = new SmoothCamera(0, 0, Constants.CAMERA_WIDTH, Constants.CAMERA_HEIGHT, Constants.MAXIMUM_VELOCITY_X, Constants.MAXIMUM_VELOCITY_Y, Constants.ZOOM_FACTOR_CHANGE); mSmoothCamera.setBounds(0f, 0f, Constants.CAMERA_WIDTH, Constants.CAMERA_HEIGHT); But above thing create problem for me. When user perform zoom in and leave game play scene then other scene behaviour not look good. I already set zoom factor to 1 for this purpose. But now it show camera translation in other scene. Because scene switching time it so much small that player can easily saw translation of camera that I don't want to show. After camera reposition, everything works perfect but how to set camera its proper position. For example my loading text move from bottom to top or vice versa based on camera movement. Any more detail you want then I can able to give you.

    Read the article

  • How to use Parcel in Android?

    - by Mike
    I'm trying to use Parcel to write and then read back a Parcelable. For some reason, when I read the object back from the file, it's coming back as null. public void testFoo() { final Foo orig = new Foo("blah blah"); // Wrote orig to a parcel and then byte array final Parcel p1 = Parcel.obtain(); p1.writeValue(orig); final byte[] bytes = p1.marshall(); // Check to make sure that the byte array seems to contain a Parcelable assertEquals(4, bytes[0]); // Parcel.VAL_PARCELABLE // Unmarshall a Foo from that byte array final Parcel p2 = Parcel.obtain(); p2.unmarshall(bytes, 0, bytes.length); final Foo result = (Foo) p2.readValue(Foo.class.getClassLoader()); assertNotNull(result); // FAIL assertEquals( orig.str, result.str ); } protected static class Foo implements Parcelable { protected static final Parcelable.Creator<Foo> CREATOR = new Parcelable.Creator<Foo>() { public Foo createFromParcel(Parcel source) { final Foo f = new Foo(); f.str = (String) source.readValue(Foo.class.getClassLoader()); return f; } public Foo[] newArray(int size) { throw new UnsupportedOperationException(); } }; public String str; public Foo() { } public Foo( String s ) { str = s; } public int describeContents() { return 0; } public void writeToParcel(Parcel dest, int ignored) { dest.writeValue(str); } } What am I missing? UPDATE: To simplify the test I've removed the reading and writing of files in my original example.

    Read the article

  • Can't get past 2542 Threads in Java on 4GB iMac OSX 10.6.3 Snow Leopard (32bit)

    - by fuzzy lollipop
    I am running the following program trying to figure out how to configure my JVM to get the maximum number of threads my machine can support. For those that might not know, Snow Leopard ships with Java 6. I tried starting it with defaults, and the following command lines, I always get the Out of Memory Error at Thread 2542 no matter what the JVM options are set to. java TestThreadStackSizes 100000 java -Xss1024 TestThreadStackSizes 100000 java -Xmx128m -Xss1024 TestThreadStackSizes 100000 java -Xmx2048m -Xss1024 TestThreadStackSizes 100000 java -Xmx2048m -Xms2048m -Xss1024 TestThreadStackSizes 100000 no matter what I pass it, I get the same results, Out of Memory Error at 2542 public class TestThreadStackSizes { public static void main(final String[] args) { Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { public void uncaughtException(final Thread t, final Throwable e) { System.err.println(e.getMessage()); System.exit(1); } }); int numThreads = 1000; if (args.length == 1) { numThreads = Integer.parseInt(args[0]); } for (int i = 0; i < numThreads; i++) { try { Thread t = new Thread(new SleeperThread(i)); t.start(); } catch (final OutOfMemoryError e) { throw new RuntimeException(String.format("Out of Memory Error on Thread %d", i), e); } } } private static class SleeperThread implements Runnable { private final int i; private SleeperThread(final int i) { this.i = i; } public void run() { try { System.out.format("Thread %d about to sleep\n", this.i); Thread.sleep(1000 * 60 * 60); } catch (final InterruptedException e) { throw new RuntimeException(e); } } } } Any ideas on now I can affect these results?

    Read the article

  • Sending multi-part email from Google App Engine using Spring's JavaMailSender fails

    - by hleinone
    It works without the multi-part (modified from the example in Spring documentation): final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper( mimeMessage); message.setTo(toAddress); message.setFrom(fromAddress); message.setSubject(subject); final String htmlText = FreeMarkerTemplateUtils .processTemplateIntoString(configuration .getTemplate(htmlTemplate), model); message.setText(htmlText, true); } }; mailSender.send(preparator); But once I change it to: final MimeMessagePreparator preparator = new MimeMessagePreparator() { public void prepare(final MimeMessage mimeMessage) throws Exception { final MimeMessageHelper message = new MimeMessageHelper( mimeMessage, true); ... message.setText(plainText, htmlText); } }; mailSender.send(preparator); I get: Failed message 1: javax.mail.MessagingException: Converting attachment data failed at com.google.appengine.api.mail.stdimpl.GMTransport.sendMessage(GMTransport.java:231) at org.springframework.mail.javamail.JavaMailSenderImpl.doSend(JavaMailSenderImpl.java:402) ... This is especially difficult since the GMTransport is proprietary Google class and no sources are available, which would make it a bit easier to debug. Anyone have any ideas what to try next? My bean config, for helping you to help me: <bean id="mailSender" class="org.springframework.mail.javamail.JavaMailSenderImpl" p:username="${mail.username}" p:password="${mail.password}" p:protocol="gm" />

    Read the article

  • JCo | How to iterate column wise

    - by cedar715
    The data from SAP is returned as a JCo.Table. However, we don't want to display ALL the columns in the VIEW. So, what we have done is, we have created a file called display.xml which has the JCO.Table columns to be displayed. The display.xml is converted to a List and each field is verified if it is present in the display list(see the code below) which is redundant from second row onwards. final Table outputTable = jcoFunction.getTableParameterList(). getTable("OUTPUT_TABLE"); final int numRows = outputTable.getNumRows(); for (int i = 0; i < numRows; i++) { final FieldIterator fields = outputTable.fields(); while (fields.hasNextFields()) { final JCO.Field recordField = fields.nextField(); final String sapFieldName = recordField.getName(); final DisplayFieldDto key = new DisplayFieldDto(sapFieldName); if (displayFields.contains(key)) { System.out.println("recordField.getName() = " + recordField.getName()); final String sapFieldName = (String)recordField.getValue(); } else { // ignore the field. } } } What is the better way to filter the fields in JCo? Can I iterate column wise? Thank you :)

    Read the article

  • array of structures, or structure of arrays?

    - by Jason S
    Hmmm. I have a table which is an array of structures I need to store in Java. The naive don't-worry-about-memory approach says do this: public class Record { final private int field1; final private int field2; final private long field3; /* constructor & accessors here */ } List<Record> records = new ArrayList<Record>(); If I end up using a large number ( 106 ) of records, where individual records are accessed occasionally, one at a time, how would I figure out how the preceding approach (an ArrayList) would compare with an optimized approach for storage costs: public class OptimizedRecordStore { final private int[] field1; final private int[] field2; final private long[] field3; Record getRecord(int i) { return new Record(field1[i],field2[i],field3[i]); } /* constructor and other accessors & methods */ } edit: assume the # of records is something that is changed infrequently or never I'm probably not going to use the OptimizedRecordStore approach, but I want to understand the storage cost issue so I can make that decision with confidence. obviously if I add/change the # of records in the OptimizedRecordStore approach above, I either have to replace the whole object with a new one, or remove the "final" keyword. kd304 brings up a good point that was in the back of my mind. In other situations similar to this, I need column access on the records, e.g. if field1 and field2 are "time" and "position", and it's important for me to get those values as an array for use with MATLAB, so I can graph/analyze them efficiently.

    Read the article

  • Using static variables for Strings

    - by Vivart
    below content is taken from Best practice: Writing efficient code but i didn't understand why private static String x = "example"; faster than private static final String x ="example"; Can anybody explain this. Using static variables for Strings When you define static fields (also called class fields) of type String, you can increase application speed by using static variables (not final) instead of constants (final). The opposite is true for primitive data types, such as int. For example, you might create a String object as follows: private static final String x = "example"; For this static constant (denoted by the final keyword), each time that you use the constant, a temporary String instance is created. The compiler eliminates "x" and replaces it with the string "example" in the bytecode, so that the BlackBerry® Java® Virtual Machine performs a hash table lookup each time that you reference "x". In contrast, for a static variable (no final keyword), the String is created once. The BlackBerry JVM performs the hash table lookup only when it initializes "x", so access is faster. private static String x = "example"; You can use public constants (that is, final fields), but you must mark variables as private.

    Read the article

  • Android SQLite Problem: Program Crash When Try a Query!

    - by Skatephone
    Hi i have a problem programming with android SDK 1.6. I'm doing the same things of the "notepad exaple" but the programm crash when i try some query. If i try to do a query directly in to the DatabaseHelper create() metod it goes, but out of this function it doesn't. Do you have any idea? this is the source: public class DbAdapter { public static final String KEY_NAME = "name"; public static final String KEY_TOT_DAYS = "totdays"; public static final String KEY_ROWID = "_id"; private static final String TAG = "DbAdapter"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; private static final String DATABASE_NAME = "flowratedb"; private static final String DATABASE_TABLE = "girl_data"; private static final String DATABASE_TABLE_2 = "girl_cyle"; private static final int DATABASE_VERSION = 2; /** * Database creation sql statement */ private static final String DATABASE_CREATE = "create table "+DATABASE_TABLE+" (id integer, name text not null, totdays int);"; private static final String DATABASE_CREATE_2 = "create table "+DATABASE_TABLE_2+" (ref_id integer, day long not null);"; private final Context mCtx; private static class DatabaseHelper extends SQLiteOpenHelper { DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); db.execSQL(DATABASE_CREATE_2); db.delete(DATABASE_TABLE, null, null); db.delete(DATABASE_TABLE_2, null, null); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE); db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE_2); onCreate(db); } } public DbAdapter(Context ctx) { this.mCtx = ctx; } public DbAdapter open() throws SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } public void close() { mDbHelper.close(); } public long createGirl(int id,String name, int totdays) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_ROWID, id); initialValues.put(KEY_NAME, name); initialValues.put(KEY_TOT_DAYS, totdays); return mDb.insert(DATABASE_TABLE, null, initialValues); } public long createGirl_fd_day(int refid, long fd) { ContentValues initialValues = new ContentValues(); initialValues.put("ref_id", refid); initialValues.put("calendar", fd); return mDb.insert(DATABASE_TABLE, null, initialValues); } public boolean updateGirl(int rowId, String name, int totdays) { ContentValues args = new ContentValues(); args.put(KEY_NAME, name); args.put(KEY_TOT_DAYS, totdays); return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } public boolean deleteGirlsData() { if (mDb.delete(DATABASE_TABLE_2, null, null)>0) if(mDb.delete(DATABASE_TABLE, null, null)>0) return true; return false; } public Bundle fetchAllGirls() { Bundle extras = new Bundle(); Cursor cur = mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_TOT_DAYS}, null, null, null, null, null); cur.moveToFirst(); int tot = cur.getCount(); extras.putInt("tot", tot); int index; for (int i=0;i<tot;i++){ index=cur.getInt(cur.getColumnIndex("_id")); extras.putString("name"+index, cur.getString(cur.getColumnIndex("name"))); extras.putInt("totdays"+index, cur.getInt(cur.getColumnIndex("totdays"))); } cur.close(); return extras; } public Cursor fetchGirl(int rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME, KEY_TOT_DAYS}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public Cursor fetchGirlCD(int rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_TABLE_2, new String[] {"ref_id", "day"}, "ref_id=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } } Tank's Valerio From Italy :)

    Read the article

  • Clicking Elements in Android Doesn't Display the Correct Values

    - by Devin
    I apologize if this code looks a bit like a mess (considering the length); I figured I'd just include everything that goes on in my program at the moment. I'm attempting to create a fairly simple Tic Tac Toe app for Android. I've set up my UI nicely so far so that there are a "grid" of TextViews. As a sort of "debug" right now, I have it so that when one clicks on a TextView, it should display the value of buttonId in a message box. Right now, it displays the correct assigned value for the first element I click, but no matter what I click afterwards, it always just displays the first value buttonID had. I attempted to debug it but couldn't exactly find a point where it would pull the old value (to the best of my knowledge, it reassigned the value). There's a good possibility I'm missing something small, because this is my first Android project (of any note). Can someone help get different values of buttonId to appear or point out the error in my logic? The code: package com.TicTacToe.app; import com.TicTacToe.app.R; //Other import statements public class TicTacToe extends Activity { public String player = "X"; public int ALERT_ID; public int buttonId; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Sets up instances of UI elements final TextView playerText = (TextView)findViewById(R.id.CurrentPlayerDisp); final Button button = (Button) findViewById(R.id.SetPlayer); final TextView location1 = (TextView)findViewById(R.id.location1); final TextView location2 = (TextView)findViewById(R.id.location2); final TextView location3 = (TextView)findViewById(R.id.location3); final TextView location4 = (TextView)findViewById(R.id.location4); final TextView location5 = (TextView)findViewById(R.id.location5); final TextView location6 = (TextView)findViewById(R.id.location6); final TextView location7 = (TextView)findViewById(R.id.location7); final TextView location8 = (TextView)findViewById(R.id.location8); final TextView location9 = (TextView)findViewById(R.id.location9); playerText.setText(player); //Handlers for events button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Perform action on click if (player.equals("X")){ player = "O"; playerText.setText(player); } else if(player.equals("O")){ player = "X"; playerText.setText(player); } //Sets up the dialog buttonId = 0; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 1; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 2; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 3; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 4; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 5; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 6; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location7.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 7; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location8.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 8; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); location9.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Sets up the dialog buttonId = 9; ALERT_ID = 0; onCreateDialog(ALERT_ID); showDialog(ALERT_ID); } }); } protected Dialog onCreateDialog(int id){ String msgString = "You are on spot " + buttonId; AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(msgString) .setCancelable(false) .setNeutralButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); return alert; } }

    Read the article

  • Java: If vs. Switch

    - by _ande_turner_
    I have a piece of code with a) which I replaced with b) purely for legibility ... a) if ( WORD[ INDEX ] == 'A' ) branch = BRANCH.A; /* B through to Y */ if ( WORD[ INDEX ] == 'Z' ) branch = BRANCH.Z; b) switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; /* B through to Y */ case 'Z' : branch = BRANCH.Z; break; } ... will the switch version cascade through all the permutations or jump to a case ? EDIT: Some of the answers below regard alternative approaches to the approach above. I have included the following to provide context for its use. The reason I asked, the Question above, was because the speed of adding words empirically improved. This isn't production code by any means, and was hacked together quickly as a PoC. The following seems to be a confirmation of failure for a thought experiment. I may need a much bigger corpus of words than the one I am currently using though. The failure arises from the fact I did not account for the null references still requiring memory. ( doh ! ) public class Dictionary { private static Dictionary ROOT; private boolean terminus; private Dictionary A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z; private static Dictionary instantiate( final Dictionary DICTIONARY ) { return ( DICTIONARY == null ) ? new Dictionary() : DICTIONARY; } private Dictionary() { this.terminus = false; this.A = this.B = this.C = this.D = this.E = this.F = this.G = this.H = this.I = this.J = this.K = this.L = this.M = this.N = this.O = this.P = this.Q = this.R = this.S = this.T = this.U = this.V = this.W = this.X = this.Y = this.Z = null; } public static void add( final String...STRINGS ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); for ( final String STRING : STRINGS ) Dictionary.add( STRING.toUpperCase().toCharArray(), Dictionary.ROOT , 0, STRING.length() - 1 ); } private static void add( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A = Dictionary.instantiate( BRANCH.A ); break; case 'B' : branch = BRANCH.B = Dictionary.instantiate( BRANCH.B ); break; case 'C' : branch = BRANCH.C = Dictionary.instantiate( BRANCH.C ); break; case 'D' : branch = BRANCH.D = Dictionary.instantiate( BRANCH.D ); break; case 'E' : branch = BRANCH.E = Dictionary.instantiate( BRANCH.E ); break; case 'F' : branch = BRANCH.F = Dictionary.instantiate( BRANCH.F ); break; case 'G' : branch = BRANCH.G = Dictionary.instantiate( BRANCH.G ); break; case 'H' : branch = BRANCH.H = Dictionary.instantiate( BRANCH.H ); break; case 'I' : branch = BRANCH.I = Dictionary.instantiate( BRANCH.I ); break; case 'J' : branch = BRANCH.J = Dictionary.instantiate( BRANCH.J ); break; case 'K' : branch = BRANCH.K = Dictionary.instantiate( BRANCH.K ); break; case 'L' : branch = BRANCH.L = Dictionary.instantiate( BRANCH.L ); break; case 'M' : branch = BRANCH.M = Dictionary.instantiate( BRANCH.M ); break; case 'N' : branch = BRANCH.N = Dictionary.instantiate( BRANCH.N ); break; case 'O' : branch = BRANCH.O = Dictionary.instantiate( BRANCH.O ); break; case 'P' : branch = BRANCH.P = Dictionary.instantiate( BRANCH.P ); break; case 'Q' : branch = BRANCH.Q = Dictionary.instantiate( BRANCH.Q ); break; case 'R' : branch = BRANCH.R = Dictionary.instantiate( BRANCH.R ); break; case 'S' : branch = BRANCH.S = Dictionary.instantiate( BRANCH.S ); break; case 'T' : branch = BRANCH.T = Dictionary.instantiate( BRANCH.T ); break; case 'U' : branch = BRANCH.U = Dictionary.instantiate( BRANCH.U ); break; case 'V' : branch = BRANCH.V = Dictionary.instantiate( BRANCH.V ); break; case 'W' : branch = BRANCH.W = Dictionary.instantiate( BRANCH.W ); break; case 'X' : branch = BRANCH.X = Dictionary.instantiate( BRANCH.X ); break; case 'Y' : branch = BRANCH.Y = Dictionary.instantiate( BRANCH.Y ); break; case 'Z' : branch = BRANCH.Z = Dictionary.instantiate( BRANCH.Z ); break; } if ( INDEX == INDEX_LIMIT ) branch.terminus = true; else Dictionary.add( WORD, branch, INDEX + 1, INDEX_LIMIT ); } public static boolean is( final String STRING ) { Dictionary.ROOT = Dictionary.instantiate( Dictionary.ROOT ); return Dictionary.is( STRING.toUpperCase().toCharArray(), Dictionary.ROOT, 0, STRING.length() - 1 ); } private static boolean is( final char[] WORD, final Dictionary BRANCH, final int INDEX, final int INDEX_LIMIT ) { Dictionary branch = null; switch ( WORD[ INDEX ] ) { case 'A' : branch = BRANCH.A; break; case 'B' : branch = BRANCH.B; break; case 'C' : branch = BRANCH.C; break; case 'D' : branch = BRANCH.D; break; case 'E' : branch = BRANCH.E; break; case 'F' : branch = BRANCH.F; break; case 'G' : branch = BRANCH.G; break; case 'H' : branch = BRANCH.H; break; case 'I' : branch = BRANCH.I; break; case 'J' : branch = BRANCH.J; break; case 'K' : branch = BRANCH.K; break; case 'L' : branch = BRANCH.L; break; case 'M' : branch = BRANCH.M; break; case 'N' : branch = BRANCH.N; break; case 'O' : branch = BRANCH.O; break; case 'P' : branch = BRANCH.P; break; case 'Q' : branch = BRANCH.Q; break; case 'R' : branch = BRANCH.R; break; case 'S' : branch = BRANCH.S; break; case 'T' : branch = BRANCH.T; break; case 'U' : branch = BRANCH.U; break; case 'V' : branch = BRANCH.V; break; case 'W' : branch = BRANCH.W; break; case 'X' : branch = BRANCH.X; break; case 'Y' : branch = BRANCH.Y; break; case 'Z' : branch = BRANCH.Z; break; } if ( branch == null ) return false; if ( INDEX == INDEX_LIMIT ) return branch.terminus; else return Dictionary.is( WORD, branch, INDEX + 1, INDEX_LIMIT ); } }

    Read the article

  • How to call a WCF service using soap2 on android?

    - by Qing
    Hi all, Here is my code import org.ksoap2.; import org.ksoap2.serialization.; import org.ksoap2.transport.*; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class ksop2test extends Activity { /** Called when the activity is first created. */ private static final String METHOD_NAME = "SayHello"; // private static final String METHOD_NAME = "HelloWorld"; private static final String NAMESPACE = "http://tempuri.org"; // private static final String NAMESPACE = "http://tempuri.org"; private static final String URL = "http://192.168.0.2:8080/HelloWCF/Service1.svc"; // private static final String URL = "http://192.168.0.2:8080/webservice1/Service1.asmx"; final String SOAP_ACTION = "http://tempuri.org/IService1/SayHello"; // final String SOAP_ACTION = "http://tempuri.org/HelloWorld"; TextView tv; StringBuilder sb; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); tv = new TextView(this); sb = new StringBuilder(); call(); tv.setText(sb.toString()); setContentView(tv); } public void call() { try { SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); request.addProperty("name", "Qing"); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope( SoapEnvelope.VER11); envelope.dotNet = true; envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); androidHttpTransport.call(SOAP_ACTION, envelope); sb.append(envelope.toString() + "\n");//cannot get the xml request send SoapPrimitive result = (SoapPrimitive)envelope.getResponse(); //to get the data String resultData = result.toString(); // 0 is the first object of data sb.append(resultData + "\n"); } catch (Exception e) { sb.append("Error:\n" + e.getMessage() + "\n"); } } } I can successfully access .asmx service, but when I try to call a wcf service the virtual machine said : Error: expected:END_TAG{http://schemas.xmlsoap.org/soap/envelope/}Body(position:END_TAG@1:712 in java.io.InputStreamReader@43ba6798 How to print what the request send? Here is the wcf wsdl: <wsdl:definitions name="Service1" targetNamespace="http://tempuri.org/"> - - - - - - - - - - - - It uses in tag and the asmx uses in tag what's the difference? Thanks. -Qing

    Read the article

  • Rendering HTML in Java

    - by ferronrsmith
    I am trying to create a help panel for an application I am working on. The help file as already been created using html technology and I would like it to be rendered in a pane and shown. All the code I have seen shows how to render a site e.g. "http://google.com". I want to render a file from my pc e.g. "file://c:\tutorial.html" This is the code i have, but it doesn't seem to be working. import javax.swing.JEditorPane; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JScrollPane; import javax.swing.SwingUtilities; import java.awt.Color; import java.awt.Container; import java.io.IOException; import static java.lang.System.err; import static java.lang.System.out; final class TestHTMLRendering { // ------------------------------ CONSTANTS ------------------------------ /** * height of frame in pixels */ private static final int height = 1000; /** * width of frame in pixels */ private static final int width = 1000; private static final String RELEASE_DATE = "2007-10-04"; /** * title for frame */ private static final String TITLE_STRING = "HTML Rendering"; /** * URL of page we want to display */ private static final String URL = "file://C:\\print.html"; /** * program version */ private static final String VERSION_STRING = "1.0"; // --------------------------- main() method --------------------------- /** * Debugging harness for a JFrame * * @param args command line arguments are ignored. */ @SuppressWarnings( { "UnusedParameters" } ) public static void main( String args[] ) { // Invoke the run method on the Swing event dispatch thread // Sun now recommends you call ALL your GUI methods on the Swing // event thread, even the initial setup. // Could also use invokeAndWait and catch exceptions SwingUtilities.invokeLater( new Runnable() { /** * } fire up a JFrame on the Swing thread */ public void run() { out.println( "Starting" ); final JFrame jframe = new JFrame( TITLE_STRING + " " + VERSION_STRING ); Container contentPane = jframe.getContentPane(); jframe.setSize( width, height ); contentPane.setBackground( Color.YELLOW ); contentPane.setForeground( Color.BLUE ); jframe.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); try { out.println( "acquiring URL" ); JEditorPane jep = new JEditorPane( URL ); out.println( "URL acquired" ); JScrollPane jsp = new JScrollPane( jep, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED ); contentPane.add( jsp ); } catch ( IOException e ) { err.println( "can't find URL" ); contentPane.add( new JLabel( "can't find URL" ) ); } jframe.validate(); jframe.setVisible( true ); // Shows page, with HTML comments erroneously displayed. // The links are not clickable. } } ); }// end main }// end TestHTMLRendering

    Read the article

  • Refresh Button in java

    - by lakshmi
    I need to make a simple refresh button for a gui java program I have the button made but its not working properly. I just am not sure what the code needs to be to make the button work. Any help would be really appreciated.I figured the code below ` public class CompanySample extends Panel { DBServiceAsync dbService = GWT.create(DBService.class); Panel panel = new Panel(); public Panel CompanySampledetails(com.viji.example.domain.Record trec, int count) { panel.setWidth(800); Panel borderPanel = new Panel(); Panel centerPanel = new Panel(); final FormPanel formPanel = new FormPanel(); formPanel.setFrame(true); formPanel.setLabelAlign(Position.LEFT); formPanel.setPaddings(5); formPanel.setWidth(800); final Panel inner = new Panel(); inner.setLayout(new ColumnLayout()); Panel columnOne = new Panel(); columnOne.setLayout(new FitLayout()); GridPanel gridPanel = null; if (gridPanel != null) { gridPanel.getView().refresh(); gridPanel.clear(); } gridPanel = new SampleGrid(trec); gridPanel.setHeight(450); gridPanel.setTitle("Company Data"); final RowSelectionModel sm = new RowSelectionModel(true); sm.addListener(new RowSelectionListenerAdapter() { public void onRowSelect(RowSelectionModel sm, int rowIndex, Record record) { formPanel.getForm().loadRecord(record); } }); gridPanel.setSelectionModel(sm); gridPanel.doOnRender(new Function() { public void execute() { sm.selectFirstRow(); } }, 10); columnOne.add(gridPanel); inner.add(columnOne, new ColumnLayoutData(0.6)); final FieldSet fieldSet = new FieldSet(); fieldSet.setLabelWidth(90); fieldSet.setTitle("company Details"); fieldSet.setAutoHeight(true); fieldSet.setBorder(false); final TextField txtcompanyname = new TextField("Name", "companyname", 120); final TextField txtcompanyaddress = new TextField("Address", "companyaddress", 120); final TextField txtcompanyid = new TextField("Id", "companyid", 120); txtcompanyid.setVisible(false); fieldSet.add(txtcompanyid); fieldSet.add(txtcompanyname); fieldSet.add(txtcompanyaddress); final Button addButton = new Button(); final Button deleteButton = new Button(); final Button modifyButton = new Button(); final Button refeshButton = new Button(); addButton.setText("Add"); deleteButton.setText("Delete"); modifyButton.setText("Modify"); refeshButton.setText("Refresh"); fieldSet.add(addButton); fieldSet.add(deleteButton); fieldSet.add(modifyButton); fieldSet.add(refeshButton); final ButtonListenerAdapter buttonClickListener = new ButtonListenerAdapter() { public void onClick(Button button, EventObject e) { if (button == refeshButton) { sendDataToServ("Refresh"); } } }; addButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Add")) { sendDataToServer("Add"); } } private void sendDataToServer(String action) { String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { Window.alert("Record not inserted"); } @Override public void onSuccess(String result) { Window.alert("Record inserted"); } }; if (action.trim().equals("Add")) { System.out.println("Before insertServer"); dbService.insertCompany(txtcnameToServer, txtcaddressToServer, ascallback); } } }); deleteButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Delete")) { sendDataToServer("Delete"); } } private void sendDataToServer(String action) { String txtcidToServer = txtcompanyid.getText().trim(); String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (!action.equals("Delete")) { if (txtcidToServer.trim().equals("") || txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } } else if (txtcidToServer.trim().equals("")) { Window.alert("Doesn't deleted any row"); } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { // TODO Auto-generated method stub Window.alert("Record not deleted"); } @Override public void onSuccess(String result) { Window.alert("Record deleted"); } }; if (action.trim().equals("Delete")) { System.out.println("Before deleteServer"); dbService.deleteCompany(Integer.parseInt(txtcidToServer), ascallback); } } }); modifyButton.addListener(new ButtonListenerAdapter() { @Override public void onClick(Button button, EventObject e) { if (button.getText().equals("Modify")) { sendDataToServer("Modify"); } } private void sendDataToServer(String action) { // TODO Auto-generated method stub System.out.println("ACTION :----->" + action); String txtcidToServer = txtcompanyid.getText().trim(); String txtcnameToServer = txtcompanyname.getText().trim(); String txtcaddressToServer = txtcompanyaddress.getText().trim(); if (txtcnameToServer.trim().equals("") || txtcaddressToServer.trim().equals("")) { Window .alert("Incomplete Data. Fill/Select all the needed fields"); action = "Nothing"; } AsyncCallback ascallback = new AsyncCallback<String>() { @Override public void onFailure(Throwable caught) { Window.alert("Record not Updated"); } @Override public void onSuccess(String result) { Window.alert("Record Updated"); } }; if (action.equals("Modify")) { System.out.println("Before UpdateServer"); dbService.modifyCompany(Integer.parseInt(txtcidToServer), txtcnameToServer, txtcaddressToServer, ascallback); } } }); inner.add(new PaddedPanel(fieldSet, 0, 10, 0, 0), new ColumnLayoutData( 0.4)); formPanel.add(inner); borderPanel.add(centerPanel, new BorderLayoutData(RegionPosition.CENTER)); centerPanel.add(formPanel); panel.add(borderPanel); return panel; } public void sendDataToServ(String action) { AsyncCallback<com.viji.example.domain.Record> callback = new AsyncCallback<com.viji.example.domain.Record>() { @Override public void onFailure(Throwable caught) { System.out.println("Failure"); } public void onSuccess(com.viji.example.domain.Record result) { CompanySampledetails(result, 1); } }; dbService.getRecords(callback); } } class SampleGrid extends GridPanel { private static BaseColumnConfig[] columns = new BaseColumnConfig[] { new ColumnConfig("Name", "companyname", 120, true), new ColumnConfig("Address", "companyaddress", 120, true), }; private static RecordDef recordDef = new RecordDef(new FieldDef[] { new IntegerFieldDef("companyid"), new StringFieldDef("companyname"), new StringFieldDef("companyaddress") }); public SampleGrid(com.viji.example.domain.Record trec) { Object[][] data = new Object[0][];// getCompanyDataSmall(); MemoryProxy proxy = new MemoryProxy(data); ArrayReader reader = new ArrayReader(recordDef); Store store = new SimpleStore(new String[] { "companyid", "companyname", "companyaddress" }, new Object[0][]); store.load(); ArrayList<Company> Companydetails = trec.getCompanydetails(); for (int i = 0; i < Companydetails.size(); i++) { Company company = Companydetails.get(i); store.add(recordDef.createRecord(new Object[] { company.getCompanyid(), company.getCompanyName(), company.getCompanyaddress() })); } store.commitChanges(); setStore(store); ColumnModel columnModel = new ColumnModel(columns); setColumnModel(columnModel); } } `

    Read the article

< Previous Page | 8 9 10 11 12 13 14 15 16 17 18 19  | Next Page >