How to hide the controls of HTMLEditor? - javafx-2

is it possible to hide the controls of a HTMLEditor above the actual text? (Alignment, Copy&Paste icons, stylings etc.)
Thanks for any help

public static void hideHTMLEditorToolbars(final HTMLEditor editor)
{
editor.setVisible(false);
Platform.runLater(new Runnable()
{
#Override
public void run()
{
Node[] nodes = editor.lookupAll(".tool-bar").toArray(new Node[0]);
for(Node node : nodes)
{
node.setVisible(false);
node.setManaged(false);
}
editor.setVisible(true);
}
});
}

If you use unsupported methods, you can customize the toolbars pretty easily.
As Uluk states in his answer, the methods below aren't officially supported.
import java.util.regex.Pattern;
import javafx.application.Application;
import javafx.scene.*;
import javafx.scene.image.ImageView;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorSample extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.show();
hideImageNodesMatching(htmlEditor, Pattern.compile(".*(Cut|Copy|Paste).*"), 0);
Node seperator = htmlEditor.lookup(".separator");
seperator.setVisible(false); seperator.setManaged(false);
}
public void hideImageNodesMatching(Node node, Pattern imageNamePattern, int depth) {
if (node instanceof ImageView) {
ImageView imageView = (ImageView) node;
String url = imageView.getImage().impl_getUrl();
if (url != null && imageNamePattern.matcher(url).matches()) {
Node button = imageView.getParent().getParent();
button.setVisible(false); button.setManaged(false);
}
}
if (node instanceof Parent)
for (Node child : ((Parent) node).getChildrenUnmodifiable())
hideImageNodesMatching(child, imageNamePattern, depth + 1);
}
}

It seems you cannot according to this official tutorial.
The formatting toolbars are provided in the implementation of the
component. You cannot toggle their visibility. However, you still can
customize the appearance of the editor by applying CSS style ...

