How to sort search dictionary result based on frequency in j2me - java-me

This is my dictionary format:
word Frequency
Gone 60
Goes 10
Go 30
So far the system returns words eg starting with 'g' as go30, goes10, gone60 as a list.
(alphabetically). I want to increase the accuracy of the system so that the search result is based on frequency. Words with high frequencies appear first. kindly help.
Here is the Text midlet class that reads the dictionary line by line.
public class Text extends MIDlet {
// Fields
private static final String[] DEFAULT_KEY_CODES = {
// 1
".,?!'\"1-()#/:_",
// 2
"ABC2",
// 3
"DEF3",
// 4
"GHI4",
// 5
"JKL5",
// 6
"MNO6",
// 7
"PQRS7",
// 8
"TUV8",
// 9
"WXYZ9",
};
//Initializing inner Classes
public ComposeText() {
cmdHandler = new CommandHandler();
lineVector = new Vector();
}
//Calling All InitMethods, setting Theme, Show MainForm
public void startApp() {
Display.init(this);
setTheme();
initCmd();
initMainGui();
mainFrm.show();
}
public void pauseApp() {
}
public void destroyApp(boolean unconditional) {
}
//Initializing all the Commands
public void initCmd() {
exitCmd = new Command("Exit");
selectCmd = new Command("Ok");
cancelCmd = new Command("Cancel");
predCmd = new Command("Prediction");
sendCmd = new Command("Send");
tfPredArea = new TextField();
//check dictionary
try {
readFile();
} catch (IOException ex) {
ex.printStackTrace();
}
}
//Initiating MainScreen
public void initMainGui() {
mainFrm = new Form("Compose Text");
mainFrm.setLayout(new BorderLayout());
mainFrm.setLayout(new CoordinateLayout(150, 150));
mainFrm.addCommand(exitCmd);
mainFrm.addCommand(predCmd);
mainFrm.addCommand(sendCmd);
mainFrm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(ae.getSource() == predCmd){
initPredGui();
} else if(ae.getSource() == exitCmd){
destroyApp(true);
notifyDestroyed();
}
}
});
// To : 07xxxxxxxxxx
Dimension d1 = new Dimension(130, 20);
lbTo = new Label("To:");
lbTo.setX(10);
lbTo.setY(10);
tfTo = new TextField();
tfTo.setReplaceMenu(false);
tfTo.setConstraint(TextField.NUMERIC);
tfTo.setInputModeOrder(new String[]{"123"});
tfTo.setMaxSize(13);
tfTo.setX(40);
tfTo.setY(10);
tfTo.setPreferredSize(d1);
//Message : Compose Text
Dimension d2 = new Dimension(135, 135);
lbSms = new Label("Message:");
lbSms.setX(5);
lbSms.setY(40);
tfSms = new TextField();
tfSms.setReplaceMenu(false);
tfSms.setX(40);
tfSms.setY(40);
tfSms.setPreferredSize(d2);
//add stuff
mainFrm.addComponent(lbTo);
mainFrm.addComponent(lbSms);
mainFrm.addComponent(tfTo);
mainFrm.addComponent(tfSms);
}
//Initiating FilterSelection Screen
public void initPredGui() {
predForm = new Form("Prediction on");
predForm.setLayout(new CoordinateLayout(150, 150));
predForm.addCommand(cancelCmd);
predForm.addCommand(selectCmd);
//textfied in prediction form
final Dimension d5 = new Dimension(200, 200);
tfPredArea = new TextField();
tfPredArea.setReplaceMenu(false);
tfPredArea.setX(10);
tfPredArea.setY(10);
tfPredArea.setPreferredSize(d5);
predForm.addComponent(tfPredArea);
final ListModel underlyingModel = new DefaultListModel(lineVector);
// final ListModel underlyingModel = new
DefaultListModel(tree.getAllPrefixMatches(avail));
// this is a list model that can narrow down the underlying model
final SortListModel proxyModel = new SortListModel(underlyingModel);
final List suggestion = new List(proxyModel);
tfPredArea.addDataChangeListener(new DataChangedListener() {
public void dataChanged(int type, int index) {
int len = 0;
int i = 0;
String input = tfPredArea.getText();
len = tfPredArea.getText().length();
//ensure start search character is set for each word
if (!(len == 0)) {
for (i = 0; i < len; i++) {
if (input.charAt(i) == ' ') {
k = i;
}
}
String currentInput = input.substring(k + 1, len);
proxyModel.filter(currentInput);
}
}
});
Dimension d3 = new Dimension(110, 120);
suggestion.setX(80);
suggestion.setY(80);
suggestion.setPreferredSize(d3);
predForm.addComponent(suggestion);
suggestion.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String string = suggestion.getSelectedItem().toString();
if (tfPredArea.getText().charAt(0) == 0) {
tfPredArea.setText(string);
}
else if (tfPredArea.getText().length() == 0) {
tfPredArea.setText(string);
} else {
tfPredArea.setText(tfPredArea.getText() + string);
}
}
});
predForm.addCommandListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == addCmd) {
newDictionaryFrm.show();
} else {
mainFrm.show();
}
}
});
predForm.show();
}
//Setting Theme for All Forms
public void setTheme() {
try {
Resources r = Resources.open("/theme.res");
UIManager.getInstance().setThemeProps(r.getTheme(
r.getThemeResourceNames()[0]));
} catch (java.io.IOException e) {
System.err.println("Couldn't load the theme");
}
}
//Inner class CommandHandler
public class CommandHandler implements ActionListener {
public void actionPerformed(ActionEvent ae) {
//cancelCommand from predictionForm
if (ae.getSource() == cancelCmd) {
if (edit) {
mainFrm.show();
// clearFields();
} else if (ae.getSource() == selectCmd){
tfPredList.addDataChangeListener(model);
predForm.show();
}
else{}
}
}
}
// method that reads dictionary line by line
public void readFile() throws IOException {
tree = new Trie();
InputStreamReader reader = new InputStreamReader(
getClass().getResourceAsStream("/Maa Corpus.txt-01-ngrams-Alpha.txt"));
String line = null;
// Read a single line from the file. null represents the EOF.
while ((line = readLine(reader)) != null) {
// Append to a vector to be used as a list
lineVector.addElement(line);
}
}
public String readLine(InputStreamReader reader) throws IOException {
// Test whether the end of file has been reached. If so, return null.
int readChar = reader.read();
if (readChar == -1) {
return null;
}
StringBuffer string = new StringBuffer("");
// Read until end of file or new line
while (readChar != -1 && readChar != '\n') {
// Append the read character to the string.
// This is part of the newline character
if (readChar != '\r') {
string.append((char) readChar);
}
// Read the next character
readChar = reader.read();
}
return string.toString();
}
}
}
The SortListModel Class has a filter method that gets prefix from the textfield datachangeLister
class SortListModel implements ListModel, DataChangedListener {
private ListModel underlying;
private Vector filter;
private Vector listeners = new Vector();
public SortListModel(ListModel underlying) {
this.underlying = underlying;
underlying.addDataChangedListener(this);
}
private int getFilterOffset(int index) {
if(filter == null) {
return index;
}
if(filter.size() > index) {
return ((Integer)filter.elementAt(index)).intValue();
}
return -1;
}
private int getUnderlyingOffset(int index) {
if(filter == null) {
return index;
}
return filter.indexOf(new Integer(index));
}
public void filter(String str) {
filter = new Vector();
str = str.toUpperCase();
for(int iter = 0 ; iter < underlying.getSize() ; iter++) {
String element = (String)underlying.getItemAt(iter);
if(element.toUpperCase().startsWith(str)) // suggest only if smthing
{
filter.addElement(new Integer(iter));
}
}
dataChanged(DataChangedListener.CHANGED, -1);
}
public Object getItemAt(int index) {
return underlying.getItemAt(getFilterOffset(index));
}
public int getSize() {
if(filter == null) {
return underlying.getSize();
}
return filter.size();
}
public int getSelectedIndex() {
return Math.max(0, getUnderlyingOffset(underlying.getSelectedIndex()));
}
public void setSelectedIndex(int index) {
underlying.setSelectedIndex(getFilterOffset(index));
}
public void addDataChangedListener(DataChangedListener l) {
listeners.addElement(l);
}
public void removeDataChangedListener(DataChangedListener l) {
listeners.removeElement(l);
}
public void addSelectionListener(SelectionListener l) {
underlying.addSelectionListener(l);
}
public void removeSelectionListener(SelectionListener l) {
underlying.removeSelectionListener(l);
}
public void addItem(Object item) {
underlying.addItem(item);
}
public void removeItem(int index) {
underlying.removeItem(index);
}
public void dataChanged(int type, int index) {
if(index > -1) {
index = getUnderlyingOffset(index);
if(index < 0) {
return;
}
}
for(int iter = 0 ; iter < listeners.size() ; iter++) {
((DataChangedListener)listeners.elementAt(iter)).dataChanged(type, index);
}
}
}

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.

