gwt cell table dynamic columns - sorting need an example - sorting

I'm new to GWT and I need to create a sortable dynamic celltable.
I saw an example of IndexedColumn class. I generated a Dynamic cell table (List of ArrayList of String), but couldn't make it sort.
does anybody have a simple implementation example?
Thanks

Found my mistake...
Here is my working example:
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.view.client.ListDataProvider;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class DynamicTable implements EntryPoint {
/**
* This is the entry point method.
*/
public void onModuleLoad() {
List<ArrayList<String>> data = this.getThedata();
CellTable<List<String>> table = new CellTable<List<String>>();
ArrayList<String> dataHeaders = data.remove(0);
ArrayList<IdxColumn> columnList = new ArrayList<IdxColumn>();
ListDataProvider<List<String>> dataProvider = new ListDataProvider<List<String>>();
dataProvider.addDataDisplay(table);
List<List<String>> list = dataProvider.getList();
for (List<String> l : data) {
list.add(l);
}
ListHandler<List<String>> columnSortHandler = new ListHandler<List<String>>(list);
table.getColumnSortList().clear();
for (int i = 0; i < data.get(0).size(); i++) {
final int index = i;
IdxColumn iCol = new IdxColumn(index);
columnList.add(iCol);
table.addColumn(iCol, dataHeaders.get(index) + " (" +iCol.getIndex() + ")");
columnSortHandler.setComparator(iCol, new Comparator<List<String>>() {
public int compare(List<String> o1, List<String> o2) {
if (o1 == o2) {
return 0;
}
if (o1 != null) {
return (o2 != null) ? o1.get(0).compareTo(o2.get(0)) : 1;
}
return -1;
}
});
iCol.setSortable(true);
table.getColumnSortList().push(iCol);
}
table.addColumnSortHandler(columnSortHandler);
table.setRowCount(data.size(), true);
table.setRowData(0, data);
RootPanel.get().add(table);
}
// build the data
private List<ArrayList<String>> getThedata() {
List<ArrayList<String>> data = new ArrayList<ArrayList<String>>();
ArrayList<String> dataHeaders = new ArrayList<String>();
dataHeaders.add("Header 1");
dataHeaders.add("Header 2");
dataHeaders.add("Header 3");
dataHeaders.add("Header 4");
dataHeaders.add("Header 5");
dataHeaders.add("Header 6");
data.add(dataHeaders);
for (int i = 0; i < 20; i++) {
ArrayList<String> dataRow = new ArrayList<String>();
dataRow.add("Col1 Row" + i);
dataRow.add("Col2 Row" + i);
dataRow.add("Col3 Row" + i);
dataRow.add("Col4 Row" + i);
dataRow.add("Col5 Row" + i);
dataRow.add("Col6 Row" + i);
data.add(dataRow);
}
return data;
}
}
And the IdxColumn class:
import java.util.List;
import com.google.gwt.cell.client.TextCell;
import com.google.gwt.user.cellview.client.Column;
public class IdxColumn extends Column<List<String>, String> {
private final int index;
public IdxColumn( int index) {
super(new TextCell());
this.index = index;
}
#Override
public String getValue(List<String> object) {
return object.get(index);
}
public int getIndex() {
return this.index;
}
}

Related

Animation depends on previous animations