I've made some functions to modify the HTML-Editor (to get a minimalistic version of it), maybe someone else might want to use it too.
The Code:
import javafx.application.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import com.sun.javafx.scene.web.skin.PopupButton;
public class HTMLEditorModifyer extends Application {
public static void main(String[] args) { launch(args); }
#Override public void start(Stage stage) {
final HTMLEditor htmlEditor = new HTMLEditor();
stage.setScene(new Scene(htmlEditor));
stage.setWidth(300);
stage.setHeight(200);
stage.show();
addCustomToolBarTo(htmlEditor);
printChildren(htmlEditor, 20);
moveFromTo(htmlEditor, "PopupButton", 0, "ToolBar", 2);
moveFromTo(htmlEditor, "PopupButton", 1, "ToolBar", 2);
moveFromTo(htmlEditor, "Separator", 4, "ToolBar", 2);
moveFromTo(htmlEditor, "ComboBox", 2, "ToolBar", 2);
moveFromTo(htmlEditor, "Separator", 5, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 6, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 7, "ToolBar", 2);
moveFromTo(htmlEditor, "ToggleButton", 8, "ToolBar", 2);
removeFrom(htmlEditor, "ToolBar", 1);
removeFrom(htmlEditor, "ToolBar", 0);
//printChildren(htmlEditor, 20);
}
public void moveFromTo(HTMLEditor he, String t, int c, String t2, int c2)
{
Node nCb = new Button(); //just has to be sth.
//Copy From:
int i = 0;
switch(t)
{
case "PopupButton":
for (Node candidate: (he.lookupAll("PopupButton")))
{
if (candidate instanceof PopupButton)
{
PopupButton cb = (PopupButton) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "Separator":
for (Node candidate: (he.lookupAll("Separator")))
{
if (candidate instanceof Separator)
{
Separator cb = (Separator) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "ComboBox":
for (Node candidate: (he.lookupAll("ComboBox")))
{
if (candidate instanceof ComboBox)
{
ComboBox cb = (ComboBox) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
case "ToggleButton":
for (Node candidate: (he.lookupAll("ToggleButton")))
{
if (candidate instanceof ToggleButton)
{
ToggleButton cb = (ToggleButton) candidate;
if (i == c)
{
nCb = cb;
break;
}
}
i++;
}
break;
}
//Copy To:
i = 0;
switch(t2)
{
case "ToolBar":
for (Node candidate: (he.lookupAll("ToolBar")))
{
if (candidate instanceof ToolBar)
{
ToolBar cb2 = (ToolBar) candidate;
if (i == c2)
{
cb2.getItems().add(nCb);
break;
}
}
i++;
}
break;
}
}
public void removeFrom(HTMLEditor he, String t, int c)
{
int i = 0;
switch(t)
{
case "ToolBar":
for (Node candidate: (he.lookupAll("ToolBar")))
{
if (candidate instanceof ToolBar)
{
ToolBar cb = (ToolBar) candidate;
if (i == c)
{
Node nCb = cb;
((Pane) nCb.getParent()).getChildren().remove(nCb);
break;
}
}
i++;
}
break;
case "PopupButton":
for (Node candidate: (he.lookupAll("PopupButton")))
{
if (i == c)
{
Node nCb = candidate;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
i++;
}
break;
case "ToggleButton":
for (Node candidate: (he.lookupAll("ToggleButton")))
{
if (candidate instanceof ToggleButton)
{
ToggleButton cb = (ToggleButton) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "Separator":
for (Node candidate: (he.lookupAll("Separator")))
{
if (candidate instanceof Separator)
{
Separator cb = (Separator) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "Button":
for (Node candidate: (he.lookupAll("Button")))
{
if (candidate instanceof Button)
{
Button cb = (Button) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
case "ComboBox":
for (Node candidate: (he.lookupAll("ComboBox")))
{
if (candidate instanceof ComboBox)
{
ComboBox cb = (ComboBox) candidate;
if (i == c)
{
Node nCb = cb;
nCb.setVisible(false); nCb.setManaged(false);
break;
}
}
i++;
}
break;
}
}
public void printChildren(HTMLEditor he, int MAXDEPTH)
{
System.out.println("Print Children ==========>>>>");
String[] hieraArray = new String[MAXDEPTH];
int maxDepth = 0;
int lastDepth = 0;
Node parent;
/* List all elements of the HTMLeditor */
for (Node element: (he.lookupAll("*")))
{
parent = element.getParent();
if (maxDepth == 0)
{
hieraArray[0] = element.getClass().getSimpleName().toString();
System.out.print(hieraArray[0]);
System.out.println("");
maxDepth = 1;
}
else
{
int i = 0, i2 = 0;
boolean found = false;
for(i=maxDepth; i>=0; i--)
{
if (hieraArray[i] == null || parent.getClass().getSimpleName() == null) continue;
if (hieraArray[i].equals(parent.getClass().getSimpleName()))
{
for (i2 = 0; i2 <= i; i2++)
{
System.out.print("|");
}
if ((Math.abs(lastDepth-i2)) > 2) System.out.print("->" + element.getClass().getSimpleName() + " {p: " + parent.getClass().getSimpleName() + "}");
else System.out.print("->" + element.getClass().getSimpleName());
//if (element.getClass().getSimpleName().equals("PopupButton")) System.out.print(" ??: " + element + " ::: " + element.getClass());
lastDepth = i2;
hieraArray[(i+1)] = element.getClass().getSimpleName();
if (maxDepth < (i+1)) maxDepth = (i+1);
found = true;
System.out.println("");
break;
}
}
if (found == false)
{
hieraArray[(i+1)] = parent.getClass().getSimpleName();
if (maxDepth < (i+1)) maxDepth = (i+1);
}
if ((maxDepth+1) >= MAXDEPTH)
{
System.out.println("MAXDEPTH reached! increase ArraySize!");
return;
}
}
}
}
public ToolBar addCustomToolBarTo(HTMLEditor he)
{
/* Thers one GridPane to the HTMLEditor where we add the ToolBar */
ToolBar customTB = new ToolBar();
for (Node candidate: (he.lookupAll("GridPane")))
{
if (candidate instanceof GridPane)
{
((GridPane) candidate).getChildren().add(customTB);
break;
}
}
return customTB;
}
}

If someone really wants to use an unsupported way to hide the Toolbars then there is an even easier way to achieve this (I haven't tested if this causes any problems in the HTMLEditor control so use this at your own risk).
package htmleditorsample;
import javafx.application.Application;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.web.HTMLEditor;
import javafx.stage.Stage;
public class HTMLEditorSample extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) {
final HTMLEditor htmlEditor = new HTMLEditor();
primaryStage.setScene(new Scene(htmlEditor));
primaryStage.show();
for (Node toolBar = htmlEditor.lookup(".tool-bar"); toolBar != null; toolBar = htmlEditor.lookup(".tool-bar")) {
((Pane) toolBar.getParent()).getChildren().remove(toolBar);
}
}
}

Try this:
.html-editor .top-toolbar
{
-fx-max-width: 0px;
-fx-min-width: 0px;
-fx-pref-width: 0px;
-fx-max-height: 0px;
-fx-min-height: 0px;
-fx-pref-height: 0px;
-fx-opacity: 0;
}
.html-editor .bottom-toolbar
{
-fx-max-width: 0px;
-fx-min-width: 0px;
-fx-pref-width: 0px;
-fx-max-height: 0px;
-fx-min-height: 0px;
-fx-pref-height: 0px;
-fx-opacity: 0;
}

You should be able to hide buttons from its toolbars, even remove them.
I'd do it this way:
final Map map = new HashMap();
for (Node candidate: (htmlEditor.lookupAll("ToolBar"))) {
List list = ((ToolBar) candidate).getItems();
for (int i = 0; i < list.size(); i++) {
Node b = (Node) list.get(i);
map.put(map.size() + 1, b);
}
}
// So we've fetch all buttons (including separators) and assigned
// each an index number. Now then to hide an item:
((Node) map.get(2)).setVisible(false); // Hides copy button
((Node) map.get(13)).setVisible(false); // Hides bullets button
// Or to just completely remove them:
map.remove(18); // Removes font-menu-button
map.remove(25); // Removes editor-strike button

.tool-bar
{
/*-fx-visibility:hidden;
-fx-display:none; */
-fx-opacity: 0;
}
opacity works, but the menu stays active.

This is a pretty old thread, but most of these answers only sort of work, especially on newer JDKs, so here is the custom HTML editor class that I wrote based on some of the concepts in this thread.
import javafx.application.Platform;
import javafx.scene.Node;
import javafx.scene.control.ToolBar;
import javafx.scene.web.HTMLEditor;
import java.util.ArrayList;
import java.util.HashSet;
public class MinimalHTMLEditor extends HTMLEditor {
public MinimalHTMLEditor() {
super();
customizeHtmlEditor(this);
}
public static void customizeHtmlEditor(final HTMLEditor editor) {
editor.setVisible(false);
Platform.runLater(() -> {
ToolBar toolBar1 = (ToolBar) editor.lookup(".top-toolbar");
ToolBar toolBar2 = (ToolBar) editor.lookup(".bottom-toolbar");
HashSet<Node> nodesToKeep = new HashSet<>();
nodesToKeep.add(editor.lookup(".html-editor-numbers"));
nodesToKeep.add(editor.lookup(".html-editor-bullets"));
nodesToKeep.add(editor.lookup(".html-editor-foreground"));
nodesToKeep.add(editor.lookup(".html-editor-background"));
nodesToKeep.add(editor.lookup(".html-editor-bold"));
nodesToKeep.add(editor.lookup(".html-editor-italics"));
nodesToKeep.add(editor.lookup(".html-editor-underline"));
nodesToKeep.add(editor.lookup(".html-editor-strike"));
toolBar1.getItems().removeIf(n -> !nodesToKeep.contains(n));
toolBar2.getItems().removeIf(n -> !nodesToKeep.contains(n));
ArrayList<Node> toCopy = new ArrayList<>();
toCopy.addAll(toolBar2.getItems());
toolBar2.getItems().clear();
toolBar1.getItems().addAll(toCopy);
toolBar2.setVisible(false);
toolBar2.setManaged(false);
editor.setVisible(true);
});
}
}

You can remove specific buttons using CSS, for example:
.html-editor-copy {
visibility: hidden;
}
The full list of the CSS button names can be found at:
Oracle CSS Reference Guide

Related

NullPointerException not in my code but in onResume() for LibGDX AndroidInput

This the stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.epl.game, PID: 18789
java.lang.RuntimeException: Unable to resume activity {com.epl.game/com.epl.game.AndroidLauncher}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.badlogic.gdx.backends.android.AndroidInput.onResume()' on a null object reference
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4205)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237)
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.badlogic.gdx.backends.android.AndroidInput.onResume()' on a null object reference
at com.badlogic.gdx.backends.android.AndroidApplication.onResume(AndroidApplication.java:300)
at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1453)
at android.app.Activity.performResume(Activity.java:7962)
at android.app.ActivityThread.performResumeActivity(ActivityThread.java:4195)
at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:4237) 
at android.app.servertransaction.ResumeActivityItem.execute(ResumeActivityItem.java:52) 
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:49 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
This is my main project
package com.epl.game;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Intersector;
import com.badlogic.gdx.math.Rectangle;
import org.omg.PortableServer.POAManagerPackage.State;
import java.util.ArrayList;
import java.util.Random;
public class epl extends ApplicationAdapter {
MyTextInputListener listener = new MyTextInputListener();
SpriteBatch batch;
Texture background;
Texture[] man;
State[] gsm;
int batsmanState = 0;
int pause = 0;
float gravity = 0.2f;
float velocity = 0;
int manY = 0;
Rectangle manRectangle;
BitmapFont font1;
BitmapFont font2;
BitmapFont font3;
Texture dizzy;
int score = 0;
int gameState = 0;
int i1 = 0;
int i2 = 0;
State state0;
State state1;
State state2;
State state3;
State state4;
State state5;
Random random;
String humanName;
ArrayList<Integer> coinXs = new ArrayList<>();
ArrayList<Integer> coinYs = new ArrayList<>();
ArrayList<Rectangle> coinRectangles = new ArrayList<>();
Texture coin;
int coinCount;
ArrayList<Integer> bombXs = new ArrayList<>();
ArrayList<Integer> bombYs = new ArrayList<>();
ArrayList<Rectangle> bombRectangles = new ArrayList<>();
Texture bomb;
int bombCount;
PlayServices ply;
#Override
public void create() {
batch = new SpriteBatch();
background = new Texture("bg.png");
man = new Texture[4];
man[0] = new Texture("batsman.jpg");
man[1] = new Texture("batsman.jpg");
man[2] = new Texture("batsman.jpg");
man[3] = new Texture("batsman.jpg");
gsm = new State[6];
gsm[0] = (state0);
gsm[1] = (state1);
gsm[2] = (state2);
gsm[3] = (state3);
gsm[4] = (state4);
gsm[5] = (state5);
manY = Gdx.graphics.getHeight() / 2;
coin = new Texture("ball.png");
bomb = new Texture("stump.jpeg");
random = new Random();
dizzy = new Texture("out.jpeg");
font1 = new BitmapFont();
font1.setColor(Color.RED);
font1.getData().setScale(10);
font2 = new BitmapFont();
font2.setColor(Color.RED);
font2.getData().setScale(10);
font3 = new BitmapFont();
font3.setColor(Color.RED);
font3.getData().setScale(10);
}
public void makeCoin() {
float height = random.nextFloat() * Gdx.graphics.getHeight();
coinYs.add((int) height);
coinXs.add(Gdx.graphics.getWidth());
}
public void makeBomb() {
float height = random.nextFloat() * Gdx.graphics.getHeight();
bombYs.add((int)height);
bombXs.add(Gdx.graphics.getWidth());
}
private String myText;
public class MyTextInputListener implements Input.TextInputListener {
#Override
public void input(String text) {
}
#Override
public void canceled() {
whatIsYourName();
}
public String getText() {
return myText;
}
public void whatIsYourName() {
Gdx.input.getTextInput(listener, "Name : ", "", "eg:Jonathan");
humanName = listener.getText();
gameState = 1;
}
}
public epl(PlayServices ply){
this.ply = ply;
}
#Override
public void render () {
batch.begin();
batch.draw(background, 0, 0, Gdx.graphics.getWidth(),
Gdx.graphics.getHeight());
if (gameState == 1 && state1 == null) {
// GAME IS LIVE
// BOMB
if (bombCount < 250) {
bombCount++;
} else {
bombCount = 0;
makeBomb();
}
bombRectangles.clear();
for (int i = 0; i < bombXs.size(); i++) {
batch.draw(bomb, bombXs.get(i), bombYs.get(i));
bombXs.set(i, bombXs.get(i) - 8);
bombRectangles.add(new Rectangle(bombXs.get(i),
bombYs.get(i),
bomb.getWidth(), bomb.getHeight()));
}
// COINS
if (coinCount < 100) {
coinCount++;
} else {
coinCount = 0;
makeCoin();
}
coinRectangles.clear();
for (int i = 0; i < coinXs.size(); i++) {
batch.draw(coin, coinXs.get(i), coinYs.get(i));
coinXs.set(i, coinXs.get(i) - 4);
coinRectangles.add(new Rectangle(coinXs.get(i),
coinYs.get(i),
coin.getWidth(), coin.getHeight()));
}
if (Gdx.input.justTouched()) {
velocity = -10;
}
if (pause < 8) {
pause++;
} else {
pause = 0;
if (batsmanState < 3) {
batsmanState++;
} else {
batsmanState = 0;
}
}
velocity += gravity;
manY -= velocity;
if (manY <= 0) {
manY = 0;
}
} else if (gameState == 5 && state5 == null) {
//leaderboard
if (Gdx.input.justTouched()){
ply.submitScore(humanName,score);
ply.showScore(humanName);
gameState = 1;
}
}else if (gameState == 3 && state3 == null) {
//name
listener.whatIsYourName();
gameState = 1;
} else if (gameState == 0 && state0 == null) {
// Waiting to start
if (humanName == null){
gameState = 3;
}else{
gameState = 1;
}
} else if (gameState == 4 && state4 == null) {
//final score display
font3.draw(batch, "Score = " + score,100,1400);
if (Gdx.input.justTouched()){
score = 0;
gameState = 1;
}
}else if (gameState == 2 && state2 == null) {
// GAME OVER
if (Gdx.input.justTouched()) {
manY = Gdx.graphics.getHeight() / 2;
velocity = 0;
coinXs.clear();
coinYs.clear();
coinRectangles.clear();
coinCount = 0;
bombXs.clear();
bombYs.clear();
bombRectangles.clear();
bombCount = 0;
i1 = 0;
i2 = 0;
}
}
if (gameState == 2) {
batch.draw(dizzy, Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY);
if (Gdx.input.justTouched()){
gameState = 4;
}
} else {
batch.draw(man[batsmanState], Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY);
}
manRectangle = new Rectangle(Gdx.graphics.getWidth() / 2 -
man[batsmanState].getWidth() / 2, manY,
man[batsmanState].getWidth(), man[batsmanState].getHeight());
for (int i=0; i < coinRectangles.size();i++) {
if (Intersector.overlaps(manRectangle, coinRectangles.get(i))) {
score++;
i1 = random.nextInt((4 -1) + 1);
score = score + i1;
i2 = i1 + 1;
coinRectangles.remove(i);
coinXs.remove(i);
coinYs.remove(i);
break;
}
}
for (int i=0; i < bombRectangles.size();i++) {
if (Intersector.overlaps(manRectangle, bombRectangles.get(i))) {
gameState = 2;
}
}
font1.draw(batch, String.valueOf(score),100,200);
font2.draw(batch, String.valueOf(i2),900,200);
batch.end();
}
#Override
public void dispose () {
batch.dispose();
}
}
This is my android launcher
package com.epl.game;
import android.content.Intent;
import android.os.Bundle;
import com.badlogic.gdx.backends.android.AndroidApplication;
import com.google.android.gms.games.Games;
import com.google.example.games.basegameutils.GameHelper;
public class AndroidLauncher extends AndroidApplication implements PlayServices {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gameHelper = new GameHelper(this, GameHelper.CLIENT_GAMES);
gameHelper.enableDebugLog(true);
GameHelper.GameHelperListener gameHelperListener = new GameHelper.GameHelperListener() {
#Override
public void onSignInFailed() {
}
#Override
public void onSignInSucceeded() {
}
};
gameHelper.setup(gameHelperListener);
}
String leaderboard = "CgkI7PuNlqsVEAIQAA";
private GameHelper gameHelper;
#Override
protected void onStart() {
super.onStart();
gameHelper.onStart(this); // You will be logged in to google play services as soon as you open app , i,e on start
}
#Override
protected void onStop() {
super.onStop();
gameHelper.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
gameHelper.onActivityResult(requestCode, resultCode, data);
}
#Override
public boolean signIn() {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
gameHelper.beginUserInitiatedSignIn();
}
});
} catch (Exception e) {
}
return true;
}
#Override
public void submitScore(String LeaderBoard, int highScore) {
if (isSignedIn()) {
Games.Leaderboards.submitScore(gameHelper.getApiClient(), LeaderBoard, highScore);
} else {
System.out.println(" Not signin Yet ");
}
}
#Override
public void showScore(String leaderboard) {
if (isSignedIn()) {
startActivityForResult(Games.Leaderboards.getLeaderboardIntent(gameHelper.getApiClient(), leaderboard), 1);
} else {
signIn();
}
}
#Override
public boolean isSignedIn() {
return false;
}
And this is my play services interface
package com.epl.game;
public interface PlayServices
{
boolean signIn();
void submitScore(String LeaderBoard, int highScore);
void showScore(String LeaderBoard);
boolean isSignedIn();
}
I am new to libgdx and I am trying to create a game with a leaderboard .
I created this by importing the BaseGameUtils .
Else if you have another way i could create a global leaderboard in my
game please let me know.
It is critical that you call the initialize method in onCreate of your AndroidLauncher class. This is what sets up LibGDX's backends for graphics, sound, and input. Since you did not call initialize, the input class (along with graphics, sound, files, etc.) was not set up and assigned, and so is still null when the resume part of the lifecycle is reached. This leads to the NullPointerException.
In your case, your onCreate method should look something like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
// customize the configuration here
initialize(new epl(), config);
// Your other setup code...
}
Note, class names in Java should always start with a capital letter. It will make it easier to read and understand your code.

Exception in Application constructor

I wanna write a Snake game with javaFX , but there is exception that I don't know about and I want to know how to fix it. ( i know it's not complete yet )
and I want to know , the class that extends Application ( with start override )
is exactly the main in other programs?
as you see , here is not static void main BC I didn't need, but if i want to add main where shoud i do?
it's the Exeption...
Exception in Application constructor
Exception in thread "main" java.lang.NoSuchMethodException: Main_Snake.main([Ljava.lang.String;)
at java.lang.Class.getMethod(Class.java:1819)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:125)
and my code is :
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.BorderPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.util.ArrayList;
/**
* Created by Nadia on 1/5/2016.
*/
public class Main_Snake extends Application{
Snake snake = new Snake();
Apple apple = new Apple();
Canvas canvas = new Canvas(800, 600);
boolean goNorth = true, goSouth, goWest, goEast;
int x, y = 0; // marbut be apple
boolean j = false;
// int gm_ov = 0; // vase game over shodan
ArrayList<Integer> X = new ArrayList<Integer>();
ArrayList<Integer> Y = new ArrayList<>();
#Override
public void start(Stage primaryStage) throws Exception {
BorderPane b = new BorderPane(canvas);
Scene scene = new Scene(b, 800, 600);
primaryStage.setScene(scene);
primaryStage.show();
//KeyBoard(scene);
scene.setOnKeyPressed(new EventHandler<KeyEvent>() {
#Override
public void handle(KeyEvent e) {
switch (e.getText()) {
case "w":
if (!goSouth) {
goNorth = true;
goSouth = false;
goWest = false;
goEast = false;
}
break;
case "s":
if (!goNorth) {
goSouth = true;
goNorth = false;
goWest = false;
goEast = false;
}
break;
case "a":
if (!goEast) {
goWest = true;
goEast = false;
goSouth = false;
goNorth = false;
}
break;
case "d":
if (!goWest) {
goEast = true;
goWest = false;
goSouth = false;
goNorth = false;
}
break;
}
}
});
play();
}
public void play(){
AnimationTimer timer = new AnimationTimer() {
private long lastUpdate = 0;
#Override
public void handle(long now) {
if (now - lastUpdate >= 40_000_000) { // payin avordane sor#
snake.pos_S(); // har bar mar rasm mishe bad az move va ye sib ba X,Y khodesh rasm mishe tu tabe move dar morede tabe Point hast
apple.pos_A();
apple.random_Pos();
snake.Move();
lastUpdate = now; // sor#
}
}
};
timer.start();
}
/* public void KeyBoard(Scene scene) {
}*/
}
class Apple extends Main_Snake {
public void random_Pos() {
if (j == false) { // ye sib bede ke ru mar nabashe ( rasmesh tu rasme )
do {
x = (int) (Math.random() * 790 + 1);
y = (int) (Math.random() * 590 + 1);
} while (X.indexOf(x) != -1 && Y.get(X.indexOf(x)) == y || x % 10 != 0 || y % 10 != 0);
/*inja aval chek kardam tu araylist x hast ya na ag bud sharte aval ok hala sharte do ke tu Y ham mibinim tu hamun shomare khune
y barabare y mast ag bud pas ina bar ham montabeghan va sharte dovom ham ok . 2 sharte akhar ham vase ine ke mare ma faghat mazrab
haye 10 and pas ta vaghti in se shart bargharare jahayie ke ma nemikhaym va hey jaye dg mide*/
j = true;
}
}
public void pos_A() {
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.BLACK);
gc.fillRect(x, y, 10, 10);
}
public void Point() {
if (X.get(0) == x && Y.get(0) == y) {
j = false;
}
}
}
class Snake extends Main_Snake {
Snake(){ //cunstructor
X.add(400);
Y.add(300);
X.add(400);
Y.add(310);
X.add(400);
Y.add(320);
X.add(400);
Y.add(330);
X.add(400);
Y.add(340);
}
public void pos_S(){
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.setFill(Color.WHITE);
gc.fillRect(0, 0, canvas.getWidth(), canvas.getHeight());
apple.pos_A();
// keshidane mar (body yeki ezafe tar az adade morabaA mide)
for (int i = X.size() - 1; i >= 0; i--)
gc.fillRect(X.get(i), Y.get(i), 10, 10);
}
public void Move(){
int Px = X.get(X.size() - 1);
int Py = Y.get(Y.size() - 1);
for (int z = X.size() - 1 ; z > 0 ; z--){
X.remove(z);
X.add(z , X.get(z-1) ) ;
Y.remove(z);
Y.add(z , Y.get(z-1) ) ;
}
if (goNorth) {
Y.add(0 , Y.get(0) - 10);
Y.remove(1);
}
if (goSouth) {
Y.add(0 , Y.get(0) + 10);
Y.remove(1);
}
if (goEast) {
X.add(0 , X.get(0) + 10);
X.remove(1);
}
if (goWest) {
X.add(0 , X.get(0) - 10);
X.remove(1);
}
apple.Point(); // emtiaz gerefte
if ( j == false) {
X.add(Px);
Y.add(Py);
}
if ( X.get(0) > 790 ){
X.remove(0);
X.add(0 , 0);
}
if ( X.get(0) < 0 ){
X.remove(0);
X.add(0 , 800);
}
if ( Y.get(0) > 590 ){
Y.remove(0);
Y.add(0 , 0);
}
if ( Y.get(0) < 0 ){
Y.remove(0);
Y.add(0 , 600);
}
}
}
The standard Oracle Java Runtime Environment can execute Application subclasses directly from the command line, even if they do not contain a main method. So assuming you are using a standard JRE, from the command line you can execute
java Main_Snake
and it will run (assuming no other errors, etc).
Other environments, and most IDEs, don't support this execution mode, so if you want to run in those environments (including running in Eclipse, for example), you need a main(...) method which launches your JavaFX application. So just add
public static void main(String[] args) {
launch(args);
}
to the Main_Snake class.