XPages: How to acces an application scope bean from a session scope bean

I need a value from my application scope managed bean in my session scope managed bean. Not sure how to get this done. Saw a poste here: https://guedebyte.wordpress.com/2012/05/19/accessing-beans-from-java-code-in-xpages-learned-by-reading-the-sourcecode-of-the-extensionlibrary/ But I get a bunch of errors... I also found this: JSF 2.0 Accessing Application Scope bean from another Bean so IM thinking maybe I need to redefine my application bean??? Totally clueless...
How can I make that happen?
Here is the application scope bean's code:
public class AppConfig implements Serializable {
private static final long serialVersionUID = 2768250939591274442L;
public AppConfig() {
initDefaults();
initFromConfigDoc();
}
// Control the number of entries displayed in the widgets
private int nbWidgetFavorites = 0;
private int nbWidgetMostPopular = 0;
private int nbWidgetToolbox = 0;
// Control the number of entries to display in the What's new view
private int nbWhatsNew = 0;
private String showDetailsWhatsNew = "no";
//controls various search options
private int nbSearchResults = 0;
private int nbMaxSearchResults = 0;
//the home page to use for each language
private String homePageUNID_FR = "";
private String homePageUNID_EN = "";
//application email address to use (webmaster)
// DEV ADDRESS
private String appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
// UAT ADDRESS
// PROD ADDRESS
//path to the stats DB
private String statsDB = "";
//application message, if needed
private String systemMessageFR = "";
private String systemMessageEN = "";
//default lang (defined here as session bean will read from the App bean first to
// see if there's a value stored there)
private String defaultLang = "";
//default prov
private String defaultProv = "";
// show Province drop down?
private String showProv = "no";
//various text for "share this link" emails
private String senderEmail = "";
private String senderName = "";
private String appURL = "";
private String emailText = "";
private String clickLinkText = "";
private String emailFooter = "";
private String messageIntro = "";
private String allowRatingModification = "";
/*****************************************************************************/
private void initDefaults() {
// Control the number of entries displayed in the widgets
nbWidgetFavorites = 10;
nbWidgetMostPopular = 10;
nbWidgetToolbox = 10;
nbWhatsNew = 15;
showDetailsWhatsNew = "no";
nbSearchResults = 25;
nbMaxSearchResults = 100;
homePageUNID_FR = "";
homePageUNID_EN = "";
appEmailAddress = "DEVTEAMTEST/DEV#DEVELOPMENTCORP";
statsDB = "belair\\xBiblioStats.nsf";
systemMessageFR = "";
systemMessageEN = "";
defaultLang = "FR";
defaultProv = "QC";
showProv = "no";
allowRatingModification = "1";
}
/*****************************************************************************/
public boolean persistToConfigDoc() {
//write content of sessionScope vars to config doc
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc == null) {
doc = db.createDocument();
doc.replaceItemValue("form", "AppConfig");
}
doc.replaceItemValue("nbWidgetFavorites", this.nbWidgetFavorites);
doc.replaceItemValue("nbWidgetMostPopular", this.nbWidgetMostPopular);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWidgetToolbox", this.nbWidgetToolbox);
doc.replaceItemValue("nbWhatsNew", this.nbWhatsNew);
doc.replaceItemValue("showDetailsWhatsNew", this.showDetailsWhatsNew);
doc.replaceItemValue("nbSearchResults", this.nbSearchResults);
doc.replaceItemValue("nbMaxSearchResults", this.nbMaxSearchResults);
doc.replaceItemValue("homePageUNID_FR", this.homePageUNID_FR);
doc.replaceItemValue("homePageUNID_EN", this.homePageUNID_EN);
doc.replaceItemValue("appEmailAddress", this.appEmailAddress);
doc.replaceItemValue("statsDB", this.statsDB);
doc.replaceItemValue("systemMessageFR", this.systemMessageFR);
doc.replaceItemValue("systemMessageEN", this.systemMessageEN);
doc.replaceItemValue("defaultLang", this.defaultLang);
doc.replaceItemValue("defaultProv", this.defaultProv);
doc.replaceItemValue("showProv", this.showProv);
doc.replaceItemValue("senderEmail", this.senderEmail);
doc.replaceItemValue("senderName", this.senderName);
doc.replaceItemValue("appURL", this.appURL);
doc.replaceItemValue("emailText", this.emailText);
doc.replaceItemValue("clickLinkText", this.clickLinkText);
doc.replaceItemValue("emailFooter", this.emailFooter);
doc.replaceItemValue("messageIntro", this.messageIntro);
doc.replaceItemValue("allowRatingModification", this.allowRatingModification);
doc.save();
return true;
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
/*****************************************************************************/
public void initFromConfigDoc() {
try {
Database db = ExtLibUtil.getCurrentSession().getCurrentDatabase();
View view = db.getView("AppConfig");
Document doc = view.getFirstDocument();
if(doc != null) {
//load default values
if(doc.hasItem("nbWidgetFavorites")) {
int tmp = doc.getItemValueInteger("nbWidgetFavorites");
if(tmp > 0) {
this.nbWidgetFavorites = tmp;
}
}
if(doc.hasItem("nbWidgetMostPopular")) {
int tmp = doc.getItemValueInteger("nbWidgetMostPopular");
if(tmp > 0) {
this.nbWidgetMostPopular = tmp;
}
}
if(doc.hasItem("nbWidgetToolbox")) {
int tmp = doc.getItemValueInteger("nbWidgetToolbox");
if(tmp > 0) {
this.nbWidgetToolbox = tmp;
}
}
if(doc.hasItem("nbWhatsNew")) {
int tmp = doc.getItemValueInteger("nbWhatsNew");
if(tmp > 0) {
this.nbWhatsNew = tmp;
}
}
if(doc.hasItem("showDetailsWhatsNew")) {
String tmp = doc.getItemValueString("showDetailsWhatsNew");
this.showDetailsWhatsNew = tmp;
}
if(doc.hasItem("nbSearchResults")) {
int tmp = doc.getItemValueInteger("nbSearchResults");
if(tmp > 0) {
this.nbSearchResults = tmp;
}
}
if(doc.hasItem("nbMaxSearchResults")) {
int tmp = doc.getItemValueInteger("nbMaxSearchResults");
if(tmp > 0) {
this.nbMaxSearchResults = tmp;
}
}
if(doc.hasItem("homePageUNID_FR")) {
String tmp = doc.getItemValueString("homePageUNID_FR");
if(!"".equals(tmp)) {
this.homePageUNID_FR = tmp;
}
}
if(doc.hasItem("homePageUNID_EN")) {
String tmp = doc.getItemValueString("homePageUNID_EN");
if(!"".equals(tmp)) {
this.homePageUNID_EN = tmp;
}
}
if(doc.hasItem("appEmailAddress")) {
String tmp = doc.getItemValueString("appEmailAddress");
if(!"".equals(tmp)) {
this.appEmailAddress = tmp;
}
}
if(doc.hasItem("statsDB")) {
String tmp = doc.getItemValueString("statsDB");
if(!"".equals(tmp)) {
this.statsDB = tmp;
}
}
if(doc.hasItem("systemMessageFR")) {
String tmp = doc.getItemValueString("systemMessageFR");
if(!"".equals(tmp)) {
this.systemMessageFR = tmp;
}
}
if(doc.hasItem("systemMessageEN")) {
String tmp = doc.getItemValueString("systemMessageEN");
if(!"".equals(tmp)) {
this.systemMessageEN = tmp;
}
}
if(doc.hasItem("defaultLang")) {
String tmp = doc.getItemValueString("defaultLang");
if(!"".equals(tmp)) {
this.defaultLang = tmp;
}
}
if(doc.hasItem("defaultProv")) {
String tmp = doc.getItemValueString("defaultProv");
if(!"".equals(tmp)) {
this.defaultProv = tmp;
}
}
if(doc.hasItem("showProv")) {
String tmp = doc.getItemValueString("showProv");
if(!"".equals(tmp)) {
this.showProv = tmp;
}
}
if(doc.hasItem("senderEmail")) {
String tmp = doc.getItemValueString("senderEmail");
if(!"".equals(tmp)) {
this.senderEmail = tmp;
}
}
if(doc.hasItem("senderName")) {
String tmp = doc.getItemValueString("senderName");
if(!"".equals(tmp)) {
this.senderName = tmp;
}
}
if(doc.hasItem("appURL")) {
String tmp = doc.getItemValueString("appURL");
if(!"".equals(tmp)) {
this.appURL = tmp;
}
}
if(doc.hasItem("emailText")) {
String tmp = doc.getItemValueString("emailText");
if(!"".equals(tmp)) {
this.emailText = tmp;
}
}
if(doc.hasItem("clickLinkText")) {
String tmp = doc.getItemValueString("clickLinkText");
if(!"".equals(tmp)) {
this.clickLinkText = tmp;
}
}
if(doc.hasItem("emailFooter")) {
String tmp = doc.getItemValueString("emailFooter");
if(!"".equals(tmp)) {
this.emailFooter = tmp;
}
}
if(doc.hasItem("messageIntro")) {
String tmp = doc.getItemValueString("messageIntro");
if(!"".equals(tmp)) {
this.messageIntro = tmp;
}
}
//allowRatingModification
if(doc.hasItem("allowRatingModification")) {
String tmp = doc.getItemValueString("allowRatingModification");
if(!"".equals(tmp)) {
this.allowRatingModification = tmp;
}
}
}
} catch (NotesException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*****************************************************************************/
public int getNbWidgetFavorites() {
return nbWidgetFavorites;
}
public void setNbWidgetFavorites(int nbWidgetFavorites) {
this.nbWidgetFavorites = nbWidgetFavorites;
}
public int getNbWidgetMostPopular() {
return nbWidgetMostPopular;
}
public void setNbWidgetMostPopular(int nbWidgetMostPopular) {
this.nbWidgetMostPopular = nbWidgetMostPopular;
}
public int getNbWidgetToolbox() {
return nbWidgetToolbox;
}
public void setNbWidgetToolbox(int nbWidgetToolbox) {
this.nbWidgetToolbox = nbWidgetToolbox;
}
public void setNbWhatsNew(int nbWhatsNew) {
this.nbWhatsNew = nbWhatsNew;
}
public int getNbWhatsNew() {
return nbWhatsNew;
}
public void setShowDetailsWhatsNew(String showDetailsWhatsNew) {
this.showDetailsWhatsNew = showDetailsWhatsNew;
}
public String getShowDetailsWhatsNew() {
return showDetailsWhatsNew;
}
public int getNbSearchResults() {
return nbSearchResults;
}
public void setNbSearchResults(int nbSearchResults) {
this.nbSearchResults = nbSearchResults;
}
public int getNbMaxSearchResults() {
return nbMaxSearchResults;
}
public void setNbMaxSearchResults(int nbMaxSearchResults) {
this.nbMaxSearchResults = nbMaxSearchResults;
}
public String getHomePageUNID_FR() {
return homePageUNID_FR;
}
public void setHomePageUNID_FR(String homePageUNID_FR) {
this.homePageUNID_FR = homePageUNID_FR;
}
public String getHomePageUNID_EN() {
return homePageUNID_EN;
}
public void setHomePageUNID_EN(String homePageUNID_EN) {
this.homePageUNID_EN = homePageUNID_EN;
}
public String getAppEmailAddress() {
return appEmailAddress;
}
public void setAppEmailAddress(String appEmailAddress) {
this.appEmailAddress = appEmailAddress;
}
public String getSystemMessageFR() {
return systemMessageFR;
}
public void setSystemMessageFR(String systemMessageFR) {
this.systemMessageFR = systemMessageFR;
}
public String getSystemMessageEN() {
return systemMessageEN;
}
public void setSystemMessageEN(String systemMessageEN) {
this.systemMessageEN = systemMessageEN;
}
public void setStatsDB(String statsDB) {
this.statsDB = statsDB;
}
public String getStatsDB() {
return statsDB;
}
public void setDefaultLang(String defaultLang) {
this.defaultLang = defaultLang;
}
public String getDefaultProv() {
return defaultProv;
}
public void setDefaultProv(String defaultPRov) {
this.defaultProv = defaultPRov;
}
public void setShowProv(String showProv) {
this.showProv = showProv;
}
public String getShowProv() {
return showProv;
}
public String getDefaultLang() {
return defaultLang;
}
public String getMessageIntro() {
return messageIntro;
}
public void setMessageIntro(String messageIntro) {
this.messageIntro = messageIntro;
}
public String getSenderEmail() {
return senderEmail;
}
public void setSenderEmail(String senderEmail) {
this.senderEmail = senderEmail;
}
public String getSenderName() {
return senderName;
}
public void setSenderName(String senderName) {
this.senderName = senderName;
}
public String getAppURL() {
return appURL;
}
public void setAppURL(String appURL) {
this.appURL = appURL;
}
public String getEmailText() {
return emailText;
}
public void setEmailText(String emailText) {
this.emailText = emailText;
}
public String getClickLinkText() {
return clickLinkText;
}
public void setClickLinkText(String clickLinkText) {
this.clickLinkText = clickLinkText;
}
public String getEmailFooter() {
return emailFooter;
}
public void setEmailFooter(String emailFooter) {
this.emailFooter = emailFooter;
}
//allowRatingModification
public String getAllowRatingModification() {
return allowRatingModification;
}
public void setAllowRatingModification(String allowRatingModification) {
this.allowRatingModification = allowRatingModification;
}
}
The VariableResolver goes through all implicit variables (e.g. session, database) as well as scoped variables (e.g. applicationScope.myVar). Your bean is also accessed from SSJS via the VariableResolver.
So you can use:
ExtLibUtil.resolveVariable(FacesContext.getCurrentInstance(), "myAppScopeBean");
This is not a direct answer to your question...
An alternative would be to set the value you want in applicationScope and then access it this way from your bean. To access the entire bean directly is a different answer.
You use this code get a handle to your applicationScope.
FacesContext facesContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = facesContext.getExternalContext();
Map<String, Object> applicationScope = externalContext.getApplicationMap();
Then to use this you have code like this:
String agentLogDB = (String) applicationScope.get("LOGDB");

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.

Blackberry - How if addElement() doesn't work?

I am a newbie of Blackberry developing application. I try to store all xml parsing data to an object, and set them to a vector.
public class XmlParser extends MainScreen {
Database d;
private HttpConnection hcon = null;
private Vector binN;
public Vector getBinN() {
return binN;
}
public void setBinN(Vector bin) {
this.binN = bin;
}
LabelField from;
LabelField ttl;
LabelField desc;
LabelField date;
public XmlParser() {
LabelField title = new LabelField("Headline News" ,LabelField.HCENTER|LabelField.USE_ALL_WIDTH);
setTitle(title);
try {
URI myURI = URI.create("file:///SDCard/Database/WebFeed.db");
d = DatabaseFactory.open(myURI);
Statement st = d.createStatement("SELECT feed_url, feed_name FROM WebFeed");
st.prepare();
Cursor c = st.getCursor();
while (c.next()) {
Row r = c.getRow();
hcon = (HttpConnection)Connector.open(r.getString(0));
hcon.setRequestMethod(HttpConnection.GET);
hcon.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
hcon.setRequestProperty("Content-Length", "0");
hcon.setRequestProperty("Connection", "close");
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
builder.isValidating();
Document document = builder.parse(hcon.openInputStream());
Element rootElement = document.getDocumentElement();
rootElement.normalize();
NodeList list = document.getElementsByTagName("item");
int i=0;
while (i<10){
Node item = list.item(i);
if(item.getNodeType() != Node.TEXT_NODE) {
NodeList itemChilds = item.getChildNodes();
int j=0;
while (j<10){
Node detailNode = itemChilds.item(j);
if(detailNode.getNodeType() != Node.TEXT_NODE) {
if(detailNode.getNodeName().equalsIgnoreCase("title")) {
ttl = new LabelField(getNodeValue(detailNode)) {
public void paint(Graphics g) {
g.setColor(Color.BLUE);
super.paint(g);
}
};
from = new LabelField(r.getString(1), LabelField.FIELD_RIGHT|LabelField.USE_ALL_WIDTH);
ttl.setFont(Font.getDefault().derive(Font.BOLD));
from.setFont(Font.getDefault().derive(Font.BOLD));
add (from);
add (ttl);
} else if(detailNode.getNodeName().equalsIgnoreCase("description")) {
desc = new LabelField(getNodeValue(detailNode), 0, 70, USE_ALL_WIDTH);
add(desc);
} else if(detailNode.getNodeName().equalsIgnoreCase("dc:date")) {
date = new LabelField(getNodeValue(detailNode), 11, 5, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else if(detailNode.getNodeName().equalsIgnoreCase("pubDate")) {
date = new LabelField(getNodeValue(detailNode), 0, 22, USE_ALL_WIDTH) {
public void paint(Graphics g) {
g.setColor(Color.ORANGE);
super.paint(g);
}
};
add(date);
add(new SeparatorField());
} else {
System.out.println("not the node");
}
} else {
System.out.println("not text node");
}
j++;
}
}
i++;
BinNews bin = new BinNews();
bin.setProv(from.getText());
bin.setTitle(ttl.getText());
bin.setDesc(desc.getText());
bin.setDate(date.getText());
binN.addElement(bin);
}
setBinN(binN);
}
//setBinN(binN);
st.close();
d.close();
} catch (Exception e) {
add (new LabelField(e.toString(),LabelField.HCENTER|LabelField.USE_ALL_WIDTH));
System.out.println(e.toString());
}
}
public String getNodeValue(Node node) {
NodeList nodeList = node.getChildNodes();
Node childNode = nodeList.item(0);
return childNode.getNodeValue();
}
}
I try to store all data from an object called BinNews, to a vector called binN. But when I do debugging, I found that BinN has null value, because "binN.addElement(bin)" doesn't work.
Please advise.
First, you don't actually call setBinN until after the while(i < 10) loop completes. So when you say binN.addElement(bin) then binN will be null.
However your setBinN(binN) call doesn't make sense because you're passing in binN and then setting it to itself which isn't going to do anything.
What you can do is have binN = new Vector(); at the top of the constructor and then it won't be null later on. I don't think the setBinN call will be necessary later on if you're adding the BinNews objects straight to binN.

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