How do I get input from a user using j2me canvases? is this even possible? - java-me

I am currently trying to learn J2ME and build a connect four game (some of you might know this as 'four in a row'). I've More or less got all of the aspects of my game working, apart from one thing that is driving me mad! This is of course getting the text from the user!
For the two player mode of the game I want to be able to allow each player to enter their name. I am struggling to find a working example of text input that doesn't use the main Midlet.
For example the examples on java2x.com just use a single midlet (no classes or canvases or anything).
As it stands my application's main midlet start method simply opens a main menu class:
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
public void startApp() {
MainMenu mm = new MainMenu();
showScreen(mm);
}
public static void showScreen(Displayable screen) {
Display.getDisplay(instance).setCurrent(screen);
}
public void pauseApp() {
}
public static void quitApp() {
instance.notifyDestroyed();
}
public void destroyApp(boolean unconditional) {
}
}
The main menu class is as follows:
package view;
import javax.microedition.lcdui.*;
import lang.*;
import model.*;
import midlet.Main;
public class MainMenu extends List implements CommandListener {
private Command ok = new Command(StringDefs.currDefs.getString("TEXT_OK"), Command.OK, 1);
public MainMenu() {
super(StringDefs.currDefs.getString("TEXT_TITLE"), List.IMPLICIT);
// we we add in the menu items
append(StringDefs.currDefs.getString("TEXT_PLAY1"), null);
append(StringDefs.currDefs.getString("TEXT_PLAY2"), null);
append(StringDefs.currDefs.getString("TEXT_HIGHSCORETABLE"), null);
append(StringDefs.currDefs.getString("TEXT_HELP"), null);
append(StringDefs.currDefs.getString("TEXT_QUIT"), null);
this.addCommand(ok);
this.setCommandListener(this);
}
public void commandAction(Command c, Displayable d) {
if (c == ok) {
int selectedItem = this.getSelectedIndex();
if (selectedItem != -1) {
switch (selectedItem) {
case 0:
GameBoard gameBoard = new model.GameBoard();
GameCanvasOnePlayer board = new GameCanvasOnePlayer(gameBoard);
Main.showScreen(board);
break;
case 1:
GameBoard gameBoardTwo = new model.GameBoard();
GameCanvasTwoPlayer GameCanvasTwoPlayer = new GameCanvasTwoPlayer(gameBoardTwo);
Main.showScreen(GameCanvasTwoPlayer);
break;
case 2:
HighScores hc = new HighScores();
midlet.Main.showScreen(hc);
break;
case 3:
Help he = new Help();
midlet.Main.showScreen(he);
break;
case 4:
QuitConfirmation qc = new QuitConfirmation();
midlet.Main.showScreen(qc);
break
}
}
}
}
}
When a two player game is selected (case 1 in the above switch) from this menu I would like two text boxes to appear so that I can get both player names and store them.
What would be the best way of going about this? is this even possible with canvases? And do you know where I can find a relevant example or at least something which may help?

You can either:
1. Make the user enter his input in an ugly Textbox (which takes the whole screen)
2. Use the textbox control I've written from scratch a long time ago which is available here
and looks something like this (3 Textfields shown):