NullPointerException in working with JButtons

public class Node extends JButton {
private Node rightConnection ;
private Node downConnection ;
private Node rightNode ,downNode, leftNode ,upNode;
private ArrayList<String> buttonImages = new ArrayList<String>();
public static void connectNodes(ArrayList<Node> nodes) {
for (int i = 0; i < nodes.size(); i++) {
nodes.get(i).setRightNode((nodes.get(i).getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + 1) : null);
nodes.get(i).setDownNode((nodes.get(i).getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) ? nodes.get(i + Integer.parseInt(SetMap.getMapSize())) : null);
nodes.get(i).setLeftNode((nodes.get(i).getLocation().x / 150 > 0) ? nodes.get(i - 1) : null);
nodes.get(i).setUpNode((nodes.get(i).getLocation().y / 150 > 0) ? nodes.get(i - Integer.parseInt(SetMap.getMapSize())) : null);
}
}
public class SetContent {
private JPanel contentPanel;
private int imgNum;
public SetContent() {
contentPanel = new JPanel(null);
contentPanel.setLocation(1166, 0);
contentPanel.setSize(200, 768);
makeOptionNodes();
}
private void makeOptionNodes() {
MouseListener mouseListener = new DragMouseAdapter();
for (int row = 0; row < 13; row++) {
for (int col = 0; col < 2; col++) {
Node button = new Node();
button.setSize(100, 50);
button.setLocation(col * 100, row * 50);
ImageIcon img = new ImageIcon("src/com/company/" + this.imgNum++ + ".png");
button.setIcon(new ImageIcon(String.valueOf(img)));
// to remote the spacing between the image and button's borders
//button.setMargin(new Insets(0, 0, 0, 0));
// to add a different background
//button.setBackground( ... );
button.setTransferHandler(new TransferHandler("icon"));
button.addMouseListener(mouseListener);
contentPanel.add(button);
}
}
}
}
public class DragMouseAdapter extends MouseAdapter{
String name= new String();
public void mousePressed(MouseEvent e) {
JComponent c = (JComponent) e.getSource();
TransferHandler handler = c.getTransferHandler();
handler.exportAsDrag(c, e, TransferHandler.COPY);
name = handler.getDragImage().toString();// here is another nullpointerException
for(int i = 0 ; i< Integer.parseInt(SetMap.getMapSize()) ; i++) {
if (c.getName().equals(String.valueOf(i))) {
((Node) c).getButtonImages().add(name);
}
}
}
}
public class SetMap {
private static String mapSize;
private JPanel nodesPanel;
private ArrayList<Node> nodes;
public SetMap() {
nodes = new ArrayList<Node>();
for (Node node : nodes) {
node = new Node();
}
nodesPanel = new JPanel(null);
nodesPanel.setLocation(0, 0);
nodesPanel.setSize(1166, 768);
this.mapSize = JOptionPane.showInputDialog(null, "enter map size:");
makeMapNodes();
Node.connectNodes(this.nodes);
makeConnections();
}
private void makeMapNodes() {
for (int row = 0; row < Integer.parseInt(this.mapSize); row++) {
for (int col = 0; col < Integer.parseInt(this.mapSize); col++) {
final Node button = new Node();
button.setRightNode(null);
button.setDownNode(null);
button.setLeftNode(null);
button.setUpNode(null);
button.setRightConnection(null);
button.setDownConnection(null);
button.setTransferHandler(new TransferHandler("icon"));
button.setSize(100, 100);
button.setLocation(col * 150, row * 150);
this.nodes.add(button);
nodesPanel.add(button);
Node.setNodeName(this.nodes, this.nodes.indexOf(button));
button.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
int index = nodes.indexOf(button);
nodes.remove(button);
Node.setNodeName(nodes, index);
button.invalidate();
button.setVisible(false);
if (button.getLocation().x / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getRightConnection().invalidate();
button.getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 < Integer.parseInt(SetMap.getMapSize()) - 1) {
button.getDownConnection().invalidate();
button.getDownConnection().setVisible(false);
}
if (button.getLocation().x / 150 > 0) {
button.getLeftNode().getRightConnection().invalidate();
button.getLeftNode().getRightConnection().setVisible(false);
}
if (button.getLocation().y / 150 > 0) {
button.getUpNode().getDownConnection().invalidate();
button.getUpNode().getDownConnection().setVisible(false);
}
}
});
}
}
}
private void makeConnections() {
for (Node button : this.nodes){
final Node rightConnection = new Node();
final Node downConnection = new Node();
rightConnection.setSize(50, 35);
downConnection.setSize(35, 50);
rightConnection.setLocation(button.getLocation().x + 100, button.getLocation().y + 35);
downConnection.setLocation(button.getLocation().x + 35, button.getLocation().y + 100);
button.setRightConnection(rightConnection);
button.setDownConnection(downConnection);
ImageIcon imgH = new ImageIcon("src/com/company/horizontal.png");
rightConnection.setIcon(new ImageIcon(String.valueOf(imgH)));
ImageIcon imgV = new ImageIcon("src/com/company/vertical.png");
downConnection.setContentAreaFilled(false);
downConnection.setIcon(new ImageIcon(String.valueOf(imgV)));
if(button.getLocation().x / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(rightConnection);
}
if(button.getLocation().y / 150 != Integer.parseInt(this.mapSize)-1) {
nodesPanel.add(downConnection);
}
rightConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
rightConnection.invalidate();
rightConnection.setVisible(false);
}
});
downConnection.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
downConnection.invalidate();
downConnection.setVisible(false);
}
});
}
}
}
public class File {
public static void writeInFile(ArrayList<Node> nodes) {
try {
FileWriter fileWriter = new FileWriter("G:\\file.txt");
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write("[" + SetMap.getMapSize() + "]" + "[" + SetMap.getMapSize() + "]");
bufferedWriter.newLine();
Iterator itr = nodes.iterator();
while (itr.hasNext()) {
Node node = (Node) itr.next();
if (node != null) {
bufferedWriter.write(node.getText());
bufferedWriter.newLine();
bufferedWriter.write("R" + ((node.getRightConnection() != null) ? node.getRightNode().getText() : null) + " D" + ((node.getDownConnection() != null) ? node.getDownNode().getText() : null) + " L" + ((node.getLeftNode().getRightConnection() != null) ? node.getLeftNode().getText() : null) + " U" + ((node.getUpNode().getDownConnection() != null) ? node.getUpNode().getText() : null));//here is the NullPOinterException
bufferedWriter.newLine();
bufferedWriter.write("image");
bufferedWriter.newLine();
Iterator it = node.getButtonImages().iterator();
while (it.hasNext()){
String images = (String) it.next();
bufferedWriter.write(" " + images);
}
}
}
bufferedWriter.close();
fileWriter.close();
} catch (IOException e) {
System.out.println(e);
}
}
}
public class Main {
public static void main(String[] args) {
JFrame mainFrame = new JFrame();
mainFrame.setExtendedState(JFrame.MAXIMIZED_BOTH);
mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
mainFrame.setLayout(null);
final SetMap map = new SetMap();
SetContent options = new SetContent();
mainFrame.add(map.getNodesPanel());
mainFrame.add(options.getContentPanel());
JButton saveButton = new JButton("save");
saveButton.setSize(100, 25);
saveButton.setLocation(1050, 10);
saveButton.addActionListener(new AbstractAction() {
#Override
public void actionPerformed(ActionEvent e) {
File.writeInFile(map.getNodes());
}
});
map.getNodesPanel().add(saveButton);
mainFrame.setVisible(true);
JOptionPane.showMessageDialog(null, "choose nodes and connections you want to remove");
}
}
I'm trying to write the changes that are made on some nodes I added in mapPanel but in the File class the line (which is commented), I get NullPointerException and also for another line in class DragMouseAdapter I get this exception again.
I've omitted some unimportant part of code. I know it's a lot to check code but I would be thankful for any simple help in this case cause I'm a real noob in programming.

