How to move a Bug in GridWorld with arrow keys - keyevent

I'm making a game for my computer Science class and I am trying to move a character object that extends Bug with the arrow keys. Should I put the code to move with the arrow keys in the Character class or in the World class? And what should the code look like? Right now I've got this code in the Character class and it complies fine, but when I try to to run it in the grid nothing happens when I press the arrow keys.
public class Character extends Bug
{
Random pokemon;
public Character()
{
}
public void act(KeyEvent e)
{
move(e);
pokemon = new Random();
if(pokemon.nextInt(10) == 5)
System.out.println("It works!!");
}
public void move(KeyEvent e)
{
Grid<Actor> gr = getGrid();
Location loc = getLocation();
if(gr == null)
return;
if( e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(!(getDirection() == 90))
setDirection(90);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(!(getDirection() == 270))
setDirection(270);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_UP)
{
if(!(getDirection() == 0))
setDirection(0);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(!(getDirection() == 180))
setDirection(180);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
public class Character extends Bug
{
Random pokemon;
public Character()
{
}
public void act(KeyEvent e)
{
move(e);
pokemon = new Random();
if(pokemon.nextInt(10) == 5)
System.out.println("It works!!");
}
public void move(KeyEvent e)
{
Grid<Actor> gr = getGrid();
Location loc = getLocation();
if(gr == null)
return;
if( e.getKeyCode() == KeyEvent.VK_RIGHT)
{
if(!(getDirection() == 90))
setDirection(90);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_LEFT)
{
if(!(getDirection() == 270))
setDirection(270);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_UP)
{
if(!(getDirection() == 0))
setDirection(0);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
else if( e.getKeyCode() == KeyEvent.VK_DOWN)
{
if(!(getDirection() == 180))
setDirection(180);
else
{
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
}
}
Is this code correct for a KeyEvent and how can I call on this code from the World class?
Any help would be greatly appreciated!

In the ActorWorld class there is a method boolean keyPressed(String description, Location loc) this method is the for the sole purpose of being overridden in a subclass. description is the KeyStroke in the format found here, and loc is the Location that the cursor was on when the key was pressed. (Although in your case it doesn't matter)
So in short, you should extend KeyPressed in a Custom CharacterWorld extends ActorWorld class.

Related

How to Resume video after SeekTo() method in VideoView?

I have a VideoView and when I pause video, then leave the page and come back - I need to resume video from last position.
But I have a problem - after SeekTo() method video starts from beginning.
I tried to put SeekTo() in SetSource to AutoPlay but nothing is changed((
Here is my VideoPlayerRender:
[assembly: ExportRenderer(typeof(VideoPlayer),
typeof(FormsVideoLibrary.Droid.VideoPlayerRenderer))]
namespace FormsVideoLibrary.Droid
{
public class VideoPlayerRenderer : ViewRenderer<VideoPlayer, ARelativeLayout>
{
VideoView videoView;
MediaController mediaController; // Used to display transport controls
bool isPrepared;
public VideoPlayerRenderer(Context context) : base(context)
{
}
protected override void OnElementChanged(ElementChangedEventArgs<VideoPlayer> args)
{
base.OnElementChanged(args);
if (args.NewElement != null)
{
if (Control == null)
{
// Save the VideoView for future reference
videoView = new VideoView(Context);
// Put the VideoView in a RelativeLayout
ARelativeLayout relativeLayout = new ARelativeLayout(Context);
relativeLayout.AddView(videoView);
// Center the VideoView in the RelativeLayout
ARelativeLayout.LayoutParams layoutParams =
new ARelativeLayout.LayoutParams(LayoutParams.MatchParent, LayoutParams.MatchParent);
layoutParams.AddRule(LayoutRules.CenterInParent);
videoView.LayoutParameters = layoutParams;
// Handle a VideoView event
videoView.Prepared += OnVideoViewPrepared;
SetNativeControl(relativeLayout);
}
SetAreTransportControlsEnabled();
SetSource();
args.NewElement.UpdateStatus += OnUpdateStatus;
args.NewElement.PlayRequested += OnPlayRequested;
args.NewElement.PauseRequested += OnPauseRequested;
args.NewElement.StopRequested += OnStopRequested;
}
if (args.OldElement != null)
{
args.OldElement.UpdateStatus -= OnUpdateStatus;
args.OldElement.PlayRequested -= OnPlayRequested;
args.OldElement.PauseRequested -= OnPauseRequested;
args.OldElement.StopRequested -= OnStopRequested;
}
}
protected override void Dispose(bool disposing)
{
if (Control != null && videoView != null)
{
videoView.Prepared -= OnVideoViewPrepared;
}
if (Element != null)
{
Element.UpdateStatus -= OnUpdateStatus;
}
base.Dispose(disposing);
}
void OnVideoViewPrepared(object sender, EventArgs args)
{
isPrepared = true;
((IVideoPlayerController)Element).Duration = TimeSpan.FromMilliseconds(videoView.Duration);
var mediaPlayer = sender as MediaPlayer;
var startTime = new TimeSpan(0, 0, 0);
if (App.CurrentPosition > startTime)
{
var position = (int)App.CurrentPosition.TotalMilliseconds;
****mediaPlayer.SeekTo(position);****
((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, position);
}
}
protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs args)
{
base.OnElementPropertyChanged(sender, args);
if (args.PropertyName == VideoPlayer.AreTransportControlsEnabledProperty.PropertyName)
{
SetAreTransportControlsEnabled();
}
else if (args.PropertyName == VideoPlayer.SourceProperty.PropertyName)
{
SetSource();
}
else if (args.PropertyName == VideoPlayer.PositionProperty.PropertyName)
{
if (Math.Abs(videoView.CurrentPosition - Element.Position.TotalMilliseconds) > 1000)
{
videoView.SeekTo((int)Element.Position.TotalMilliseconds);
}
}
}
void SetAreTransportControlsEnabled()
{
if (Element.AreTransportControlsEnabled)
{
mediaController = new MediaController(Context);
mediaController.SetMediaPlayer(videoView);
videoView.SetMediaController(mediaController);
}
else
{
videoView.SetMediaController(null);
if (mediaController != null)
{
mediaController.SetMediaPlayer(null);
mediaController = null;
}
}
}
void SetSource()
{
isPrepared = false;
bool hasSetSource = false;
if (Element.Source is UriVideoSource)
{
string uri = (Element.Source as UriVideoSource).Uri;
if (!String.IsNullOrWhiteSpace(uri))
{
videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
hasSetSource = true;
}
}
else if (Element.Source is FileVideoSource)
{
string filename = (Element.Source as FileVideoSource).File;
if (!String.IsNullOrWhiteSpace(filename))
{
videoView.SetVideoPath(filename);
hasSetSource = true;
}
}
else if (Element.Source is ResourceVideoSource)
{
string package = Context.PackageName;
string path = (Element.Source as ResourceVideoSource).Path;
if (!String.IsNullOrWhiteSpace(path))
{
string filename = Path.GetFileNameWithoutExtension(path).ToLowerInvariant();
string uri = "android.resource://" + package + "/raw/" + filename;
videoView.SetVideoURI(Android.Net.Uri.Parse(uri));
hasSetSource = true;
}
}
if (hasSetSource && Element.AutoPlay)
{
videoView.Start();
}
}
// Event handler to update status
void OnUpdateStatus(object sender, EventArgs args)
{
VideoStatus status = VideoStatus.NotReady;
var startTime = new TimeSpan(0, 0, 0);
if (isPrepared)
{
status = videoView.IsPlaying ? VideoStatus.Playing : VideoStatus.Paused;
}
TimeSpan timeSpan = TimeSpan.FromMilliseconds(videoView.CurrentPosition);
((IElementController)Element).SetValueFromRenderer(VideoPlayer.PositionProperty, timeSpan);
if (status == VideoStatus.Paused &&
timeSpan > startTime &&
!isApplicationInTheBackground())
{
App.CurrentPosition = timeSpan;
}
}
I used XamarinMediaManager and all works.

To automate file upload in oracle open script [OATS]

I am very new to Oracle Application Testing Suite(OATS).In my project I need to automate the file uploading functionality. That is , after clicking browse..button , file explorer will open.
My question is how to aytomate this scenario.
I serached many websites and in youtube but did not get any useful. Please help as it is important in my current project. Any help will be appreciated.
Most of file upload based on windows objects .
Open Script doesn't support windows based object identification for that we have to use external plugin or jar files
best suitable one is RobotClass .
Here is the complete example
http://www.testinghive.com/how-to-perform-file-upload-in-oats-tool/
try
{
Robot robot = new Robot();
robot.delay(200);
upload_parseChars("C:\\testDemo.xlsx", robot);
robot.delay(200);
robot.keyPress(KeyEvent.VK_ENTER);
robot.keyRelease(KeyEvent.VK_ENTER);
}
catch (AWTException e) {
e.printStackTrace();
}
public void upload_parseChars(String letter, Robot robot) throws AbstractScriptException {
for (int i = 0; i < letter.length(); i++) {
//info("inside uf_Vik_parseChars method ");
char chary = letter.charAt(i);
//info("Current character = "+letter.charAt(i));
upld_typeCharacter(Character.toString(chary), robot);
}
}
public void upld_typeCharacter(String letter, Robot robot) throws AbstractScriptException {
// info("Pressed event ");
if (Character.isLetterOrDigit(letter.charAt(0))) {
try {
boolean upperCase = Character.isUpperCase(letter.charAt(0));
String variableName = "VK_" + letter.toUpperCase();
KeyEvent ke = new KeyEvent(new JTextField(), 0, 0, 0, 0, ' ');
#SuppressWarnings("rawtypes")
Class clazz = ke.getClass();
Field field = clazz.getField(variableName);
int keyCode = field.getInt(ke);
robot.delay(80);
if (upperCase)
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(keyCode);
robot.keyRelease(keyCode);
if (upperCase)
robot.keyRelease(KeyEvent.VK_SHIFT);
} catch (Exception e) {
System.out.println(e);
}
} else {
if (letter.equals("!")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_1);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_2);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("#")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_3);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("$")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_4);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("%")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_5);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("^")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_6);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("&")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_7);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("*")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_8);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("=")) {
robot.keyPress(KeyEvent.VK_EQUALS);
robot.keyRelease(KeyEvent.VK_EQUALS);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals("/")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("\\")) {
robot.keyPress(KeyEvent.VK_BACK_SLASH);
robot.keyRelease(KeyEvent.VK_BACK_SLASH);
} else if (letter.equals("_")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_MINUS);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(":")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(";")) {
robot.keyPress(KeyEvent.VK_SEMICOLON);
robot.keyRelease(KeyEvent.VK_SEMICOLON);
} else if (letter.equals(",")) {
robot.keyPress(KeyEvent.VK_COMMA);
robot.keyRelease(KeyEvent.VK_COMMA);
} else if (letter.equals("-")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SUBTRACT);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals("?")) {
robot.keyPress(KeyEvent.VK_SHIFT);
robot.keyPress(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SLASH);
robot.keyRelease(KeyEvent.VK_SHIFT);
} else if (letter.equals(" ")) {
robot.keyPress(KeyEvent.VK_SPACE);
robot.keyRelease(KeyEvent.VK_SPACE);
} else if (letter.equals(".")) {
robot.keyPress(KeyEvent.VK_PERIOD);
robot.keyRelease(KeyEvent.VK_PERIOD);
}
}
}
THE download dialog and upload dialog is supported. try to record one and try related

java.sql.SQLException: I/O Error: Socket closed

I want to sync data from MSSQL to android sqllite.All syncdata method write in ansync class.But sometime application return java.sql.SQLException: I/O Error: Socket closed error and not finish sync data . Sometime application successfully sync all update data.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
{
CheckProductGroupInfoHasNew();
CheckProductInfoHasNew();
CheckProductPriceInfoHasNew();
CheckCustomerInfoHasNew();
}
private void CheckProductInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PC");
else
_AsyncSyncData.execute("PC");
}
private void CheckProductPriceInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PPRICE");
else
_AsyncSyncData.execute("PPRICE");
}
private void CheckCustomerInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"CV");
else
_AsyncSyncData.execute("CV");
}
private void CheckProductGroupInfoHasNew() {
AsyncSyncData _AsyncSyncData = new AsyncSyncData();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
_AsyncSyncData.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
"PG");
else
_AsyncSyncData.execute("PG");
}
class AsyncSyncData extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
if (params[0].toString().equals("PG")) {
_ListProductGroupInfo = _MSDBConnection
.SelectProductGroupInfo(_Query);}
} else if (params[0].equals("PC")) {
_ListProductInfo = _MSDBConnection
.SelectProductInfo(_Query);
} else if (params[0].equals("CV")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
} else if (params[0].equals("PPRICE")) {
_ListProductPriceInfo = _MSDBConnection
.SelectProductPriceInfo(_Query);
} else if (params[0].equals("VAT")) {
_ListCustomerInfo = _MSDBConnection
.SelectCustomerInfo(_Query);
}
#Override
protected void onPostExecute(String result) {
try {
if (result.equals("PG")) {
int _result = 0;
if ((_result = SyncProductGroupInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Group Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PC")) {
int _result = 0;
if ((_result = SyncProductInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("PPRICE")) {
int _result = 0;
if ((_result = SyncProductPriceInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Product Price Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
} else if (result.equals("CV")) {
int _result = 0;
if ((_result = SyncCustomerInfo()) > 0) {
Toast.makeText(
_context,
"Save Successfully .Customer Data rows = "
+ _result, Toast.LENGTH_SHORT).show();
}
HomeFragment.BindProductGroup();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} else if (result.equals("VAT")) {
if (SyncVatInfo()) {
Toast.makeText(_context, "Save Successfully Vat Data",
Toast.LENGTH_SHORT).show();
}
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
}
} catch (Exception ex) {
Log.i("onPostExecute Ex",
" Chan I'm onPostExecute" + ex.getMessage());
ex.printStackTrace();
Toast.makeText(_context, ex.getMessage().toString(),
Toast.LENGTH_LONG).show();
SyncActivity.this.finish();
// close the progress dialog
progressDialog.dismiss();
} finally {
}
}

TableView, managing look of particular cells

I got a method which evaluates whats in the string with what was set by user in TableView cells. (string have values like "343288709789" and each cell contains null or single digit number).
It works, however now I would like TableView to highlight(change background or text color) certain cells where user set wrong value. How can I achive this?
PS. Ive read similiar questions to this but I dont think I can achieve this in TableCell class implementation, because cells should change color only after uses press "Check" option.
private void compareAndEvaluate(String source, NewTableView newTableView){
ObservableList<MyData> data = newTableView.getData();
source = source.replaceAll("\\D+","");
System.out.println("data size: " +data.size() + "\n\n" + source);
int numOfValid = 0,
numOfInvalid = 0;
ObservableList<ObjectProperty<Integer>> rowData;
for(int i=0, n=0; i < data.size(); i++){ //rows(Y)
rowData = data.get(i).returnCellsData();
for(int j = 1; j < rowData.size(); ++j, ++n){ //columns(X)
Integer iNext = Integer.valueOf(String.valueOf(source.charAt(n)));
if( iNext == rowData.get(j).get() )
++numOfValid;
else
++numOfInvalid;
}
}
Dialogs.create().title("Results").masthead(null).message("Correct: " + numOfValid + ", Invalid: " + numOfInvalid).showInformation();
}
If that helps, here is implementation of TableCell used by TableView:
public class EditingCellNumbers extends TableCell<MyData, Integer>{
private TextField textField;
private TableView<MyData> parentTableView;
public EditingCellNumbers(TableView<MyData> parent) {
this.parentTableView = parent;
}
#Override
public void startEdit(){
if (!isEmpty()) {
super.startEdit();
createTextField();
setText(null);
setGraphic(textField);
textField.selectAll();
textField.requestFocus();
}
}
#Override
public void cancelEdit() {
super.cancelEdit();
if(getItem() != null){
setText(String.valueOf(getItem()));
}else{
setText(null);
commitEdit(null);
}
setGraphic(null);
}
#Override
public void updateItem(Integer item, boolean empty) {
super.updateItem(item, empty);
if (empty) {
setText(null);
setGraphic(null);
} else {
if (isEditing()) {
if (textField != null) {
textField.setText(getString());
}
setText(null);
setGraphic(textField);
} else {
setText(getString());
setGraphic(null);
if(getTableColumn().getText() == "#"){
setStyle("-fx-font-weight: bold;"
+ "-fx-background-color: linear-gradient( from -100.0% 150.0% to 120.0% 100.0%, rgb(128,128,128) 0.0, rgb(255,255,255) 100.0);");
}else{
if(getItem() == null)
setStyle("-fx-border-color: lavender; -fx-border-width: 0 1 0 0;");
else
setStyle("-fx-border-color: palegreen; -fx-border-width: 0 1 1 0;");
}
}
}
}
private void createTextField() {
textField = new TextField(getString());
textField.setStyle("-fx-background-color: ivory; -fx-border-color: red;");
textField.setMinWidth(this.getWidth() - this.getGraphicTextGap()* 2);
textField.focusedProperty().addListener(
(ObservableValue<? extends Boolean> arg0, Boolean arg1, Boolean arg2) -> {
if (!arg2) {
if(getItem() != null){
try{
commitEdit(Integer.valueOf(textField.getText()));
}catch(NumberFormatException f){
commitEdit(null);
}
}else
commitEdit(null);
}
});
textField.setOnKeyReleased(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent event) {
if(event.getCode() == KeyCode.BACK_SPACE){
if(getItem() != null){
numberOfEmptyCells.set(numberOfEmptyCells.get() + 1);
numberOfFilledCells.set(numberOfFilledCells.get() - 1);
}
commitEdit(null);
}else{
try{
int i = Integer.valueOf(textField.getText());
//digit given...
if( (i>=0) && (i<10) ){//making sure cell is filled with just one digit
if(getItem() == null){
numberOfEmptyCells.set(numberOfEmptyCells.get() - 1);
numberOfFilledCells.set(numberOfFilledCells.get() + 1);
}
commitEdit(Integer.valueOf(textField.getText()));
int selectedColumn = parentTableView.getSelectionModel().getSelectedCells().get(0).getColumn(); // gets the number of selected column
int selectedRow = parentTableView.getSelectionModel().getSelectedCells().get(0).getRow();
//moving to another cell editing
if(selectedColumn < numberOfColumns-1){
parentTableView.getSelectionModel().selectNext();
parentTableView.edit(selectedRow, parentTableView.getColumns().get(selectedColumn+1));
}else{
parentTableView.getSelectionModel().select(selectedRow+1, parentTableView.getColumns().get(1));
parentTableView.edit(selectedRow+1, parentTableView.getColumns().get(1));
}
}else
textField.clear();
}catch(NumberFormatException e){
textField.clear();
}
}
}
});
}
private String getString() {
return getItem() == null ? "" : getItem().toString();
}
}
}
Instead of making your columns in your data model Integer, make them some kind of an object that stores both the integer and the evaluation result. Use the evaluation result to determine the colour of the cell in your customized TableCell.

Camera Problems

I have run into a few problems when trying to get the camera to work accordingly... The camera Demo Works on the 8520 device (Has a memory Card) but does not work on the 9780 device (Has No Memory Card) the error given
ERROR Class java.lang.ArrayOutOfBoundsException :index 0>=0
My code Sample:
public class MyScreen extends MainScreen{
Player _p;
VideoControl _videoControl;
FileConnection fileconn;
String PATH;
String GetfileName;
LabelField GetPhotofileName = new LabelField("",LabelField.FOCUSABLE){
protected boolean navigationClick(int status, int time){
Dialog.alert("Clicked");
return true;
}
};
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
}else if( root.equalsIgnoreCase("store/") ) {
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
protected boolean invokeAction(int action){
boolean handled = super.invokeAction(action);
if(SdcardAvailabulity()){
PATH = System.getProperty("fileconn.dir.memorycard.photos")+"Image_"+System.currentTimeMillis()+".jpg";//here "str" having the current Date and Time;
} else {
// PATH = System.getProperty("file:///store/home/user/pictures/")+"Image_"+System.currentTimeMillis()+".jpg";
PATH = System.getProperty("fileconn.dir.photos")+"Image_"+System.currentTimeMillis()+".jpg";
}
if(!handled){
if(action == ACTION_INVOKE){
try{
byte[] rawImage = _videoControl.getSnapshot(null);
System.out.println("----------1");
fileconn=(FileConnection)Connector.open(PATH);
System.out.println("----------2");
if(fileconn.exists()){
fileconn.delete();
System.out.println("----------3");
}
fileconn.create();
System.out.println("----------4");
OutputStream os=fileconn.openOutputStream();
System.out.println("----------5");
os.write(rawImage);
GetfileName =fileconn.getName();
System.out.println("----------6");
System.out.println("GetfileName----------"+GetfileName);
fileconn.close();
System.out.println("----------7");
os.close();
Status.show("Image is Captured",200);
GetPhotofileName.setText(GetfileName);
System.out.println("----------8");
if(_p!=null)
_p.close();
System.out.println("----------9");
}catch(Exception e){
if(_p!=null){
_p.close();
}
if(fileconn!=null){
try{
fileconn.close();
}catch (IOException e1){
//if the action is other than click the trackwheel(means go to the menu options) then we do nothing;
}
}
}
}
}
return handled;
}
public MyScreen(){
setTitle("Camera App");
try{
System.out.println("Debug------------10");
_p = javax.microedition.media.Manager.createPlayer("capture://video?encoding=jpeg&width=1024&height=768");
_p.realize();
_videoControl = (VideoControl) _p.getControl("VideoControl");
System.out.println("Debug------------11");
if (_videoControl != null){
Field videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
System.out.println("Debug------------12");
_videoControl.setVisible(true);
_p.start();
System.out.println("Debug------------13");
if(videoField != null){
add(videoField);
System.out.println("Debug------------14");
}
}
}catch(Exception e){
if(_p!=null) {
_p.close();
}
Dialog.alert(e.toString());
}
add(GetPhotofileName);
}
}
on the 8520 (Has a Memory Card) the code works fine on the 9780 (Has no Memory Card) the the code stops at "System.out.println("debug---1")", can anyone please tell me if you can see any problem with my code???
public static boolean SdcardAvailabulity() {
String root = null;
Enumeration e = FileSystemRegistry.listRoots();
while (e.hasMoreElements()) {
root = (String) e.nextElement();
if( root.equalsIgnoreCase("sdcard/") ) {
return true;
}else if( root.equalsIgnoreCase("store/") ) {
return false;
}
}
class MySDListener implements FileSystemListener {
public void rootChanged(int state, String rootName) {
if( state == ROOT_ADDED ) {
if( rootName.equalsIgnoreCase("sdcard/") ) {
}
} else if( state == ROOT_REMOVED ) {
}
}
}
return true;
}
This is the sollution, My "SD card availability" code only returned true which caused the picture not to save when the blackberry had no memory card inserted. # Eugen Martynov Please read through the code and you will see it is there :)

Resources