I've got a solution! well sort of.
I can create a form without using the main midlet:
The following main class is part of a source package called midlet (much like in my project):
package midlet;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import view.*;
public class Main extends MIDlet {
private static UsernameForm unameForm=new UsernameForm();
private static MIDlet instance;
public void startApp() {
instance=this;
showScreen(unameForm); // show user name form
}
public static String getUsername1() {
return(unameForm.getUsername1());
}
public static String getUsername2() {
return(unameForm.getUsername2());
}
public void pauseApp() {
}
public static void showScreen(Displayable d) {
Display.getDisplay(instance).setCurrent(d); // show next screen
}
public void destroyApp(boolean unconditional) {
}
}
The next bit of code is the username form class that is part of a source package called view:
package view;
import javax.microedition.lcdui.*;
public class UsernameForm extends Form implements CommandListener {
private String username1="";
private String username2="";
private TextField tfUsername1=new javax.microedition.lcdui.TextField("User 1","User1",40,TextField.ANY);
private TextField tfUsername2=new javax.microedition.lcdui.TextField("User 2","User2",40,TextField.ANY);
private Command cmdOK=new Command("OK",Command.OK,1);
public UsernameForm() {
super("User details");
append(tfUsername1);
append(tfUsername2);
addCommand(cmdOK);
setCommandListener(this);
}
public void commandAction(Command cmd,Displayable d) {
if (cmd==cmdOK) {
this.setUsername1(tfUsername1.getString());
this.setUsername2(tfUsername2.getString());
// TO DO, GO TO NEXT SCREEN
}
}
/**
* #return the username1
*/
public String getUsername1() {
return username1;
}
/**
* #param username1 the username1 to set
*/
public void setUsername1(String username1) {
this.username1 = username1;
}
/**
* #return the username2
*/
public String getUsername2() {
return username2;
}
/**
* #param username2 the username2 to set
*/
public void setUsername2(String username2) {
this.username2 = username2;
}
}
So it looks like there's no easy way of doing it using canvases, I think I am better of using 'ugly forms' instead as they should work whatever the device.

That's a really sticky situation. Basically you will need to use J2ME's input text widget (which by the way looks horrible). If you don't, you'll end up having to implement all the logic behind the different types of phone keyboards and you won't have access to the dictionary... Your canvas will basically only be capturing keystrokes, not text input...
Sorry.

Here you need to, implement custom Items, all you need to do is to extend the part of the canvas where to want the user/player to enter his/her name to the CustomItems, and implement the customItems predefined abstract methods, and write method for Key Strokes and that's available in the nokia forum. They have explained it pretty good. Check out the Nokia forum.

Related

Actor position is incorrect - Libgdx