Commands sometimes don't work

There is a Canvas which has two Commands. The problem is that when the canvas is first opened then the commands work , but when I open it for the second time then the command doesn't work! Here is the code:
package view;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;
import javax.microedition.lcdui.Canvas;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;
import javax.microedition.lcdui.StringItem;
public class DetailPhotoClient extends Canvas implements CommandListener {
private Command delete, back;
private GaleriePhotos backForm;
private FileConnection fcFile;
private Image sourceImage;
private InputStream is;
private boolean ok,oom, io;
public DetailPhotoClient(GaleriePhotos prevForm, String absolutePathphotoName)
{
super();
back = new Command("Retour", Command.SCREEN, 1);
addCommand(back);
delete = new Command("Supprimer", Command.SCREEN, 2);
addCommand(delete);
setCommandListener(this);
backForm = prevForm;
ok = true;
oom = false;
io = false;
try {
fcFile = (FileConnection) Connector.open(absolutePathphotoName, Connector.READ);
is = fcFile.openInputStream();
sourceImage = Image.createImage(is);
is.close();
fcFile.close();
} catch (IOException ex) {
handleException();
} catch (OutOfMemoryError oome) {
handleOOM();
}
}
private void handleException() {
ok = false;
io = true;
repaint();
}
private void handleOOM() {
ok = false;
oom = true;
repaint();
}
protected void paint(Graphics g) {
StringItem chp;
int chpW;
int x, y = getHeight()/2;
g.fillRect(0, 0, getWidth(), getHeight());
if (ok)
g.drawImage(sourceImage, 0, 0, Graphics.TOP | Graphics.LEFT);
if (io)
{
chp = new StringItem(null,"Erreur média et/ou d'entrée-sortie !");
chpW = chp.getPreferredWidth();
x = ( getWidth() - chpW ) / 2 ;
g.setColor(16711422);
if (x<0)
g.drawString("Erreur média et/ou d'entrée-sortie !", 0, y, Graphics.TOP | Graphics.LEFT);
else
g.drawString("Erreur média et/ou d'entrée-sortie !", x, y, Graphics.TOP | Graphics.LEFT);
}
if (oom)
{
chp = new StringItem(null,"Mémoire insuffisante !");
chpW = chp.getPreferredWidth();
x = ( getWidth() - chpW ) / 2 ;
g.setColor(16711422);
if (x<0)
g.drawString("Mémoire insuffisante !", 0, y, Graphics.TOP | Graphics.LEFT);
else
g.drawString("Mémoire insuffisante !", x, y, Graphics.TOP | Graphics.LEFT);
}
}
public void commandAction(Command c, Displayable d) {
if (c == back)
backForm.showBack();
else
{
backForm.showBack();
backForm.deletePhoto();
}
}
}
So why doesn't the Command work sometimes? Tested the app with an Alcatel OT-806D phone
Well your code is widely exposed to threats related to CommandListener to start with. Look, any piece of code "outside" your class can make your commands irresponsive:
void makeItDeaf(DetailPhotoClient detailPhotoClient) {
detailPhotoClient.setCommandListener(null);
// voila! your commands will be still visible but
// wouldn't respond anymore
}
To make sure that you don't accidentally break the command listener like above, "hide" it about as follows:
//...
public class DetailPhotoClient extends Canvas { // no "implements" here
private Command delete, back;
private GaleriePhotos backForm;
private FileConnection fcFile;
private Image sourceImage;
private InputStream is;
private boolean ok,oom, io;
public DetailPhotoClient(GaleriePhotos prevForm,
String absolutePathphotoName)
{
super();
back = new Command("Retour", Command.SCREEN, 1);
addCommand(back);
delete = new Command("Supprimer", Command.SCREEN, 2);
addCommand(delete);
backForm = prevForm;
setCommandListener(new CommandListener() {
public void commandAction(Command c, Displayable d) {
if (backForm == null) {
System.out.println("backForm is null: ignore command");
return;
}
if (c == back) {
System.out.println("back command");
backForm.showBack();
} else {
System.out.println("delete command");
backForm.showBack();
backForm.deletePhoto();
}
}
});
ok = true;
oom = false;
//...
}
//...
}