I am trying to set node animation, that depends on previous animations of that node as well as other nodes.
To demonstrate the issue I'll use a simple Pane with 4 Label children:
The main class as well as the model and view classes:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javafx.animation.TranslateTransition;
import javafx.application.Application;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;
public final class Puzzle extends Application{
private Controller controller;
#Override
public void start(Stage stage) throws Exception {
controller = new Controller();
BorderPane root = new BorderPane(controller.getBoardPane());
root.setTop(controller.getControlPane());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) { launch();}
}
class View{
private static final double size = 70;
private static Duration animationDuration = Duration.millis(600);
private int[][] cellModels;
private Node[][] cellNodes;
private CountDownLatch latch;
Button play = new Button("Play");
private Pane board, control = new HBox(play);;
View(Model model) {
cellModels = model.getCellModels();
cellNodes = new Node[cellModels.length][cellModels[0].length];
makeBoardPane();
((HBox) control).setAlignment(Pos.CENTER_RIGHT);
}
private void makeBoardPane() {
board = new Pane();
for (int row = 0; row < cellModels.length ; row ++ ) {
for (int col = 0; col < cellModels[row].length ; col ++ ) {
Label label = new Label(String.valueOf(cellModels[row][col]));
label.setPrefSize(size, size);
Point2D location = getLocationByRowCol(row, col);
label.setLayoutX(location.getX());
label.setLayoutY(location.getY());
label.setStyle("-fx-border-color:blue");
label.setAlignment(Pos.CENTER);
cellNodes[row][col] = label;
board.getChildren().add(label);
}
}
}
synchronized void updateCell(int id, int row, int column) {
if(latch !=null) {
try {
latch.await();
} catch (InterruptedException ex) { ex.printStackTrace();}
}
latch = new CountDownLatch(1);
Node node = getNodesById(id).get(0);
Point2D newLocation = getLocationByRowCol(row, column);
Point2D moveNodeTo = node.parentToLocal(newLocation );
TranslateTransition transition = new TranslateTransition(animationDuration, node);
transition.setFromX(0); transition.setFromY(0);
transition.setToX(moveNodeTo.getX());
transition.setToY(moveNodeTo.getY());
//set animated node layout to the translation co-ordinates:
//https://stackoverflow.com/a/30345420/3992939
transition.setOnFinished(ae -> {
node.setLayoutX(node.getLayoutX() + node.getTranslateX());
node.setLayoutY(node.getLayoutY() + node.getTranslateY());
node.setTranslateX(0);
node.setTranslateY(0);
latch.countDown();
});
transition.play();
}
private List<Node> getNodesById(int...ids) {
List<Node> nodes = new ArrayList<>();
for(Node node : board.getChildren()) {
if(!(node instanceof Label)) { continue; }
for(int id : ids) {
if(((Label)node).getText().equals(String.valueOf(id))) {
nodes.add(node);
break;
}
}
}
return nodes ;
}
private Point2D getLocationByRowCol(int row, int col) {
return new Point2D(size * col, size * row);
}
Pane getBoardPane() { return board; }
Pane getControlPane() { return control;}
Button getPlayBtn() {return play ;}
}
class Model{
private int[][] cellModels = new int[][] { {0,1}, {2,3} };
private SimpleObjectProperty<int[][]> cellModelsProperty =
cellModelsProperty = new SimpleObjectProperty<>(cellModels);
void addChangeListener(ChangeListener<int[][]> listener) {
cellModelsProperty.addListener(listener);
}
int[][] getCellModels() {
return (cellModelsProperty == null) ? null : cellModelsProperty.get();
}
void setCellModels(int[][] cellModels) {
cellModelsProperty.set(cellModels);
}
}
and the controller class:
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.layout.Pane;
class Controller {
private View view ;
private Model model;
Controller() {
model = new Model();
model.addChangeListener(getModelCangeListener());//observe model changes
view = new View(model);
view.getPlayBtn().setOnAction( a -> shuffle()); //animation works fine
//view.getPlayBtn().setOnAction( a -> IntStream.
// range(0,4).forEach( (i)-> shuffle())); //messes the animation
}
private ChangeListener<int[][]> getModelCangeListener() {
return (ObservableValue<? extends int[][]> observable,
int[][] oldValue, int[][] newValue)-> {
for (int row = 0; row < newValue.length ; row++) {
for (int col = 0; col < newValue[row].length ; col++) {
if(newValue[row][col] != oldValue[row][col]) {
final int fRow = row, fCol = col;
new Thread( () -> view.updateCell(
newValue[fRow][fCol], fRow, fCol)).start();
}
}
}
};
}
void shuffle() {
int[][] modelData = model.getCellModels();
int rows = modelData.length, columns = modelData[0].length;
int[][] newModelData = new int[rows][columns];
for (int row = 0; row < rows ; row ++) {
for (int col = 0; col < columns ; col ++) {
int colIndex = ((col+1) < columns ) ? col + 1 : 0;
int rowIndex = ((col+1) < columns ) ? row : ((row + 1) < rows) ? row +1 : 0;
newModelData[row][col] = modelData[rowIndex][colIndex];
}
}
model.setCellModels(newModelData);
}
Pane getBoardPane() { return view.getBoardPane(); }
Pane getControlPane() { return view.getControlPane(); }
}
Play button handler changes the model data (see shuffle()), the change triggers ChangeListener. The ChangeListener animates each changed label by invoking view.updateCell(..) on a separate thread. This all works as expected.
The problem starts when I try to run a few consecutive model updates (shuffle()). To simulate it I change
view.getPlayBtn().setOnAction( a -> shuffle());
with
view.getPlayBtn().setOnAction( a -> IntStream.range(0,4).forEach( (i)-> shuffle()));
which messes the animation (it plays in wrong order and ends up in wrong positions).
This does not come as a surprise: to work properly animations have to be played in a certain order: a label should be re-animated only after all four labels finished their previous animation.
The code posted runs each update on a thread, so execution order is not guaranteed.
My question is what is the right way to implement the needed sequence of multiple nodes and multiple animations ?
I looked at SequentialTransition but I couldn't figure out how it can be used to overcome the issue in question.
I did come up with a solution which I will post as an answer, because of the length of this post, and because I don't think the solution is good.
Your code does not adhere to the seperation of concerns principle. (Or at least you don't do it well.)
The animation should be done by the view and the view alone instead of collaborating between the controller and the view. Put all the animations for scheduling the animations in the View class.
SequentialTransition could wrap multiple animations in a single animation that plays them sequentially, but it shouldn't be the controller's concern to do this.
public class View {
private static final double SIZE = 70;
private static final Duration ANIMATION_DURATION = Duration.millis(600);
private final Map<Integer, Label> labelsById = new HashMap<>(); // stores labels by id
private final Button play = new Button("Play");
private Pane board;
private final HBox control;
private final Timeline animation;
private final LinkedList<ElementPosition> pendingAnimations = new LinkedList<>(); // stores parameter combination for update calls
private Node animatedNode;
public View(int[][] cellModels) { // we don't really need the whole model here
makeBoardPane(cellModels);
this.control = new HBox(play);
control.setAlignment(Pos.CENTER_RIGHT);
final DoubleProperty interpolatorValue = new SimpleDoubleProperty();
animation = new Timeline(
new KeyFrame(Duration.ZERO, evt -> {
ElementPosition ePos = pendingAnimations.removeFirst();
animatedNode = labelsById.get(ePos.id);
Point2D newLocation = getLocationByRowCol(ePos.row, ePos.column);
// create binding for layout pos
animatedNode.layoutXProperty().bind(
interpolatorValue.multiply(newLocation.getX() - animatedNode.getLayoutX())
.add(animatedNode.getLayoutX()));
animatedNode.layoutYProperty().bind(
interpolatorValue.multiply(newLocation.getY() - animatedNode.getLayoutY())
.add(animatedNode.getLayoutY()));
}, new KeyValue(interpolatorValue, 0d)),
new KeyFrame(ANIMATION_DURATION, evt -> {
interpolatorValue.set(1);
// remove bindings
animatedNode.layoutXProperty().unbind();
animatedNode.layoutYProperty().unbind();
animatedNode = null;
if (pendingAnimations.isEmpty()) {
// abort, if no more animations are pending
View.this.animation.stop();
}
}, new KeyValue(interpolatorValue, 1d)));
animation.setCycleCount(Animation.INDEFINITE);
}
private void makeBoardPane(int[][] cellModels) {
board = new Pane();
for (int row = 0; row < cellModels.length; row++) {
for (int col = 0; col < cellModels[row].length; col++) {
Point2D location = getLocationByRowCol(row, col);
int id = cellModels[row][col];
Label label = new Label(Integer.toString(id));
label.setPrefSize(SIZE, SIZE);
label.setLayoutX(location.getX());
label.setLayoutY(location.getY());
label.setStyle("-fx-border-color:blue");
label.setAlignment(Pos.CENTER);
labelsById.put(id, label);
board.getChildren().add(label);
}
}
}
private static class ElementPosition {
private final int id;
private final int row;
private final int column;
public ElementPosition(int id, int row, int column) {
this.id = id;
this.row = row;
this.column = column;
}
}
public void updateCell(int id, int row, int column) {
pendingAnimations.add(new ElementPosition(id, row, column));
animation.play();
}
private static Point2D getLocationByRowCol(int row, int col) {
return new Point2D(SIZE * col, SIZE * row);
}
public Pane getBoard() {
return board;
}
public Pane getControlPane() {
return control;
}
public Button getPlayBtn() {
return play;
}
}
Usage example with reduced complexity:
private int[][] oldValue;
#Override
public void start(Stage primaryStage) {
List<Integer> values = new ArrayList<>(Arrays.asList(0, 1, 2, 3));
oldValue = new int[][]{{0, 1}, {2, 3}};
View view = new View(oldValue);
Button btn = new Button("Shuffle");
btn.setOnAction((ActionEvent event) -> {
Collections.shuffle(values);
int[][] newValue = new int[2][2];
for (int i = 0; i < 2 * 2; i++) {
newValue[i / 2][i % 2] = values.get(i);
}
System.out.println(values);
for (int row = 0; row < newValue.length; row++) {
for (int col = 0; col < newValue[row].length; col++) {
if (newValue[row][col] != oldValue[row][col]) {
view.updateCell(newValue[row][col], row, col);
}
}
}
oldValue = newValue;
});
Scene scene = new Scene(new BorderPane(view.getBoard(), null, view.getControlPane(), btn, null));
primaryStage.setScene(scene);
primaryStage.show();
}
The solution I came up with involved controlling the execution order of the updating threads.
Todo it I changed the controller class by implementing an inner class based on this
so answer. See UpdateView in the following code.
I also modified getModelCangeListener() to use UpdateView:
import java.util.stream.IntStream;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.scene.layout.Pane;
class Controller {
private View view ;
private Model model;
private static int threadNumber = 0, threadAllowedToRun = 0;
private static final Object myLock = new Object();
Controller() {
model = new Model();
model.addChangeListener(getModelCangeListener());//observe model changes
view = new View(model);
view.getPlayBtn().setOnAction( a -> IntStream.
range(0,4).forEach( (i)-> shuffle()));
}
private ChangeListener<int[][]> getModelCangeListener() {
return (ObservableValue<? extends int[][]> observable,
int[][] oldValue, int[][] newValue)-> {
for (int row = 0; row < newValue.length ; row++) {
for (int col = 0; col < newValue[row].length ; col++) {
if(newValue[row][col] != oldValue[row][col]) {
final int fRow = row, fCol = col;
new Thread( new UpdateView(
newValue[fRow][fCol], fRow, fCol)).start();
}
}
}
};
}
private void shuffle() {
int[][] modelData = model.getCellModels();
int rows = modelData.length, columns = modelData[0].length;
int[][] newModelData = new int[rows][columns];
for (int row = 0; row < rows ; row ++) {
for (int col = 0; col < columns ; col ++) {
int colIndex = ((col+1) < columns ) ? col + 1 : 0;
int rowIndex = ((col+1) < columns ) ? row : ((row + 1) < rows) ? row +1 : 0;
newModelData[row][col] = modelData[rowIndex][colIndex];
}
}
model.setCellModels(newModelData);
}
Pane getBoardPane() { return view.getBoardPane(); }
Pane getControlPane() { return view.getControlPane(); }
//https://stackoverflow.com/a/23097860/3992939
class UpdateView implements Runnable {
private int id, row, col, threadID;
UpdateView(int id, int row, int col) {
this.id = id; this.row = row; this.col = col;
threadID = threadNumber++;
}
#Override
public void run() {
synchronized (myLock) {
while (threadID != threadAllowedToRun) {
try {
myLock.wait();
} catch (InterruptedException e) {}
}
view.updateCell(id, row, col);
threadAllowedToRun++;
myLock.notifyAll();
}
}
}
}
While it as a possible solution I think a solution based on JavaFx own tools is preferable.
The following answer is based this answer. I refactored it, breaking it into smaller, more verbose "pieces", which makes it (for me) easier to understand.
I am posting it in hope it will help others as well.
import java.util.LinkedList;
import java.util.stream.IntStream;
import javafx.animation.Animation;
import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Point2D;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;
import javafx.util.Duration;
public final class Puzzle extends Application{
private Controller controller;
#Override
public void start(Stage stage) throws Exception {
controller = new Controller();
BorderPane root = new BorderPane(controller.getBoardPane());
root.setTop(controller.getControlPane());
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
}
public static void main(String[] args) { launch();}
}
class Controller {
private View view ;
private Model model;
Controller() {
model = new Model();
model.addChangeListener(getModelCangeListener());//observe model changes
view = new View(model);
view.getPlayBtn().setOnAction( a -> IntStream.
range(0,4).forEach( (i)-> shuffle()));
}
private ChangeListener<int[][]> getModelCangeListener() {
return (ObservableValue<? extends int[][]> observable,
int[][] oldValue, int[][] newValue)-> {
for (int row = 0; row < newValue.length ; row++) {
for (int col = 0; col < newValue[row].length ; col++) {
if(newValue[row][col] != oldValue[row][col]) {
view.updateCell(newValue[row][col], row, col);
}
}
}
};
}
private void shuffle() {
int[][] modelData = model.getCellModels();
int rows = modelData.length, columns = modelData[0].length;
int[][] newModelData = new int[rows][columns];
for (int row = 0; row < rows ; row ++) {
for (int col = 0; col < columns ; col ++) {
int colIndex = ((col+1) < columns ) ? col + 1 : 0;
int rowIndex = ((col+1) < columns ) ? row : ((row + 1) < rows) ? row +1 : 0;
newModelData[row][col] = modelData[rowIndex][colIndex];
}
}
model.setCellModels(newModelData);
}
Pane getBoardPane() { return view.getBoardPane(); }
Pane getControlPane() { return view.getControlPane(); }
}
class View{
private final Timeline timeLineAnimation;// private final Timeline timeLineAnimation;
private final LinkedList<ElementPosition> pendingAnimations = new LinkedList<>(); // stores parameter combination for update calls
private static final Duration ANIMATION_DURATION = Duration.millis(600);
private static final double SIZE = 70;
private int[][] cellModels;
private final Button play = new Button("Play");
private Pane board, control = new HBox(play);
Node animatedNode;
View(Model model) {
cellModels = model.getCellModels();
makeBoardPane();
((HBox) control).setAlignment(Pos.CENTER_RIGHT);
timeLineAnimation = new TimeLineAnimation().get();
}
private void makeBoardPane() {
board = new Pane();
for (int row = 0; row < cellModels.length ; row ++ ) {
for (int col = 0; col < cellModels[row].length ; col ++ ) {
int id = cellModels[row][col];
Label label = new Label(String.valueOf(id));
label.setPrefSize(SIZE, SIZE);
Point2D location = getLocationByRowCol(row, col);
label.setLayoutX(location.getX());
label.setLayoutY(location.getY());
label.setStyle("-fx-border-color:blue");
label.setAlignment(Pos.CENTER);
label.setId(String.valueOf(id));
board.getChildren().add(label);
}
}
}
public void updateCell(int id, int row, int column) {
pendingAnimations.add(new ElementPosition(id, row, column));
timeLineAnimation.play();
}
private Node getNodeById(int id) {
return board.getChildren().filtered(n ->
Integer.valueOf(n.getId()) == id).get(0);
}
private Point2D getLocationByRowCol(int row, int col) {
return new Point2D(SIZE * col, SIZE * row);
}
Pane getBoardPane() { return board; }
Pane getControlPane() { return control;}
Button getPlayBtn() {return play ;}
private static class ElementPosition {
private final int id, row, column;
public ElementPosition(int id, int row, int column) {
this.id = id;
this.row = row;
this.column = column;
}
}
class TimeLineAnimation {
private final Timeline timeLineAnimation;
//value to be interpolated by time line
final DoubleProperty interpolatorValue = new SimpleDoubleProperty();
private Node animatedNode;
TimeLineAnimation() {
timeLineAnimation = new Timeline(getSartKeyFrame(), getEndKeyFrame());
timeLineAnimation.setCycleCount(Animation.INDEFINITE);
}
// a 0 duration event, used to do the needed setup for next key frame
private KeyFrame getSartKeyFrame() {
//executed when key frame ends
EventHandler<ActionEvent> onFinished = evt -> {
//protects against "playing" when no pending animations
if(pendingAnimations.isEmpty()) {
timeLineAnimation.stop();
return;
};
ElementPosition ePos = pendingAnimations.removeFirst();
animatedNode = getNodeById(ePos.id);
Point2D newLocation = getLocationByRowCol(ePos.row, ePos.column);
// bind x,y layout properties interpolated property interpolation effects
//both x and y
animatedNode.layoutXProperty().bind(
interpolatorValue.multiply(newLocation.getX() - animatedNode.getLayoutX())
.add(animatedNode.getLayoutX()));
animatedNode.layoutYProperty().bind(
interpolatorValue.multiply(newLocation.getY() - animatedNode.getLayoutY())
.add(animatedNode.getLayoutY()));
};
KeyValue startKeyValue = new KeyValue(interpolatorValue, 0d);
return new KeyFrame(Duration.ZERO, onFinished, startKeyValue);
}
private KeyFrame getEndKeyFrame() {
//executed when key frame ends
EventHandler<ActionEvent> onFinished =evt -> {
// remove bindings
animatedNode.layoutXProperty().unbind();
animatedNode.layoutYProperty().unbind();
};
KeyValue endKeyValue = new KeyValue(interpolatorValue, 1d);
return new KeyFrame(ANIMATION_DURATION, onFinished, endKeyValue);
}
Timeline get() { return timeLineAnimation; }
}
}
class Model{
private int[][] cellModels = new int[][] { {0,1}, {2,3} };
private SimpleObjectProperty<int[][]> cellModelsProperty =
cellModelsProperty = new SimpleObjectProperty<>(cellModels);
void addChangeListener(ChangeListener<int[][]> listener) {
cellModelsProperty.addListener(listener);
}
int[][] getCellModels() {
return (cellModelsProperty == null) ? null : cellModelsProperty.get();
}
void setCellModels(int[][] cellModels) { cellModelsProperty.set(cellModels);}
}
(to run copy paste the entire code into Puzzle.java)

How to display a clob data more than 66k in text field in oracle forms 12g

I don't know how to put clob data which is of more than 66k in Oracle Forms.
The text field will take a long data type and that too not more than 66k. I have a clob data and wanted to display.
The easiest way to display this is too make a forms bean (PJC).
Then you can display it in a JTextPane which is big enough.
You can then make a function that gives you piece of 32000 characters from the clob and give them to the bean.
package be.axi.oracle.forms.jpc;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JScrollPane;
import javax.swing.JTextPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.text.BadLocationException;
import oracle.forms.handler.IHandler;
import oracle.forms.properties.ID;
import oracle.forms.ui.CustomEvent;
import oracle.forms.ui.VBean;
/**
* A TextArea to get more than 64k texts
* #author Francois Degrelle
* #version 1.1
*/
public class BigTextArea extends VBean implements FocusListener, KeyListener
{
private static final long serialVersionUID = 1L;
public final static ID ADDTEXT = ID.registerProperty("ADD_TEXT");
public final static ID VALUE = ID.registerProperty("VALUE");
public final static ID SHOW = ID.registerProperty("SHOW");
public final static ID CLEAR = ID.registerProperty("CLEAR");
public final static ID GETTEXT = ID.registerProperty("GET_TEXT");
public final static ID GETLENGTH = ID.registerProperty("GET_LENGTH");
public final static ID pLostFocus = ID.registerProperty("BEAN_QUITTED");
private IHandler m_handler;
private int iStart = 0 ;
private int iChunk = 8192 ;
private StringBuffer sb = new StringBuffer();
protected JTextPane jtp = new JTextPane();
public BigTextArea()
{
super();
try
{
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI(this);
}
catch (Exception ex)
{
ex.printStackTrace();
}
JScrollPane ps = new JScrollPane(jtp);
ps.setBorder(null);
add(ps);
ps.setVisible(true);
}
public void init(IHandler handler)
{
m_handler = handler;
super.init(handler);
addFocusListener(this);
jtp.addFocusListener(this);
jtp.addKeyListener(this);
}
public boolean setProperty(ID property, Object value)
{
//
// add text to the TextArea
//
if (property == ADDTEXT)
{
sb.append(value.toString()) ;
printMemory();
return true;
}
//
// display the whole text
//
else if(property == SHOW)
{
jtp.setText(sb.toString());
jtp.setCaretPosition(0);
sb = new StringBuffer();
System.gc();
printMemory();
return true ;
}
//
// clear the TextArea
//
else if(property == CLEAR) {
jtp.setText("");
return true ;
}
else
{
return super.setProperty(property, value);
}
}
/*-----------------------------------*
* Get the result string from Forms *
*-----------------------------------*/
public Object getProperty(ID pId)
{
//
// returns the text length
//
if (pId == GETLENGTH)
{
return "" + jtp.getText().length();
}
//
// returns the chunks
//
else if (pId == GETTEXT) {
String s = "" ;
int iLen = jtp.getText().length() ;
while (iStart < iLen)
{
try{
if(iStart+iChunk <= iLen) s = jtp.getText(iStart,iChunk);
else s = jtp.getText(iStart,iLen-iStart);
iStart += iChunk ;
return s ;
}
catch (BadLocationException ble) { ble.printStackTrace(); return ""; }
}
iStart = 0 ;
return "" ;
}
else
{
return super.getProperty(pId);
}
} // getProperty()
/*--------------------------*
* handle the focus events *
*--------------------------*/
public void focusGained(FocusEvent e)
{
if (e.getComponent() == this)
{
// put the focus on the component
jtp.requestFocus();
}
try
{
m_handler.setProperty(FOCUS_EVENT, e);
}
catch ( Exception ex )
{
;
}
}
public void focusLost(FocusEvent e)
{
CustomEvent ce = new CustomEvent(m_handler, pLostFocus);
dispatchCustomEvent(ce);
}
/*--------------------------*
* Handle the Key listener *
*--------------------------*/
public void keyPressed(KeyEvent e)
{
/*
** Allows TAB key to exit the item
** and continue the standard Forms navigation
*/
if ( (e.getKeyCode() == KeyEvent.VK_TAB) )
{
try
{
m_handler.setProperty(KEY_EVENT, e);
}
catch ( Exception ex )
{
}
}
}
public void keyTyped(KeyEvent e)
{
}
public void keyReleased(KeyEvent e)
{
}
// utility to output the memory available
private void printMemory() {
System.out.println("Java memory in use = "
+ (Runtime.getRuntime().totalMemory()
- Runtime.getRuntime().freeMemory()));
}
}

How to retrieve data from mysql database from what is the input on my textfield

For example I have entered my pin to 123 in my text field I want that program to Show the balance, card number and account number of that certain pin
i used setters and getters to get the pin from the previous frame (login)
Here is my code
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.event.*;
import java.sql.*;
import javax.swing.table.*;
public class Test extends JFrame
{
private static final Test sh1 = new Test();
public static Test getInstance()
{
return sh1;
}
Container c;
Connection con;
Statement st;
ResultSet rs;
ResultSetMetaData rm;
JTable tb;
JButton btnback = new JButton("Back");
JTextField pin = new JTextField("");
public void setUser(String user) {this.pin.setText(user);}
public String getUser() {return this.pin.getText();}
public Test(){
this.setTitle("Data");
this.setSize(500,500);
this.setLocation(800, 80);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
c=this.getContentPane();
c.setLayout(new FlowLayout());
c.add(btnback);
c.add(pin);
stud();
}
public void stud()
{
Vector ColName = new Vector();
Vector Data = new Vector();
try{
String driver="com.mysql.jdbc.Driver";
String db="jdbc:mysql://localhost:3306/atm";
String user="root";
String pass="";
Class.forName(driver);
con=DriverManager.getConnection(db,user,pass);
st=con.createStatement();
String pincodee = pin.getText().trim();
String sqltb = "Select balance,cardnumber , accountnumber from accounts WHERE "
+ "pincode = '"+pincodee+"' ";
rs = st.executeQuery(sqltb);
rm = rs.getMetaData();
int col = rm.getColumnCount();
for(int i = 1; i <= col; i++)
{
ColName.addElement(rm.getColumnName(i));
}
while(rs.next())
{
Vector row = new Vector(col);
for(int i = 1; i <= col; i++)
{
row.addElement(rs.getObject(i));
String s = rs.getString(2);
pin.setText(s);
}
Data.addElement(row);
}
}
catch (Exception ex)
{
}
tb = new JTable( Data, ColName);
tb.repaint();
JScrollPane sc = new JScrollPane(tb);
sc.validate();
c.add(sc);
}
public static void main(String[] args)
{
Test s = new Test();
s.setVisible(true);
}
}
You need to create a button which says 'Go!' or something like that and add an action listener to it that calls your stud() method.
look here for example..
http://www.javaprogrammingforums.com/java-swing-tutorials/278-how-add-actionlistener-jbutton-swing.html
Your code is not going to work either way, you need to rewrite a great deal of it but the ActionListener class is your friend if you want actions on the user interface to call logic code.

Why mapper function not called when using SequenceFileInputFormat

I have spent two days on this issue. Thanks in advance if anyone can help! Here is the description:
First mapper and reduce work well, and the output with SequenceFileOutputFormat can be found in the output path.
First mapper:
public static class TextToRecordMapper
extends Mapper<Object, Text, Text, IntArrayWritable>{
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
}
}
First reducer:
public static class MacOneSensorSigCntReducer
extends Reducer<Text,IntArrayWritable,Text,IntArrayWritable> {
public void reduce(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
}
}
The Job part:
Job job = new Job(conf, "word count");
job.setJarByClass(RawInputText.class);
job.setMapperClass(TextToRecordMapper.class);
job.setReducerClass(MacOneSensorSigCntReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntArrayWritable.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
job.waitForCompletion(true);
This works well, and then I add my second mapper and reducer to deal with the output of the first part.
Second mapper:
public static class MacSensorsTimeLocMapper
extends Mapper<Text,IntArrayWritable,Text,IntWritable> {
private Text macInfo = new Text();
public void map(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
}
}
Second reducer:
public static class MacInfoTestReducer
extends Reducer<Text,IntWritable,Text,Text> {
public void reduce(Text key, Iterable<IntWritable> values,
Context context
) throws IOException, InterruptedException {
}
}
The Job part:
Job secondJob = new Job(conf, "word count 2");
secondJob.setJarByClass(RawInputText.class);
FileInputFormat.addInputPath(secondJob, new Path(otherArgs[1]));
secondJob.setInputFormatClass(SequenceFileInputFormat.class);
secondJob.setMapperClass(MacSensorsTimeLocMapper.class);
secondJob.setMapOutputKeyClass(Text.class);
secondJob.setMapOutputValueClass(IntArrayWritable.class);
//do not use test reducer to make things simple
//secondJob.setReducerClass(MacInfoTestReducer.class);
FileOutputFormat.setOutputPath(secondJob, new Path(otherArgs[2]));
System.exit(secondJob.waitForCompletion(true) ? 0 : 1);
The second mapper function is not called when I run the code, and the output is generated with text like the following:
00:08:CA:6C:A2:81 com.hicapt.xike.IntArrayWritable#234265
Seems like the framework calls IdentityMapper instead of mine. But how do I change that to make my mapper be called with SequenceFileInputFormat as the input format.
all the code added below:
import java.io.IOException;
import java.util.Collection;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.TreeMap;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.util.GenericOptionsParser;
public class RawInputText {
public static class TextToRecordMapper
extends Mapper<Object, Text, Text, IntArrayWritable>{
private Text word = new Text();
private IntArrayWritable mapv = new IntArrayWritable();
public void map(Object key, Text value, Context context
) throws IOException, InterruptedException {
String line = value.toString();
String[] valArray = line.split(",");
if(valArray.length == 6){
IntWritable[] valInts = new IntWritable[2];
word.set(valArray[0]+"-"+valArray[1]);
valInts[0] = new IntWritable(Integer.parseInt(valArray[2]));
valInts[1] = new IntWritable(Integer.parseInt(valArray[4]));
mapv.set(valInts);
context.write(word, mapv);
}
}
}
public static class MacOneSensorSigCntReducer
extends Reducer<Text,IntArrayWritable,Text,IntArrayWritable> {
private Text macKey = new Text();
private IntArrayWritable macInfo = new IntArrayWritable();
public void reduce(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
String[] keyArray = key.toString().split("-");
if(keyArray.length < 2){
int a = 10;
a= 20;
}
String mac = keyArray[1];
String sen = keyArray[0];
Hashtable<Integer, MinuteSignalInfo> rssiTime = new Hashtable<Integer, MinuteSignalInfo>();
MinuteSignalInfo minSig;
int rssi = 0;
int ts = 0;
int i = 0;
for (IntArrayWritable val : values) {
i = 0;
for(Writable element : val.get()) {
IntWritable eleVal = (IntWritable)element;
if(i%2 == 0)
rssi = eleVal.get();
else
ts = eleVal.get()/60;
i++;
}
minSig = (MinuteSignalInfo)rssiTime.get(ts);
if(minSig == null){
minSig = new MinuteSignalInfo();
minSig.rssi = rssi;
minSig.count = 1;
}else{
minSig.rssi += rssi;
minSig.count += 1;
}
rssiTime.put(ts, minSig);
}
TreeMap<Integer, MinuteSignalInfo> treeMap = new TreeMap<Integer, MinuteSignalInfo>();
treeMap.putAll(rssiTime);
macKey.set(mac);
i = 0;
IntWritable[] valInts = new IntWritable[1+treeMap.size()*3];
valInts[i++] = new IntWritable(Integer.parseInt(sen));
Collection<Integer> macs = treeMap.keySet();
Iterator<Integer> it = macs.iterator();
while(it.hasNext()) {
int tsKey = it.next();
valInts[i++] = new IntWritable(tsKey);
valInts[i++] = new IntWritable(treeMap.get(tsKey).rssi);
valInts[i++] = new IntWritable(treeMap.get(tsKey).count);
}
macInfo.set(valInts);
context.write(macKey, macInfo);
}
}
public static class MacSensorsTimeLocMapper
extends Mapper<Text,IntArrayWritable,Text,IntWritable> {
private Text macInfo = new Text();
public void map(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
int i = 0;
int sensor = 0;
int ts = 0;
int rssi = 0;
int count = 0;
Hashtable<Integer, MinuteSignalInfo> rssiTime = new Hashtable<Integer, MinuteSignalInfo>();
MinuteSignalInfo minSig;
for (IntArrayWritable val : values) {
i = 0;
for(Writable element : val.get()) {
IntWritable eleVal = (IntWritable)element;
int valval = eleVal.get();
if(i == 0) {
sensor = valval;
}else if(i%3 == 1){
ts = valval;
}else if(i%3 == 2){
rssi = valval;
}else if(i%3 == 0){
count = valval;
minSig = (MinuteSignalInfo)rssiTime.get(ts);
if(minSig == null){
minSig = new MinuteSignalInfo();
minSig.rssi = rssi;
minSig.count = count;
minSig.sensor = sensor;
rssiTime.put(ts, minSig);
}else{
if((rssi/count) < (minSig.rssi/minSig.count)){
minSig.rssi = rssi;
minSig.count = count;
minSig.sensor = sensor;
rssiTime.put(ts, minSig);
}
}
}
i++;
}
}
TreeMap<Integer, MinuteSignalInfo> treeMap = new TreeMap<Integer, MinuteSignalInfo>();
treeMap.putAll(rssiTime);
String macLocs = "";
Collection<Integer> tss = treeMap.keySet();
Iterator<Integer> it = tss.iterator();
while(it.hasNext()) {
int tsKey = it.next();
macLocs += String.valueOf(tsKey) + ",";
macLocs += String.valueOf(treeMap.get(tsKey).sensor) + ";";
}
macInfo.set(macLocs);
context.write(key, new IntWritable(10));
//context.write(key, macInfo);
}
}
public static class MacSensorsTimeLocReducer
extends Reducer<Text,IntArrayWritable,Text,Text> {
private Text macInfo = new Text();
public void reduce(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
int i = 0;
int sensor = 0;
int ts = 0;
int rssi = 0;
int count = 0;
Hashtable<Integer, MinuteSignalInfo> rssiTime = new Hashtable<Integer, MinuteSignalInfo>();
MinuteSignalInfo minSig;
for (IntArrayWritable val : values) {
i = 0;
for(Writable element : val.get()) {
IntWritable eleVal = (IntWritable)element;
int valval = eleVal.get();
if(i == 0) {
sensor = valval;
}else if(i%3 == 1){
ts = valval;
}else if(i%3 == 2){
rssi = valval;
}else if(i%3 == 0){
count = valval;
minSig = (MinuteSignalInfo)rssiTime.get(ts);
if(minSig == null){
minSig = new MinuteSignalInfo();
minSig.rssi = rssi;
minSig.count = count;
minSig.sensor = sensor;
rssiTime.put(ts, minSig);
}else{
if((rssi/count) < (minSig.rssi/minSig.count)){
minSig.rssi = rssi;
minSig.count = count;
minSig.sensor = sensor;
rssiTime.put(ts, minSig);
}
}
}
i++;
}
}
TreeMap<Integer, MinuteSignalInfo> treeMap = new TreeMap<Integer, MinuteSignalInfo>();
treeMap.putAll(rssiTime);
String macLocs = "";
Collection<Integer> tss = treeMap.keySet();
Iterator<Integer> it = tss.iterator();
while(it.hasNext()) {
int tsKey = it.next();
macLocs += String.valueOf(tsKey) + ",";
macLocs += String.valueOf(treeMap.get(tsKey).sensor) + ";";
}
macInfo.set(macLocs);
context.write(key, macInfo);
}
}
public static class MacInfoTestReducer
extends Reducer<Text,IntArrayWritable,Text,Text> {
private Text macInfo = new Text();
public void reduce(Text key, Iterable<IntArrayWritable> values,
Context context
) throws IOException, InterruptedException {
String tmp = "";
for (IntArrayWritable val : values) {
for(Writable element : val.get()) {
IntWritable eleVal = (IntWritable)element;
int valval = eleVal.get();
tmp += String.valueOf(valval) + " ";
}
}
macInfo.set(tmp);
context.write(key, macInfo);
}
}
public static void main(String[] args) throws Exception {
Configuration conf = new Configuration();
String[] otherArgs = new GenericOptionsParser(conf, args).getRemainingArgs();
if (otherArgs.length != 3) {
System.err.println("Usage: wordcount <in> <out>");
System.exit(2);
}
/*
Job job = new Job(conf, "word count");
job.setJarByClass(RawInputText.class);
job.setMapperClass(TextToRecordMapper.class);
job.setReducerClass(MacOneSensorSigCntReducer.class);
job.setOutputKeyClass(Text.class);
job.setOutputValueClass(IntArrayWritable.class);
job.setOutputFormatClass(SequenceFileOutputFormat.class);
FileInputFormat.addInputPath(job, new Path(otherArgs[0]));
FileOutputFormat.setOutputPath(job, new Path(otherArgs[1]));
job.waitForCompletion(true);
*/
Job secondJob = new Job(conf, "word count 2");
secondJob.setJarByClass(RawInputText.class);
FileInputFormat.addInputPath(secondJob, new Path(otherArgs[1]));
secondJob.setInputFormatClass(SequenceFileInputFormat.class);
secondJob.setMapperClass(MacSensorsTimeLocMapper.class);
//secondJob.setMapperClass(Mapper.class);
secondJob.setMapOutputKeyClass(Text.class);
secondJob.setMapOutputValueClass(IntArrayWritable.class);
secondJob.setReducerClass(MacInfoTestReducer.class);
//secondJob.setOutputKeyClass(Text.class);
//secondJob.setOutputValueClass(IntArrayWritable.class);
FileOutputFormat.setOutputPath(secondJob, new Path(otherArgs[2]));
System.exit(secondJob.waitForCompletion(true) ? 0 : 1);
}
}
package com.hicapt.xike;
public class MinuteSignalInfo {
public int sensor;
public int rssi;
public int count;
public MinuteSignalInfo() {
rssi = 0;
count = 0;
sensor = 0;
}
}
package com.hicapt.xike;
import org.apache.hadoop.io.ArrayWritable;
import org.apache.hadoop.io.IntWritable;
public class IntArrayWritable extends ArrayWritable {
public IntArrayWritable() {
super(IntWritable.class);
}
/*
public void readFields(DataInput in) throws IOException{
super.readFields(in);
}
public void write(DataOutput out) throws IOException{
super.write(out);
}*/
}

Black Berry Table View

here is my app. how to add table view or grids in the following.
should i draw every thing plz help
this is my code
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.system.*;
import net.rim.device.api.util.*;
import java.util.*;
/*An application in which user enters the data. this data is displayed when user press the save button*/
public class Display extends UiApplication {
/*declaring Strings to store the data of the user*/
String getFirstName;
String getLastName;
String getEmail;
String getGender;
String getStatus;
/*declaring text fields for user input*/
private AutoTextEditField firstName;
private AutoTextEditField lastName;
private EmailAddressEditField email;
/*declaring choice field for user input*/
private ObjectChoiceField gender;
/*declaring check box field for user input*/
private CheckboxField status;
//Declaring button fields
private ButtonField save;
private ButtonField close;
private ButtonField List;
/*declaring vector*/
private static Vector _data;
/*declaring persistent object*/
private static PersistentObject store;
/*creating an entry point*/
public static void main(String[] args)
{
Display obj = new Display();
obj.enterEventDispatcher();
}
/*creating default constructor*/
public Display()
{
/*Creating an object of the main screen class to use its functionalities*/
MainScreen mainScreen = new MainScreen();
//setting title of the main screen
mainScreen.setTitle(new LabelField("Enter Your Data"));
//creating text fields for user input
firstName = new AutoTextEditField("First Name: ", "");
lastName= new AutoTextEditField("Last Name: ", "");
email= new EmailAddressEditField("Email:: ", "");
//creating choice field for user input
String [] items = {"Male","Female"};
gender= new ObjectChoiceField("Gender",items);
//creating Check box field
status = new CheckboxField("Active",true);
//creating Button fields and adding functionality using listeners
save = new ButtonField("Save",ButtonField.CONSUME_CLICK);
save.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
save();
}
});
close = new ButtonField("Close",ButtonField.CONSUME_CLICK);
close.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context)
{
onClose();
}
});
List = new ButtonField("List",ButtonField.CONSUME_CLICK);
List.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field, int context){
pushScreen(new ListScreen());
}
});
//adding the input fields to the main screen
mainScreen.add(firstName);
mainScreen.add(lastName);
mainScreen.add(email);
mainScreen.add(gender);
mainScreen.add(status);
//adding buttons to the main screen
HorizontalFieldManager horizontal = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER);
horizontal.add(close);
horizontal.add(save);
horizontal.add(List);
mainScreen.add(horizontal);
//adding menu items
mainScreen.addMenuItem(saveItem);
mainScreen.addMenuItem(getItem);
mainScreen.addMenuItem(Deleteall);
//pushing the main screen
pushScreen(mainScreen);
}
private MenuItem Deleteall = new MenuItem("Delete all",110,10)
{
public void run()
{
int response = Dialog.ask(Dialog.D_YES_NO,"Are u sure u want to delete entire Database");
if(Dialog.YES == response){
PersistentStore.destroyPersistentObject(0xdec6a67096f833cL);
onClose();
}
else
Dialog.inform("Thank God");
}
};
//adding functionality to menu item "saveItem"
private MenuItem saveItem = new MenuItem("Save", 110, 10)
{
public void run()
{
//Calling save method
save();
}
};
//adding functionality to menu item "saveItem"
private MenuItem getItem = new MenuItem("Get", 110, 11)
{
//running thread for this menu item
public void run()
{
//synchronizing thread
synchronized (store)
{
//getting contents of the persistent object
_data = (Vector) store.getContents();
try{
for (int i = _data.size()-1; i >-1; i--)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
getFirstName = (info.getElement(StoreInfo.NAME));
getLastName = (info.getElement(StoreInfo.LastNAME));
getEmail = (info.getElement(StoreInfo.EMail));
getGender = (info.getElement(StoreInfo.GenDer));
getStatus = (info.getElement(StoreInfo.setStatus));
//calling the show method
show();
}
}
}
catch(Exception e){}
}
}
};
public void save()
{
//creating an object of inner class StoreInfo
StoreInfo info = new StoreInfo();
//getting the test entered in the input fields
info.setElement(StoreInfo.NAME, firstName.getText());
info.setElement(StoreInfo.LastNAME,lastName.getText());
info.setElement(StoreInfo.EMail, email.getText());
info.setElement(StoreInfo.GenDer,gender.toString());
if(status.getChecked())
info.setElement(StoreInfo.setStatus, "Active");
else
info.setElement(StoreInfo.setStatus, "In Active");
//adding the object to the end of the vector
_data.addElement(info);
//synchronizing the thread
synchronized (store)
{
store.setContents(_data);
store.commit();
}
//resetting the input fields
Dialog.inform("Success!");
firstName.setText(null);
lastName.setText(null);
email.setText("");
gender.setSelectedIndex("Male");
status.setChecked(true);
}
//coding for persistent store
static {
store =
PersistentStore.getPersistentObject(0xdec6a67096f833cL);
synchronized (store) {
if (store.getContents() == null) {
store.setContents(new Vector());
store.commit();
}
}
_data = new Vector();
_data = (Vector) store.getContents();
}
//new class store info implementing persistable
private static final class StoreInfo implements Persistable
{
//declaring variables
private Vector _elements;
public static final int NAME = 0;
public static final int LastNAME = 1;
public static final int EMail= 2;
public static final int GenDer = 3;
public static final int setStatus = 4;
public StoreInfo()
{
_elements = new Vector(5);
for (int i = 0; i < _elements.capacity(); ++i)
{
_elements.addElement(new String(""));
}
}
public String getElement(int id)
{
return (String) _elements.elementAt(id);
}
public void setElement(int id, String value)
{
_elements.setElementAt(value, id);
}
}
//details for show method
public void show()
{
Dialog.alert("Name is "+getFirstName+" "+getLastName+"\nGender is "+getGender+"\nE-mail: "+getEmail+"\nStatus is "+getStatus);
}
public void list()
{
Dialog.alert("haha");
}
//creating save method
//overriding onClose method
public boolean onClose()
{
System.exit(0);
return true;
}
class ListScreen extends MainScreen
{
String firstUserName="Ali";
String lastUserName="Asif";
String userEmail="assad";
String userGender="asdasd";
String userStatus="active";
private AutoTextEditField userFirstName;
private AutoTextEditField userLastName;
private EmailAddressEditField userMail;
private ObjectChoiceField usersGender;
private CheckboxField usersStatus;
private ButtonField btnBack;
public ListScreen()
{
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hr = new HorizontalFieldManager(HorizontalFieldManager.FIELD_HCENTER|HorizontalFieldManager.HORIZONTAL_SCROLLBAR);
VerticalFieldManager vr = new VerticalFieldManager();
setTitle(new LabelField("List of All Data"));
list();
btnBack = new ButtonField("Back",ButtonField.CONSUME_CLICK);
btnBack.setChangeListener(new FieldChangeListener()
{
public void fieldChanged(Field field,int context)
{
UiApplication.getUiApplication().popScreen(getScreen());
}
});
hr.add(btnBack);
add(hr);
add(sps);
}
public void list()
{
_data = (Vector) store.getContents();
try{
int sn=0;
for (int i = _data.size()-1; i >-1; i--,sn++)
{
StoreInfo info = (StoreInfo)_data.elementAt(i);
//checking for empty object
if (!_data.isEmpty())
{
//if not empty
//create a new object of Store Info class
//storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
//calling the listAll method
listAll();
}
}
}
catch(Exception e){}
}
public void listAll()
{
SeparatorField sp = new SeparatorField();
SeparatorField sps = new SeparatorField();
HorizontalFieldManager hrs = new HorizontalFieldManager(HorizontalFieldManager.HORIZONTAL_SCROLL);
hrs.add(new RichTextField(""+firstUserName+" "+lastUserName+" | "+userEmail+" | "+userGender+" | "+userStatus));
//add(new RichTextField("Email: "+userEmail));
//add(new RichTextField("Gender: "+userGender));
//add(new RichTextField("Status: "+userStatus));
//SeparatorField sp = new SeparatorField();
add(hrs);
add(sp);
add(sps);
}
public boolean onClose()
{
System.exit(0);
return true;
}
}
}
There is a nice GridFieldManager by Anthony Rizk.
Code:
public void list()
{
if (null != mGrid && null != mGrid.getManager())
mGrid.getManager().delete(mGrid);
int colWidth = net.rim.device.api.system.Display.getWidth() / 4;
mGrid = new GridFieldManager(new int[] { 0, colWidth, colWidth,
colWidth, colWidth }, VERTICAL_SCROLL | VERTICAL_SCROLLBAR);
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField("Name"));
mGrid.add(new LabelField("E-Mail"));
mGrid.add(new LabelField("Gender"));
mGrid.add(new LabelField("Active"));
add(mGrid);
_data = (Vector) store.getContents();
try {
int sn = 0;
for (int i = _data.size() - 1; i > -1; i--, sn++) {
StoreInfo info = (StoreInfo) _data.elementAt(i);
// checking for empty object
if (!_data.isEmpty()) {
// if not empty
// create a new object of Store Info class
// storing information retrieved in strings
firstUserName = (info.getElement(StoreInfo.NAME));
lastUserName = (info.getElement(StoreInfo.LastNAME));
userEmail = (info.getElement(StoreInfo.EMail));
userGender = (info.getElement(StoreInfo.GenDer));
userStatus = (info.getElement(StoreInfo.setStatus));
// calling the listAll method
mGrid.add(new NullField(FOCUSABLE));
mGrid.add(new LabelField(firstUserName + " "
+ lastUserName));
mGrid.add(new LabelField(userEmail));
mGrid.add(new LabelField(userGender));
mGrid.add(new LabelField(userStatus));
}
}
} catch (Exception e) {
}
}
See also
BlackBerry Grid Layout Manager updated

Resources