Please help me, I'm pulling my hair out.
I have a class called "HudBarView" which extends the Group class(scene2d). It takes care of the drawing of the HUD Bar at the top of the screen(Pause button, score, etc).
Another class I have is "HUDManager" which takes care of all the HUD work in the game, including HUD Bar.
These two classes are very short and self-explantory. There is nothing sophisticated.
Now, currently I have only a pause button(ImageButton) in my HUD Bar but the problem is - it is visible only after I resize or pause and then resume the screen.
Here is a gif that describes my problem:
http://i.gyazo.com/6140c4ac1ea0778e4e1afce161ea3dc0.gif
I have tried to play a little bit with the code and I found out that the positioning of the actor is wrong. For instance if I define the position of the button with these values:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width*2,Values.SCREEN_HEIGHT-Values.Pause_Height*2);
Instead of these:
Vector2 position = new Vector2(Values.SCREEN_WIDTH-Values.Pause_Width,Values.SCREEN_HEIGHT-Values.Pause_Height);
It does show up on the screen but at the wrong position and after pause/resume it show up at the correct position.
Here is my HudBarView class:
package views.hud.views;
import views.renderers.HUDManager;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.Values;
public class HUDBarView extends Group{
private ImageButton pause;
private HUDManager hud_manager;
private Skin skin;
public HUDBarView(HUDManager hud_manager) {
this.hud_manager = hud_manager;
initiate();
}
private void initiate() {
skin = new Skin(AssetsManager.getAsset(Values.BUTTONS_PACK, TextureAtlas.class));
pause = new ImageButton(skin.getDrawable("pause"));
pause.setSize(Values.Pause_Width, Values.Pause_Height);
pause.setPosition(Values.SCREEN_WIDTH - pause.getWidth(), Values.SCREEN_HEIGHT- pause.getHeight());
addActor(pause);
}
}
HUDManager class:
package views.renderers;
import views.hud.ParticleEffectsActor;
import views.hud.views.HUDBarView;
import aurelienribon.tweenengine.TweenManager;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Image;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import engine.helpers.AssetsManager;
import engine.helpers.UIHelper;
import engine.helpers.Values;
public class HUDManager extends Group {
private Stage stage;
private Skin skin;
private Image text;
private HUDBarView hudView;
public HUDManager(Stage stage) {
this.stage = stage;
initiate();
addActor(hudView);
addActor(particles);
}
public void initiate() {
skin = AssetsManager.getAsset(Values.GAME_SKIN_PACK, Skin.class);
hudView = new HUDBarView(this);
particles = new ParticleEffectsActor();
}
public Stage getStage() {
return stage;
}
}
And Here is my game screen problem:
package views.screens;
import views.renderers.GameRenderer;
import views.renderers.HUDManager;
import engine.GameInputHandler;
import engine.GameWorld;
import engine.Values;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.StretchViewport;
/* Created by David Lasry : 10/25/14 */
public class GameScreen extends ScreenWrapper {
private GameWorld world;
private HUDManager hudManager;
private GameRenderer renderer;
private Stage stage;
public GameScreen() {
super();
ScreenHandler.getInstance().getGame().getAssetsManager()
.loadAsstes(2, this);
world = new GameWorld();
stage = new Stage(new StretchViewport(Values.SCREEN_WIDTH,
Values.SCREEN_HEIGHT));
camera = (OrthographicCamera) stage.getCamera();
InputMultiplexer inputs = new InputMultiplexer();
inputs.addProcessor(stage);
inputs.addProcessor(new GameInputHandler(world.getMonkeyManager(),
camera));
Gdx.input.setInputProcessor(inputs);
}
#Override
public void render(float delta) {
switch (state) {
case RUN:
stage.act(delta);
stage.draw();
world.update(delta);
break;
case PAUSE:
break;
}
}
// Callback method that is called when the assets are loaded
#Override
public void assetsLoaded() {
super.assetsLoaded();
renderer = new GameRenderer(world);
hudManager = new HUDManager();
stage.addActor(renderer);
stage.addActor(hudManager);
}
public HUDManager getHudManager() {
return hudManager;
}
#Override
public void dispose() {
stage.dispose();
ScreenHandler.getInstance().getGame().getAssetsManager().unload(2);
}
}
I'm struggling with this problem for almost 3 days and I have no idea what is causing this.
I even opened a new project, duplicated the relevant classes and just tried to position the button at the top right corner of the screen and it worked! So why it doesn't work in my actual game?
Please help !

How do I assign contents of a string to a text field in Unity 4.6?

I am working on a C# class that imports text data from a web site. That works OK. Where I'm losing it is how to display the text in Unity 4.6 once I have all the text in a string variable. Any advice is appreciated.
Unity 4.6 UI system has component named Text. You can watch video tutorial here. Also I suggest you to check out its API.
As always, you have two options on how to add this component to the game object. You can do it from editor (just click on game object you want to have this component in hierarchy and add Text component). Or you can do it from script using gameObject.AddComponent<Text>().
In case you are not familiar with components yet, I suggest you to read this article.
Anyway, in your script you'll need to add using UnityEngine.UI; at the very top of it, because the Text class is in UnityEngine.UI namespace. Ok, so now back to script that will set the value of Text component.
First you need variable that refers to Text component. It can be done via exposing it to editor:
public class MyClass : MonoBehaviour {
public Text myText;
public void SetText(string text) {
myText.text = text;
}
}
And attaching gameObject with text component to this value in Editor.
Another option:
public class MyClass : MonoBehaviour {
public void SetText(string text) {
// you can try to get this component
var myText = gameObject.GetComponent<Text>();
// but it can be null, so you might want to add it
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
myText.text = text;
}
}
Previous script is not a good example, because GetComponent is actually expensive. So you might want to cache it’s reference:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetComponent<Text>();
// and again it can be null
if (myText == null) {
myText = gameObject.AddComponent<Text>();
}
}
// now we can set the value
myText.text = text;
}
}
BTW, the patter of ‘GetComponent or Add if it doesn’t exist yet’ is so common, that usually in Unity you want to define function
static public class MethodExtensionForMonoBehaviourTransform {
static public T GetOrAddComponent<T> (this Component child) where T: Component {
T result = child.GetComponent<T>();
if (result == null) {
result = child.gameObject.AddComponent<T>();
}
return result;
}
}
So you can use it as:
public class MyClass : MonoBehaviour {
Text myText;
public void SetText(string text) {
if (myText == null) {
// looks like we need to get it or add
myText = gameObject.GetOrAddComponent<Text>();
}
// now we can set the value
myText.text = text;
}
}
make sure you import the ui library - using UnityEngine.UI
gameObject.GetComponent<Text>().text - replace .text with any other field for UI Text
I assume that the issue is creating dynamic sized "textbox" rather than just assigning the string to a GUIText GameObject. (If not - just put a GUIText GameObject into your scene, access it via a GUIText variable in your script and use myGUIText.text = myString in Start or Update.)
If I am correct in my assumption, then I think you should just be using a GUI Label:
http://docs.unity3d.com/ScriptReference/GUI.Label.html
If you need to split the string up to place text into different labels or GUITexts, you will need to use substrings