java-me bluetooth file send

i am having two cell phones and i want to exchange file between these two.
Device A invoke java app, it will scan available bluetooth device in range, show them into list and user can select one device and click send.
i have written below code, it is not working.
package hello;
import java.io.*;
import java.util.Vector;
import javax.bluetooth.*;
import javax.microedition.io.*;
import javax.microedition.io.StreamConnection.*;
import javax.microedition.lcdui.*;
import javax.microedition.midlet.MIDlet;
import javax.obex.*;
import javax.obex.ResponseCodes;
public class MyMidlet extends MIDlet implements CommandListener, DiscoveryListener
{
public Command cmdSend;
public Command cmdScan;
public TextBox myText;
public List devList;
public Form myForm;
private LocalDevice localDev;
private DiscoveryAgent dAgent;
private ServiceRecord servRecord;
private Vector myVector;
private ClientSession connection = null;
private String url = null;
private Operation op = null;
private boolean cancelInvoked = false;
public MyMidlet()
{
cmdSend = new Command("Send", 2, 0);
cmdScan = new Command("Scan", 5, 0);
}
public void startApp()
{
if(myText == null)
{
myText = new TextBox("Dummy Text", "Hello", 10, 0);
myText.addCommand(cmdScan);
myText.setCommandListener(this);
Display.getDisplay(this).setCurrent(myText);
}
}
public void pauseApp(){}
public void destroyApp(boolean flag) { }
public void commandAction(Command command, Displayable displayable)
{
if(command == cmdScan)
{
if(myForm == null) { myForm = new Form("Scanning"); }
else {
for(int i = 0; i < myForm.size(); i++) myForm.delete(i);
}
myForm.append("Scanning for bluetooth devices..");
Display.getDisplay(this).setCurrent(myForm);
if(devList == null)
{
devList = new List("Devices", 3);
devList.addCommand(cmdSend);
devList.setCommandListener(this);
} else
{
for(int j = 0; j < devList.size(); j++) devList.delete(j);
}
if(myVector == null) myVector = new Vector();
else myVector.removeAllElements();
try
{
if(localDev == null)
{
localDev = LocalDevice.getLocalDevice();
localDev.setDiscoverable(0x9e8b33);
dAgent = localDev.getDiscoveryAgent();
}
dAgent.startInquiry(0x9e8b33, this);
}
catch(BluetoothStateException bluetoothstateexception)
{
myForm.append("Please check your bluetooth is turn-on");
}
}
if(command == cmdSend)
{
myForm.setTitle("Sending");
for(int k = 0; k < myForm.size(); k++) myForm.delete(k);
myForm.append("Sending application..");
Display.getDisplay(this).setCurrent(myForm);
try
{
RemoteDevice remotedevice = (RemoteDevice)myVector.elementAt(devList.getSelectedIndex());
dAgent.searchServices(null, new UUID[] {new UUID(4358L)}, remotedevice, this);
return;
}
catch(BluetoothStateException bluetoothstateexception1)
{
myForm.append("could not open bluetooth: " + bluetoothstateexception1.toString());
}
}
}
public void deviceDiscovered(RemoteDevice remotedevice, DeviceClass deviceclass)
{
try
{
devList.append(remotedevice.getFriendlyName(false), null);
}
catch(IOException _ex)
{
devList.append(remotedevice.getBluetoothAddress(), null);
}
myVector.addElement(remotedevice);
}
public void servicesDiscovered(int i, ServiceRecord aservicerecord[])
{
servRecord = aservicerecord[0];
}
public void serviceSearchCompleted(int i, int j)
{
if(j != 1) myForm.append("service search not completed: " + j);
try
{
byte[] fileContent = "Raxit Sheth -98922 38248".getBytes();
String s=servRecord.getConnectionURL(0, false);
myForm.append("Debug 0");
connection = (ClientSession) Connector.open(s);
myForm.append("Debug1");
HeaderSet headerSet = connection.connect(null);
myForm.append("Debug1.1");
headerSet.setHeader(HeaderSet.NAME, "a.txt");
headerSet.setHeader(HeaderSet.TYPE, "text/plain");
headerSet.setHeader(HeaderSet.LENGTH, new Long(fileContent.length));
myForm.append("Debug1.2");
//op = connection.put(headerSet); throwing java.lang.IllegalArgument.Exception
op = connection.put(null);
myForm.append("Debug1.2.1");
op.sendHeaders(headerSet);
myForm.append("Debug1.3");
OutputStream out = op.openOutputStream();
myForm.append("Debug2");
//sending data
myForm.append("Debug3");
out.write(fileContent);
myForm.append("Debug4");
//int responseCode = op.getResponseCode();
//myForm.append("resp code="+responseCode);
out.close();
op.close();
connection.close();
myForm.append("Done");
//i was expecting this will send a.txt file with content Raxit Sheth -98922 38248
//to remote device's inbox/gallery/bluetooth folder
}
catch(Exception ex) { myForm.append(ex.toString()); }
}
public void inquiryCompleted(int i)
{
Display.getDisplay(this).setCurrent(devList);
}
}
Your problem is almost certainly the fact that you're starting your bluetooth scanning in the commandAction() method. This is a system lifecycle method, and needs to return quickly. Attempting to perform a blocking operations (such as bluetooth scanning) in this thread could tie up resources which the handset needs to do other things such as the actual scanning!
Refactor so that the scanning is performed in a new thread, then try again.

Resources