PowerMocking static does not return expected object

I have a problem mocking Calendar.getInstance(). As you now this method returns a Calendar - the object I am mocking.
Right now my code looks like this:
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Calendar.getInstance() gets called various times in surveillance.checkDatabase() and every time it is a new object and not the expected mock of Calendar.
Can anyone see what I am doing wrong?
It seems that you need to add the target test class in the PrepareForTest tag:
#PrepareForTest({ Calendar.class, Surveillance.class })
#RunWith(PowerMockRunner.class)
#PrepareForTest({ Calendar.class, Surveillance.class })
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
mockStatic(Calendar.class);
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(calendar);
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
}
}
Even Tom Tresansky's example above will need it if we move the Surveillance class to somewhere outside MockCalendarTest class.
I'm not as familiar with the when(object.call()).andReturn(response); but I'm assuming it works the same way as expect.(object.call()).andReturn(response);. If that is the case, then it looks like all you are missing a replay of the class PowerMock.replay(Calendar.class) and you are trying to do a full static mock instead of a partial static mock. This should resolve your issue.
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class SurveillanceDatabaseTest {
#Test
public void testFailingDatabase() throws Exception {
Calendar calendar = new GregorianCalendar();
calendar.add(Calendar.HOUR, 1);
PowerMock.mockStaticPartial(Calendar.class, "getInstance"); //Mock Static Partial
expect(Calendar.getInstance()).andReturn(calendar);
PowerMock.replay(Calendar.class); // note the replay of the Class!
final Surveillance surveillance = new Surveillance();
surveillance.checkDatabase();
//Whatever tests you need to do here
}
}
It seems like you're doing everything right. For instance, this test below passes, proving that the Calendar returned by Calendar#getInstance() is in fact the one you set up with the static mocking.
import static org.junit.Assert.*;
import static org.powermock.api.mockito.PowerMockito.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
#RunWith(PowerMockRunner.class)
#PrepareForTest(Calendar.class)
public class MockCalendarTest {
#Test
public void testFailingDatabase() {
mockStatic(Calendar.class);
final Calendar testCalendar = new GregorianCalendar();
testCalendar.add(Calendar.HOUR, 1);
when(Calendar.getInstance()).thenReturn(testCalendar);
final Surveillance surveillance = new Surveillance();
final Calendar resultCalendar = surveillance.checkDatabase();
assertTrue(testCalendar == resultCalendar);
}
public static class Surveillance {
public Calendar checkDatabase() {
return Calendar.getInstance();
}
}
}
Perhaps post the relevant parts of the Surveillance class so we can see how it's trying to get a new Calendar and assess why it's failing.

Very basic Spinner issue with Android AIDE

Hi I'm completely new to android programming and use AIDE via tablet.
I'm trying to create a very basic program with a Spinner box that gives output on the selection Ive made via an TextView or System.Out.printIn. (Perhaps the next step up from Hello world - if you will)
For some reason that I cannot fathom,the compiler refuses to recognise the OnClickListener and gives the error message 'Unknown method OnClickListener in Android.Widget.Spinner'
When I have already checked this in the imports.
As a matter of interest I have changed the name of the Spinner and the error seems to dissapear, the problem then is the Spinner name. I have tried several variations on this, and have came to the conclusion that the best option for me is to create a variable just after Main Acivity, and before the layout is declared.
I have also disabled one of the overrides in order to resolve my problem
has anyone got an idea what the problem could be?
package com.BGilbert.AUC;
import android.app.*;
import android.os.*;
import android.widget.*;
import android.view.View.OnClickListener;
import android.widget.Spinner.*;
import android.view.*;
public class MainActivity extends Activity {;
String Fbstring;
OnClickListener Myonclick;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);
final Spinner Fbspinner=(Spinner)findViewById(R.id.Spinner);
// The problem is with this line. OnClickListener just wont be
// recognised
Fbspinner.OnClickListener(Myonclick);
}
// Override previously disabled
#Override
public void Onselect(AdapterView<?> parent,View V, int pos, long id) {
Fbstring = parent.getItemAtPosition(pos).toString();
System.out.println(Fbstring);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
You can't set an onClickListener on a spinner, only on it's views which is too advanced for you at the moment. Instead, use an onItemSelectedListener.
public class MainActivity extends Activity extends Activity implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
...
...
}
You should read the documentation first http://developer.android.com/guide/topics/ui/controls/spinner.html
Also try to use standard naming conventions:
http://www.oracle.com/technetwork/java/codeconv-138413.html
http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-135099.html#367
Finally, you have many problems in this code, e.g.
public class MainActivity extends Activity {;
Note the semicolon at the end.
Get your code compiling first, then come back with your next question.
Good luck

Presenter with swappable sub-presenters

Using GWT 2.4 with MVP, I have a presenter where the top portion can swap between a read-only presenter of a set of data or an editor for that data, depending on how you arrived at the page.
Without using GWTP, how can I swap between those two presenters and the underlying views?
Currently, the classes looks like this:
public class MainPagePresenter implements Presenter, MainPageView.Presenter, ParentPresenter {
private MainPageViewview;
private final ClientFactory clientFactory;
private StaticDataPresenter staticPresenter;
private SomeOtherPresenter otherPresenter;
}
I'd like for StaticDataPresenter to become some structure that can either hold a StaticDataPresenter or a DynamicDataPresenter that lets you edit.
Thanks for your input.
public interface DataPresenter {
void handleEdit();
}
public class StaticDataPresenter implements DataPresenter {
#Override
public void handleEdit() {
// Do nothing.
}
}
public class DynamicDataPresenter implements DataPresenter {
#Override
public void handleEdit() {
// Do something.
}
}
public class MainPagePresenter implements Presenter, MainPageView.Presenter, ParentPresenter {
private MainPageView view;
private final ClientFactory clientFactory;
private DataPresenter dataPresenter;
private SomeOtherPresenter otherPresenter;
...
public void switchDataPresenter(DataPresenter dataPresenter) {
this.dataPresenter = dataPresenter;
DataPresenterView dataPresenterView = view.dataPresenterView();
dataPresenterView.setPresenter(dataPresenter);
}
}
Your MainPageView can have a DeckPanel with both the StaticDataPresenter's view, and the SomeOtherPresenter's view.
MainPagePresenter can then tell the MainPageView to switch what is being displayed based on your needs.
What I ended up doing was putting both editors on the page, and then turning on and off the visibility in the presenter.
Thanks for your suggestions. They helped.

Resources