I want to display the table after selecting the values from comboBox. It working first time selection after that it adding another two more table in UI.
Can anyone say how to fix this?
Here the code:
package com.onmo.classes;
import java.io.IOException;
import com.sun.lwuit.Button;
import com.sun.lwuit.ComboBox;
import com.sun.lwuit.Command;
import com.sun.lwuit.Component;
import com.sun.lwuit.Container;
import com.sun.lwuit.Form;
import com.sun.lwuit.Image;
import com.sun.lwuit.Label;
import com.sun.lwuit.TabbedPane;
import com.sun.lwuit.events.ActionEvent;
import com.sun.lwuit.events.ActionListener;
import com.sun.lwuit.events.SelectionListener;
import com.sun.lwuit.layouts.BorderLayout;
import com.sun.lwuit.layouts.BoxLayout;
import com.sun.lwuit.layouts.FlowLayout;
import com.sun.lwuit.plaf.UIManager;
import com.sun.lwuit.table.DefaultTableModel;
import com.sun.lwuit.table.Table;
import com.sun.lwuit.table.TableModel;
import com.sun.lwuit.util.Resources;
public class CompareScreen implements ActionListener, SelectionListener {
private Command enterCmd;
private Command backCmd;
private Command exitCmd;
private Form comparePage;
private Label lblLeagues, lblTeam;
private Button btnTeams, btnPlayers;
private FlowLayout flowLayout;
private ComboBox comboTeamA, comboTeamB, comboTeamC, comboTeamD, player1,
player2;
private Image firstTeamImage, secondTeamImage = null;
private Container teamsContainer, teamCombo, teamImages, playersTeamTab,
playersContainer, playersTab, playerImages;
int count = 0;
CompareScreen(){
enterCmd = new Command("Select");
backCmd = new Command("Back");
exitCmd = new Command("Exit");
}
public void displayCompareScreen() {
comparePage = new Form();
// comparePage.getStyle().setBgColor(0xaa00ff);
String[] teamA = { "Team A", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] teamB = { "Team B", "Villarreal", "Violent Vegans",
"Venom XI", "Betis" };
String[] playerList1 = { "Player1", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
String[] playerList2 = { "Player2", "Acho, Sam", "Adams, Mike",
"Ajirotutu, Seyi", "Abel Gomez" };
comparePage.addCommand(backCmd);
comparePage.addCommandListener(this);
lblLeagues = new Label("Premier League");
lblTeam = new Label("Team");
btnTeams = new Button("Teams");
btnPlayers = new Button("Players");
comboTeamA = new ComboBox(teamA);
comboTeamB = new ComboBox(teamB);
comboTeamC = new ComboBox(teamA);
comboTeamD = new ComboBox(teamB);
player1 = new ComboBox(playerList1);
player2 = new ComboBox(playerList2);
comparePage.setLayout(new BorderLayout());
comparePage
.addComponent(BorderLayout.WEST, new Label("Premier League"));
comparePage.addComponent(BorderLayout.EAST, new Label("Compare"));
flowLayout = new FlowLayout();
comparePage.setLayout(flowLayout);
try {
Resources r = Resources.open("/theme/javathema.res");
UIManager.getInstance().setThemeProps(r.getTheme("javathema"));
} catch (IOException ioe) {
System.out.println("Couldn't load theme.");
}
try {
firstTeamImage = Image.createImage("/team1.png");
secondTeamImage = Image.createImage("/team2.png");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Label lblFirstTeam = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondTeam = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
Label lblFirstPlayer = new Label(firstTeamImage);
lblFirstTeam.setAlignment(Component.LEFT);
Label lblSecondPlayer = new Label(secondTeamImage);
lblSecondTeam.setAlignment(Component.RIGHT);
teamsContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
teamCombo = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamCombo.addComponent(comboTeamA);
teamCombo.addComponent(comboTeamB);
teamImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
teamImages.addComponent(lblFirstTeam);
teamImages.addComponent(lblSecondTeam);
teamsContainer.addComponent(teamCombo);
teamsContainer.addComponent(teamImages);
playersTeamTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTeamTab.addComponent(comboTeamC);
playersTeamTab.addComponent(comboTeamD);
playersTab = new Container(new BoxLayout(BoxLayout.X_AXIS));
playersTab.addComponent(player1);
playersTab.addComponent(player2);
playerImages = new Container(new BoxLayout(BoxLayout.X_AXIS));
playerImages.addComponent(lblFirstPlayer);
playerImages.addComponent(lblSecondPlayer);
playersContainer = new Container(new BoxLayout(BoxLayout.Y_AXIS));
playersContainer.addComponent(playersTeamTab);
playersContainer.addComponent(playersTab);
playersContainer.addComponent(playerImages);
TabbedPane tabbedPane = new TabbedPane(TabbedPane.TOP);
tabbedPane.addTab("Teams", teamsContainer);
tabbedPane.addTab("Players", playersContainer);
// comboTeamA.addSelectionListener(this);
comboTeamB.addSelectionListener(this);
// comboTeamC.addSelectionListener(this);
comboTeamD.addSelectionListener(this);
// comboTeamA.addActionListener(this);
comparePage.addComponent(tabbedPane);
comparePage.show();
}
public void selectionChanged(int arg0, int arg1) {
// TODO Auto-generated method stub
System.out.println("Before :" + count);
Table tableTeam = null, tablePlayer = null;
if (comboTeamA.getSelectedIndex() != 0 && comboTeamB.getSelectedIndex() != 0 && comboTeamC.getSelectedIndex() == 0 && comboTeamD.getSelectedIndex() == 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "7 ", "Wins", " 6" }, { "2 ", "Draws", " 1" },
{ "1 ", "Defeats", " 1" }, { "10 ", "Goals for", " 8" }, });
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
if (comboTeamA.getSelectedIndex() == 0 && comboTeamB.getSelectedIndex() == 0 && comboTeamC.getSelectedIndex() != 0 && comboTeamD.getSelectedIndex() != 0) {
TableModel model = new DefaultTableModel(new String[] { "10 ",
"Games Played", "10" }, new Object[][] {
{ "260 ", "Minutes Played", " 280" },
{ "240 ", "Starts", " 230" },
{ "20 ", "Substitute", " 30" },
{ "6 ", "Goals for", " 9" }, });
tablePlayer = new Table(model);
if (count == 1) {
playersContainer.addComponent(tablePlayer);
count = 0;
}
count = count + 1;
System.out.println("On :" + count);
}
/*
* if(tableTeam != null && tablePlayer != null) {
* teamsContainer.removeComponent(tableTeam);
* playersContainer.removeComponent(tablePlayer); }
*/
System.out.println("After :" + count);
}
public void actionPerformed(ActionEvent arg0) {
// TODO Auto-generated method stub
HomePage homePageObj=HomePage.getInstance();
homePageObj.displayHomePage();
}
}
The problem is at this code:
public void selectionChanged(int arg0, int arg1) {
...
tableTeam = new Table(model);
if (count == 1) {
teamsContainer.addComponent(tableTeam);
count = 0;
}
count = count + 1;
...
}
This code snippet means that you add another Table each time you select another value from the ComboBox : DON'T RESET "count" TO 0 !
Related
In previous code we would use XWPFSParagraph and Runs to find Merge Tokens that we would replace with data in our database. However, now we need to use Content Controls and do the same thing. The problem with Paragraph and Runs is that Content controls do not appear as a single run, like a Merge Token would. And we need to get the content control title to act like a Merge Token name would be so we know where to find the data in the database, and then replace it in the document. In Content Controls we wouldn't be replacing the Content Control with the data from the db, but we would have to set the Text value in the <w:sdtContentControl> with that data.
I thought about converting the <x:sdt> object into the xml text, but then it is now removed from the Poi object because it is now a string on its own.
So I was thinking of finding the <x:sdt> and fully replacing it with a new one where each part of it would be the same except the part in the <w:sdtContentControl> section. Is this possible? Any recommendations on how to use Poi to "modify" the sdt we get from the Word doc?
XWPFSDT as well as XWPFSDTCell are in experimental state up to now. They don't even have access to their underlying CTSdtBlock, CTSdtRun and CTSdtCell classes. I don't know why. So extending them to provide writing into the CTSdtBlock, CTSdtRun or CTSdtCell is not possible. If that is the need, then a new class is needed which can be created from any kind of Word SDT content control object. This class SDTContentControl could look like so:
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentBlock;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSdtContentCell;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTText;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import org.apache.xmlbeans.impl.values.XmlObjectBase;
import javax.xml.namespace.QName;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class SDTContentControl {
private XmlObject object = null;
public SDTContentControl(XmlObject object) {
this.object = object;
}
public String getTitle() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetAlias()) {
return ctSdtBlock.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetAlias()) {
return ctSdtRun.getSdtPr().getAlias().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetAlias()) {
return ctSdtCell.getSdtPr().getAlias().getVal();
}
}
}
return null;
}
public String getTag() {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetTag()) {
return ctSdtBlock.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetTag()) {
return ctSdtRun.getSdtPr().getTag().getVal();
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetTag()) {
return ctSdtCell.getSdtPr().getTag().getVal();
}
}
}
return null;
}
public String getContentText() {
XmlObject[] sdtContents = this.object.selectPath(
"declare namespace w='http://schemas.openxmlformats.org/wordprocessingml/2006/main' "
+".//w:sdtContent");
for (XmlObject sdtContent : sdtContents) {
if (sdtContent instanceof XmlObjectBase) {
return ((XmlObjectBase)sdtContent).getStringValue();
}
}
return null;
}
public void setContent(String text) {
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtContent()) {
CTSdtContentBlock sdtContentBlock = ctSdtBlock.getSdtContent();
CTP ctP = sdtContentBlock.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtBlock.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentBlock.setPArray(new CTP[]{ctP});
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtContent()) {
CTSdtContentRun sdtContentRun = ctSdtRun.getSdtContent();
CTR ctR = CTR.Factory.newInstance();
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtRun.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
sdtContentRun.setRArray(new CTR[]{ctR});
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtContent()) {
CTSdtContentCell sdtContentCell = ctSdtCell.getSdtContent();
for (int c = 0; c < sdtContentCell.getTcList().size(); c++) {
CTTc ctTc = sdtContentCell.getTcList().get(c);
CTP ctP = ctTc.getPArray(0); if (ctP == null) ctP = CTP.Factory.newInstance();
for (int r = ctP.getRList().size()-1; r >= 0 ; r--) ctP.removeR(r);
CTR ctR = ctP.addNewR();
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetRPr()) {
ctR.setRPr(ctSdtCell.getSdtPr().getRPr());
}
}
CTText ctText = ctR.addNewT();
ctText.setStringValue(text);
ctTc.setPArray(new CTP[]{ctP});
}
}
}
}
public void setContent(Calendar calendar) {
String dateFormat = "yyyy-MM-dd";
if (this.object instanceof CTSdtBlock) {
CTSdtBlock ctSdtBlock = (CTSdtBlock)this.object;
if (ctSdtBlock.isSetSdtPr()) {
if (ctSdtBlock.getSdtPr().isSetDate()) {
if (ctSdtBlock.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtBlock.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtBlock.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtRun) {
CTSdtRun ctSdtRun = (CTSdtRun)this.object;
if (ctSdtRun.isSetSdtPr()) {
if (ctSdtRun.getSdtPr().isSetDate()) {
if (ctSdtRun.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtRun.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtRun.getSdtPr().getDate().setFullDate(calendar);
}
}
} else if (this.object instanceof CTSdtCell) {
CTSdtCell ctSdtCell = (CTSdtCell)this.object;
if (ctSdtCell.isSetSdtPr()) {
if (ctSdtCell.getSdtPr().isSetDate()) {
if (ctSdtCell.getSdtPr().getDate().isSetDateFormat()) {
dateFormat = ctSdtCell.getSdtPr().getDate().getDateFormat().getVal();
}
ctSdtCell.getSdtPr().getDate().setFullDate(calendar);
}
}
}
SimpleDateFormat simpledDateFormat = new SimpleDateFormat(dateFormat);
String text = simpledDateFormat.format(calendar.getTime());
this.setContent(text);
}
public void setContent(BigDecimal value) {
DecimalFormat decimalFormat = new DecimalFormat("#,##0.00");
String text = decimalFormat.format(value.doubleValue());
this.setContent(text);
}
public void setContent(Object content) {
if (content instanceof String) {
this.setContent((String)content);
} else if (content instanceof Calendar) {
this.setContent((Calendar)content);
} else if (content instanceof BigDecimal) {
this.setContent((BigDecimal)content);
//} else if (content instanceof ...) {
//ToDo
} else {
this.setContent(String.valueOf(content));
}
}
}
A list of all SDT content control objects can be created from a XWPFDocument like so:
...
/*modifiers*/ List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
...
The SDTContentControl provides methods to get the content control title, the content control tag and the content control text content. It also provides a method to set the content control content from any kind of Object.
Complete example:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.*;
import java.util.List;
import java.util.ArrayList;
import org.apache.xmlbeans.XmlCursor;
import org.apache.xmlbeans.XmlObject;
import javax.xml.namespace.QName;
import java.util.GregorianCalendar;
import java.math.BigDecimal;
public class WordFillContentControls {
private static List<SDTContentControl> extractSDTsFromBody(XWPFDocument document) {
SDTContentControl sdt;
XmlCursor xmlcursor = document.getDocument().getBody().newCursor();
QName qnameSdt = new QName("http://schemas.openxmlformats.org/wordprocessingml/2006/main", "sdt", "w");
List<SDTContentControl> allsdts = new ArrayList<SDTContentControl>();
while (xmlcursor.hasNextToken()) {
XmlCursor.TokenType tokentype = xmlcursor.toNextToken();
if (tokentype.isStart()) {
if (qnameSdt.equals(xmlcursor.getName())) {
if (xmlcursor.getObject() instanceof XmlObject) {
sdt = new SDTContentControl((XmlObject)xmlcursor.getObject());
allsdts.add(sdt);
}
}
}
}
return allsdts;
}
public static void main(String[] args) throws Exception {
String[] contentControlTags = new String[]{
"NameTag", "GenderTag", "DateTag", "AmountTag",
"DescriptionTag", "Col1Tag", "Col2Tag",
"Col1DateTag", "Col2ChooseTag"
};
Object[] contents = new Object[]{
"Axel Richter", "male", new GregorianCalendar(2022, 0, 1), BigDecimal.valueOf(1234.56),
"Lorem ipsum semit dolor ... dolor semit ...", "Blah blah", "Blubb blubb",
new GregorianCalendar(1964, 11, 21), "My choice"
};
XWPFDocument document = new XWPFDocument(new FileInputStream("./WordFormContentControl.docx"));
List<SDTContentControl> allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
//System.out.println(sdt);
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
for (int i = 0; i < contentControlTags.length; i++) {
String tagToReplace = contentControlTags[i];
if (tagToReplace.equals(tag)) {
Object contentO = contents[i];
sdt.setContent(contentO);
}
}
}
allsdts = extractSDTsFromBody(document);
for (SDTContentControl sdt : allsdts) {
String title = sdt.getTitle();
String tag = sdt.getTag();
String content = sdt.getContentText();
System.out.println(title + ": " + tag + ": " + content);
}
FileOutputStream out = new FileOutputStream("./WordFormContentControlResult.docx");
document.write(out);
out.close();
document.close();
}
}
I'm pretty new to android studio. I noticed that my program had a very severe performance hiccup and I believe it is slowing down after I run the app every time. I think I have a runaway thread and I will attach pictures at the end of my post. I could really use some help. The first picture shows an example of the thread and then the second picture shows the thread after 5 minutes or so of waiting. I attached two codes. CameraSurfaceView runs the code while FaceDetectionThread creates the thread.
package com.example.phliip_vision;
import java.util.ArrayList;
import java.util.List;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.AttributeSet;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import com.example.phliip_vision.Point;
import com.example.phliip_vision.MeasurementStepMessage;
import com.example.phliip_vision.MessageHUB;
import com.example.phliip_vision.Util;
public class CameraSurfaceView extends SurfaceView implements Callback,
Camera.PreviewCallback {
public static final int CALIBRATION_DISTANCE_A4_MM = 294;
public static final int CALIBRATION_MEASUREMENTS = 10;
public static final int AVERAGE_THREASHHOLD = 5;
private static final String TAG = "CameraSurfaceView";
/**
* Measured distance at calibration point
*/
private float _distanceAtCalibrationPoint = -1;
private float _currentAvgEyeDistance = -1;
// private int _facesFoundInMeasurement = -1;
/**
* in cm
*/
private float _currentDistanceToFace = -1;
private final SurfaceHolder mHolder;
private Camera mCamera;
private Face _foundFace = null;
private int _threashold = CALIBRATION_MEASUREMENTS;
private FaceDetectionThread _currentFaceDetectionThread;
private List<Point> _points;
protected final Paint _middlePointColor = new Paint();
protected final Paint _eyeColor = new Paint();
private Size _previewSize;
// private boolean _measurementStartet = false;
private boolean _calibrated = false;
private boolean _calibrating = false;
private int _calibrationsLeft = -1;
public CameraSurfaceView(final Context context, final AttributeSet attrs) {
super(context, attrs);
_middlePointColor.setARGB(100, 200, 0, 0);
_middlePointColor.setStyle(Paint.Style.FILL);
_middlePointColor.setStrokeWidth(2);
_eyeColor.setColor(Color.GREEN);
mHolder = getHolder();
mHolder.addCallback(this);
}
public void setCamera(final Camera camera) {
mCamera = camera;
if (mCamera != null) {
requestLayout();
Log.d(TAG, "mCamera RANNNNNNN!!!!");
Camera.Parameters params = mCamera.getParameters();
camera.setDisplayOrientation(90);
List<String> focusModes = params.getSupportedFocusModes();
if (focusModes.contains(Camera.Parameters.FOCUS_MODE_AUTO)) {
Log.d(TAG, "FOCUS_MODE_AUTO RANNNNNNN!!!!");
// set the focus mode
params.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
// set Camera parameters
mCamera.setParameters(params);
}
}
}
/**
* Variables for the onDraw method, in order to prevent variable allocation
* to slow down the sometimes heavily called onDraw method
*/
private final PointF _middlePoint = new PointF();
private final Rect _trackingRectangle = new Rect();
private final static int RECTANGLE_SIZE = 20;
private boolean _showEyes = false;
private boolean _showTracking = true;
#SuppressLint("DrawAllocation")
#Override
protected void onDraw(final Canvas canvas) {
// super.onDraw(canvas);
if (_foundFace != null) {
_foundFace.getMidPoint(_middlePoint);
Log.d(TAG, "_middlePoint RANNNNNNN!!!!");
Log.i("Camera", _middlePoint.x + " : " + _middlePoint.y);
// portrait mode!
float heightRatio = getHeight() / (float) _previewSize.width;
float widthRatio = getWidth() / (float) _previewSize.height;
Log.i("Drawcall", _middlePoint.x + " : " + _middlePoint.y);
int realX = (int) (_middlePoint.x * widthRatio);
int realY = (int) (_middlePoint.y * heightRatio);
Log.i("Drawcall", "Real :" + realX + " : " + realY);
int halfEyeDist = (int) (widthRatio * _foundFace.eyesDistance() / 2);
if (_showTracking) {
// Middle point
Log.d(TAG, "_showTracking RANNNNNNN!!!!");
_trackingRectangle.left = realX - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _middlePointColor);
}
if (_showEyes) {
// Left eye
Log.d(TAG, "_showEyes RANNNNNNN!!!!");
_trackingRectangle.left = realX - halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX - halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
// Right eye
_trackingRectangle.left = realX + halfEyeDist - RECTANGLE_SIZE;
_trackingRectangle.top = realY - RECTANGLE_SIZE;
_trackingRectangle.right = realX + halfEyeDist + RECTANGLE_SIZE;
_trackingRectangle.bottom = realY + RECTANGLE_SIZE;
canvas.drawRect(_trackingRectangle, _eyeColor);
}
}
}
public void reset() {
Log.d(TAG, "reset RANNNNNNN!!!!");
_distanceAtCalibrationPoint = -1;
_currentAvgEyeDistance = -1;
_calibrated = false;
_calibrating = false;
_calibrationsLeft = -1;
}
/**
* Sets this current EYE distance to be the distance of a peace of a4 paper
* e.g. 29,7cm
*/
public void calibrate() {
Log.d(TAG, "calibrate RANNNNNNN!!!!");
if (!_calibrating || !_calibrated) {
_points = new ArrayList<>();
_calibrating = true;
_calibrationsLeft = CALIBRATION_MEASUREMENTS;
_threashold = CALIBRATION_MEASUREMENTS;
}
}
private void doneCalibrating() {
Log.d(TAG, "doneCalibrating RANNNNNNN!!!!");
_calibrated = true;
_calibrating = false;
_currentFaceDetectionThread = null;
// _measurementStartet = false;
_threashold = AVERAGE_THREASHHOLD;
_distanceAtCalibrationPoint = _currentAvgEyeDistance;
MessageHUB.get().sendMessage(MessageHUB.DONE_CALIBRATION, null);
}
public boolean isCalibrated() {
Log.d(TAG, "isCalibrated RANNNNNNN!!!!");
return _calibrated || _calibrating;
}
public void showMiddleEye(final boolean on) {
Log.d(TAG, "showMiddleEye RANNNNNNN!!!!");
_showTracking = on;
}
public void showEyePoints(final boolean on) {
Log.d(TAG, "showEyePoints RANNNNNNN!!!!");
_showEyes = on;
}
private void updateMeasurement(final FaceDetector.Face currentFace) {
if (currentFace == null) {
Log.d(TAG, "updateMeasurement RANNNNNNN!!!!");
// _facesFoundInMeasurement--;
return;
}
_foundFace = _currentFaceDetectionThread.getCurrentFace();
_points.add(new Point(_foundFace.eyesDistance(),
CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _foundFace
.eyesDistance())));
while (_points.size() > _threashold) {
_points.remove(0);
Log.d(TAG, "Removing points RANNNNNNN!!!!");
}
float sum = 0;
for (Point p : _points) {
sum += p.getEyeDistance();
Log.d(TAG, "adding points RANNNNNNN!!!!");
}
_currentAvgEyeDistance = sum / _points.size();
_currentDistanceToFace = CALIBRATION_DISTANCE_A4_MM
* (_distanceAtCalibrationPoint / _currentAvgEyeDistance);
_currentDistanceToFace = Util.MM_TO_CM(_currentDistanceToFace);
MeasurementStepMessage message = new MeasurementStepMessage();
message.setConfidence(currentFace.confidence());
message.setCurrentAvgEyeDistance(_currentAvgEyeDistance);
message.setDistToFace(_currentDistanceToFace);
message.setEyesDistance(currentFace.eyesDistance());
message.setMeasurementsLeft(_calibrationsLeft);
message.setProcessTimeForLastFrame(_processTimeForLastFrame);
MessageHUB.get().sendMessage(MessageHUB.MEASUREMENT_STEP, message);
}
private long _lastFrameStart = System.currentTimeMillis();
private float _processTimeForLastFrame = -1;
#Override
public void onPreviewFrame(final byte[] data, final Camera camera) {
Log.d(TAG, "onPreviewFrame RANNNNNNN!!!!" + _calibrationsLeft);
if (_calibrationsLeft == -1)
return;
if (_calibrationsLeft > 0) {
// Doing calibration !
Log.d(TAG, "_calibrationLeft RANNNNNNN!!!!" + _calibrationsLeft);
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "_currentFaceDectectionThread RANNNNNNN!!!!" + _currentFaceDetectionThread);
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null) {
Log.d(TAG, "_calibrationLeft-- RANNNNNNN!!!!");
_calibrationsLeft--;
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
if (_calibrationsLeft == 0) {
Log.d(TAG, "Calibrating done RANNNNNNN!!!!");
doneCalibrating();
invalidate();
return;
}
}
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
invalidate();
} else {
// Simple Measurement
if (_currentFaceDetectionThread != null
&& _currentFaceDetectionThread.isAlive()) {
Log.d(TAG, "Dropping frames RANNNNNNN!!!!");
// Drop Frame
return;
}
// No face detection started or already finished
_processTimeForLastFrame = System.currentTimeMillis()
- _lastFrameStart;
_lastFrameStart = System.currentTimeMillis();
if (_currentFaceDetectionThread != null)
updateMeasurement(_currentFaceDetectionThread.getCurrentFace());
Log.d(TAG, "Updating measurements RANNNNNNN!!!!");
_currentFaceDetectionThread = new FaceDetectionThread(data,
_previewSize);
_currentFaceDetectionThread.start();
Log.d(TAG, "invalidate RANNNNNNN!!!!");
invalidate();
}
}
/*
* SURFACE METHODS, TO CREATE AND RELEASE SURFACE THE CORRECT WAY.
*
* #see
* android.view.SurfaceHolder.Callback#surfaceCreated(android.view.SurfaceHolder
* )
*/
#Override
public void surfaceCreated(final SurfaceHolder holder) {
synchronized (this) {
// This allows us to make our own drawBitmap
this.setWillNotDraw(false);
}
}
#Override
public void surfaceDestroyed(final SurfaceHolder holder) {
mCamera.release();
mCamera = null;
}
#Override
public void surfaceChanged(final SurfaceHolder holder, final int format,
final int width, final int height) {
if (mHolder.getSurface() == null) {
// preview surface does not exist
return;
}
// stop preview before making changes
try {
mCamera.stopPreview();
} catch (Exception e) {
// ignore: tried to stop a non-existent preview
}
Parameters parameters = mCamera.getParameters();
_previewSize = parameters.getPreviewSize();
// mCamera.setDisplayOrientation(90);
// mCamera.setParameters(parameters);
// start preview with new settings
try {
mCamera.setPreviewDisplay(mHolder);
mCamera.startPreview();
mCamera.setPreviewCallback(this);
} catch (Exception e) {
Log.d("This", "Error starting camera preview: " + e.getMessage());
}
}
}
Here is the other code.
package com.example.phliip_vision;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.YuvImage;
import android.hardware.Camera.Size;
import android.media.FaceDetector;
import android.media.FaceDetector.Face;
import android.util.Log;
public class FaceDetectionThread extends Thread {
public static final String FACEDETECTIONTHREAD_TAG = "FaceDetectionThread_Tag";
private static final String TAG = "FaceDetectionThread";
private Face _currentFace;
private final byte[] _data;
private final Size _previewSize;
private Bitmap _currentFrame;
public FaceDetectionThread(final byte[] data, final Size previewSize) {
Log.d(TAG, "What are we waiting on in FaceDetectionThread????");
_data = data;
_previewSize = previewSize;
}
public Face getCurrentFace() {
Log.d(TAG, "What are we waiting on in Current faces????");
return _currentFace;
}
public Bitmap getCurrentFrame() {
return _currentFrame;
}
/**
* bla bla bla
*/
#Override
public void run() {
long t = System.currentTimeMillis();
YuvImage yuvimage = new YuvImage(_data, ImageFormat.NV21,
_previewSize.width, _previewSize.height, null);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (!yuvimage.compressToJpeg(new Rect(0, 0, _previewSize.width,
_previewSize.height), 100, baos)) {
Log.e("Camera", "compressToJpeg failed");
}
Log.i("Timing", "Compression finished: "
+ (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inPreferredConfig = Bitmap.Config.RGB_565;
_currentFrame = BitmapFactory.decodeStream(new ByteArrayInputStream(
baos.toByteArray()), null, bfo);
Log.i("Timing", "Decode Finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
// Rotate the so it siuts our portrait mode
Matrix matrix = new Matrix();
matrix.postRotate(90);
matrix.preScale(-1, 1);
// We rotate the same Bitmap
_currentFrame = Bitmap.createBitmap(_currentFrame, 0, 0,
_previewSize.width, _previewSize.height, matrix, false);
Log.i("Timing",
"Rotate, Create finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
if (_currentFrame == null) {
Log.e(FACEDETECTIONTHREAD_TAG, "Could not decode Image");
return;
}
FaceDetector d = new FaceDetector(_currentFrame.getWidth(),
_currentFrame.getHeight(), 1);
Face[] faces = new Face[1];
d.findFaces(_currentFrame, faces);
Log.i("Timing",
"FaceDetection finished: " + (System.currentTimeMillis() - t));
t = System.currentTimeMillis();
_currentFace = faces[0];
Log.d(FACEDETECTIONTHREAD_TAG, "Found: " + faces[0] + " Faces");
}
}
enter image description here
enter image description here
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.
I'm trying to use a third party dll called ASPTokenInputLib in my sharepoint2013 webpart .
It was working for a while when I loaded it in the bin directory but when I tried to move it to the GAC it won't work and it's stopped working if I load it in the bin now as well.
The error I get is object reference not set to an instance of an object. The sharepoint logs shows
System.NullReferenceException: Object reference not set to an instance of an object. at ASPTokenInputLib.ASPTokenInput.OnLoad(EventArgs e)
My package manifest file includes
<Assemblies>
<Assembly Location="ASPTokenInputLib.dll" DeploymentTarget="GlobalAssemblyCache" />
<Assembly Location="BidSearchWebPart.dll" DeploymentTarget="GlobalAssemblyCache">
<SafeControls>
<SafeControl Assembly="BidSearchWebPart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=59049686a9425568" Namespace="BidSearchWebPart.VisualWebPart1" TypeName="*" />
</SafeControls>
</Assembly>
If I remove any ASPTokenInput controls in the webpart the webpart loads correctly so I don't think there's a problem finding the control in the gac (I've used process monitor and it is looking in the correct place in the GAC to find the control). For some reason though it can't load the dll.
Any help would be much appreciated. Thanks!
My ascx.cs files is
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data;
using System.Data.SqlClient;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Web.Script.Serialization;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using ASPTokenInputLib;
namespace BidSearchWebPart.VisualWebPart1
{
[ToolboxItemAttribute(false)]
public partial class BidSearchWebPart : WebPart
{
private enum Columns
{
BidRef, BidName, Client, Area, TeamLead
}
private string TeamLeadsData, ExecLeadsData, StagesData, SectorsData, ServicesData, GradesData, CostCentresData, ClientsData, AreasData;
public BidSearchWebPart()
{
TeamLeadsData = RunSP("uspSelectTeamLeads", "TeamLead", "Name", ConnectionString());
ExecLeadsData = RunSP("uspSelectExecTechLeads", "ExecutiveTechnicalLead", "Name", ConnectionString());
StagesData = RunSP("uspSelectStages", "StageID", "StageDescSearch", ConnectionString());
SectorsData = RunSP("spSelectMarketSectors", "SectorID", "MktSector", CCDConnectionString());
ServicesData = RunSP("spSelectAllServices", "ServiceID", "Service", CCDConnectionString());
GradesData = RunSP("uspSelectGrades", "GradeID", "GradeDesc", ConnectionString());
CostCentresData = RunSP("uspSelectCostCentres", "CostCentre", "Name", ConnectionString());
ClientsData = RunSP("spSelectAllClients", "CompanyRef", "CoName", CCDConnectionString());
AreasData = RunSP("uspSelectAreas", "AreaID", "AreaName", ConnectionString());
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
InitializeControl();
}
protected void Page_Load(object sender, EventArgs e)
{
List<string> ddValues = new List<string>();
if (!Page.IsPostBack)
{
ddValues.Add("Greater than");
ddValues.Add("Less than");
ddCC.DataSource = ddValues;
ddFV.DataSource = ddValues;
ddCC.DataBind();
ddFV.DataBind();
}
btnSearch.Click += btnSearch_Click;
gvSearchResults.RowDataBound += gvSearchResults_RowDataBound;
tiTeamLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiTeamLead.DataSet = TeamLeadsData;
tiExecTechLead.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiExecTechLead.DataSet = ExecLeadsData;
tiStage.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiStage.DataSet = StagesData;
tiSector.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiSector.DataSet = SectorsData;
tiService.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiService.DataSet = ServicesData;
tiGrade.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiGrade.DataSet = GradesData;
tiCostCentre.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiCostCentre.DataSet = CostCentresData;
tiClient.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiClient.DataSet = ClientsData;
tiArea.DataSource = ASPTokenInput.DataSourceType.DataSet;
tiArea.DataSet = AreasData;
}
void btnSearch_Click(object sender, EventArgs e)
{
//if (string.IsNullOrEmpty(txtProjectNo.Text) && string.IsNullOrEmpty(txtProjectName.Text) && string.IsNullOrEmpty(txtClient.Text) && string.IsNullOrEmpty(txtKeyword.Text)) // Do nothing if search text boxes are blank
//{
// return;
//} else {
gvSearchResults.PageIndex = 0;
DoSearch();
//}
}
protected void gvSearchResults_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
gvSearchResults.PagerTemplate = null;
gvSearchResults.PageIndex = e.NewPageIndex;
DoSearch();
}
public void DoSearch()
{
DataTable dt = new DataTable();
string where = GetWhereClause();
if (!string.IsNullOrEmpty(where))
{
dt = FillTable("spSelectBidSearchResults", where);
}
gvSearchResults.DataSource = dt;
gvSearchResults.PageSize = 10;
gvSearchResults.PagerTemplate = null;
gvSearchResults.DataBind();
}
private DataTable FillTable(string storedProc, string where)
{
SqlConnection conn = new SqlConnection(ConnectionString());
conn.Open();
SqlCommand cmdProject = new SqlCommand(storedProc, conn);
cmdProject.CommandType = CommandType.StoredProcedure;
cmdProject.Parameters.AddWithValue("#whereclause", where);
SqlDataAdapter da = new SqlDataAdapter(cmdProject);
DataTable dt = new DataTable();
da.Fill(dt);
da.Dispose();
conn.Close();
return dt;
}
private string Symbol(string ddText)
{
if (ddText.Equals("Greater than"))
{
return ">";
}
else
{
return "<";
}
}
private string GetWhereClause()
{
string where = "";
where = GetWhereForCol(txtBidName.Text, "", "BidName", "like", where);
where = GetWhereForCol(txtDescription.Text, "", "Description", "like", where);
where = GetWhereForCol(GetTokens(tiTeamLead), "", "TeamLead", "token", where);
where = GetWhereForCol(GetTokens(tiExecTechLead), "", "ExecutiveTechnicalLead", "token", where);
where = GetWhereForCol(txtConstructionCost.Text, ddCC.Text, "ConstructionCost", "numeric", where);
where = GetWhereForCol(txtFeeValue.Text, ddFV.Text, "FeeValue", "numeric", where);
where = GetWhereForCol(GetTokens(tiStage), "", "Stage", "token", where);
where = GetWhereForCol(GetTokens(tiSector), "", "PrimarySector", "token", where, "SecondarySector");
where = GetWhereForCol(GetTokens(tiService), "", "PrimaryService", "token", where);
where = GetWhereForCol(GetTokens(tiGrade), "", "Grade", "token", where);
where = GetWhereForCol(GetTokens(tiCostCentre), "", "PrimaryCostCentre", "token", where);
where = GetWhereForCol(GetTokens(tiClient), "", "ClientRef", "token", where);
where = GetWhereForCol(GetTokens(tiArea), "", "Area", "token", where);
return where;
}
private string GetWhereForCol(string text, string ddText, string colName, string colType, string where, string otherCol = "")
{
if (!string.IsNullOrEmpty(text))
{
if (colType.Equals("like"))
{
where = AddToWhere(where, colName + " LIKE '%" + text + "%'");
}
else if (colType.Equals("numeric"))
{
string symbl = Symbol(ddText);
where = AddToWhere(where, colName + " " + symbl + " " + text);
}
else if (colType.Equals("token"))
{
if (!string.IsNullOrEmpty(otherCol))
{
where = AddToWhere(where, "(" + colName + " in (" + text + ")");
where += " OR " + otherCol + " in (" + text + "))";
}
else
{
where = AddToWhere(where, colName + " in (" + text + ")");
}
}
}
return where;
}
private string AddToWhere(string where, string clause)
{
if (!string.IsNullOrEmpty(clause))
{
if (string.IsNullOrEmpty(where))
{
where = clause;
}
else
{
where += " AND " + clause;
}
}
return where;
}
private string GetTokens(ASPTokenInput ti)
{
StringBuilder strTokens = new StringBuilder();
List<ASPTokenInput.Item> items = ti.SelectedItems;
foreach (ASPTokenInput.Item item in items)
{
if (strTokens.Length > 0)
{
strTokens.Append(", ");
}
strTokens.AppendFormat("'{0}'", item.id);
}
return strTokens.ToString();
}
public string GetSPSingleValue(string spName, string spParamName, string spParamVal, string connectionStr)
{
try
{
SqlConnection conn = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand(spName, conn);
cmd.Parameters.AddWithValue(spParamName, spParamVal);
cmd.CommandType = CommandType.StoredProcedure;
conn.Open();
string result = cmd.ExecuteScalar().ToString();
conn.Close();
return result;
}
catch
{
return "";
}
}
void gvSearchResults_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Label l;
DataRowView rowView = (DataRowView)e.Row.DataItem;
string bidRef = rowView["BidRef"].ToString();
string teamLeadID = rowView["TeamLead"].ToString();
string teamLeadName = GetSingleRecord("uspSelectTeamLeadByID", ConnectionString(), "#TeamLead", teamLeadID);
l = (Label)e.Row.Cells[(int)Columns.TeamLead].FindControl("lblTeamLead");
l.Text = teamLeadName;
if (siteCollectionExists(bidRef))
{
l = (Label)e.Row.Cells[(int)Columns.BidRef].FindControl("lblBidRef");
HyperLink hl = new HyperLink();
hl.NavigateUrl = "http://bidstore.gleeds.net/bids/" + bidRef;
hl.Text = bidRef;
e.Row.Cells[(int)Columns.BidRef].Controls.Add(hl);
l.Text = "";
}
}
}
//Check if site collection exists at given web application
private static bool siteCollectionExists(string bidNr)
{
bool returnVal = false;
var r = SPContext.Current.Site.WebApplication.Sites.Where(site => site.Url.Contains(bidNr));
foreach (SPSite s in r)
{
returnVal = true;
}
return returnVal;
}
public string TeamLeads()
{
return TeamLeadsData;
}
public string ExecutiveTechnicalLeads()
{
return ExecLeadsData;
}
public string Stages()
{
return StagesData;
}
public string Sectors()
{
return SectorsData;
}
public string Services()
{
return ServicesData;
}
public string Grades()
{
return GradesData;
}
public string CostCentres()
{
return CostCentresData;
}
public string Clients()
{
return ClientsData;
}
public string Areas()
{
return AreasData;
}
public string GetSingleRecord(string spName, string connectionStr, string param, string value)
{
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.AddWithValue(param, value);
command.Connection = conn;
conn.Open();
string result = command.ExecuteScalar().ToString();
conn.Close();
return result;
}
public string RunSP(string spName, string idCol, string nameCol, string connectionStr)
{
ArrayList data = new ArrayList();
SqlConnection conn = new SqlConnection();
SqlCommand command = new SqlCommand(spName, conn);
conn = new SqlConnection(connectionStr);
command.CommandType = CommandType.StoredProcedure;
command.Connection = conn;
conn.Open();
SqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
data.Add(new TokenInputRow(dr[idCol].ToString(), dr[nameCol].ToString()));
}
conn.Close();
return Serialize(data);
}
private static string Serialize(object obj)
{
JavaScriptSerializer ser = new JavaScriptSerializer();
return ser.Serialize(obj);
}
private string ConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=BidOpening;Persist Security Info=True;User ID=GTL_BidOpening_User;Password=G#rd3n12";
}
private string CCDConnectionString()
{
return "Data Source=10.2.40.17;Initial Catalog=CCDLive;Persist Security Info=True;User ID=GTL_CCDLive_User;Password=G#rd3n";
}
}
public class TokenInputRow
{
public string id;
public string name;
public TokenInputRow(string _id, string _name)
{
id = _id;
name = _name;
}
}
}
I am able to step through the page load, but I can't step into the ASPTokenInput dll. The code fails after the page load has finished.
The ti controls are included in my .ascx file as so %# Register TagPrefix="ati" Assembly="ASPTokenInputLib" Namespace="ASPTokenInputLib" %> ati:ASPTokenInput ID="tiTeamLead" runat="server" HintText="Start typing TeamLead..." />
Now it is another problem that occurred, it seems that the query I'm using only works for the first time but after pressing the next/previous buttons, it is giving me something else !!
Here is the query I used:
for (int i = 0; i <= months.length + 1; i++) {
try {
String a;
if (i < 9) {
a = y + "0" + (i + 1);
} else {
a = y + "" + (i + 1);
}
System.out.println("Année Courante " + a);
conn = DBConnection.connect();
String sql = "select sum(montant_operation) from operations where (select Extract(YEAR_MONTH from date_operation)) = '" + a + "' and typ_operation ='Versement';";
final ResultSet rs = conn.prepareStatement(sql).executeQuery();
if (rs.next()) {
System.out.println(series1.getData().toString());
series1.getData().add(new XYChart.Data<>(months[i], rs.getFloat("sum(montant_operation)")));
}
} catch (SQLException e) {
System.out.println(e);
}
}
But is there a query that works fine one time and then it gives error.
Have a nice day
In your BuildData (by the way, not following Java Naming Conventions, change its name) method you are updating the data of series. In the same method you are adding this series to the chart. By clicking the "next" button, BuildData method is invoked where this chart is added again which is unnecessary. Delete the
Platform.runLater(() -> {
barchart.getData().add(series1);
});
part from the method and add the chart only once in start:
...
...
vbox.getChildren().addAll(box, barchart);
barchart.getData().add(series1);
pane.getChildren().add(vbox);
...
...
The tested SSCCE:
import java.util.Calendar;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Orientation;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.chart.BarChart;
import javafx.scene.chart.CategoryAxis;
import javafx.scene.chart.NumberAxis;
import javafx.scene.chart.XYChart;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
public class BarChartDemo extends Application {
final String[] months = {"Janvier", "Février", "Mars", "Avril", "Mai", "Juin", "Juillet", "Août", "Septembre", "Octobre", "Novembre", "Décembre"};
//Connection conn;
final CategoryAxis month_axis = new CategoryAxis();
final NumberAxis data_axis = new NumberAxis();
final XYChart.Series<String, Number> series1 = new XYChart.Series();
private final BarChart<String, Number> barchart = new BarChart(month_axis, data_axis);
private Integer year = 0;
#Override
public void start(Stage primaryStage) {
year = Calendar.getInstance().get(Calendar.YEAR);
Button btn_next = new Button("NEXT");
Button btn_previous = new Button("PREVIOUS");
HBox box = new HBox(50);
box.getChildren().addAll(btn_previous, btn_next);
box.setAlignment(Pos.TOP_CENTER);
VBox vbox = new VBox(25);
box.setPadding(new Insets(10, 0, 10, 0));
FlowPane pane = new FlowPane(Orientation.VERTICAL);
vbox.getChildren().addAll(box, barchart);
barchart.getData().add(series1);
pane.getChildren().add(vbox);
Scene scene = new Scene(pane);
primaryStage.setTitle("Hello World!");
primaryStage.setScene(scene);
primaryStage.show();
BuildData(year);
btn_next.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
year += 1;
BuildData(year);
}
});
btn_previous.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent event) {
year -= 1;
BuildData(year);
}
});
}
public static void main(String[] args) {
launch(args);
}
private void BuildData(Integer y) {
series1.setName("Versement");
month_axis.setLabel("Mois de l'Année");
month_axis.setStyle("-fx-font-weight:BOLD;" + "-fx-font-size:15");
data_axis.setLabel("Valeur des Opérations Bancaires");
data_axis.setStyle("-fx-font-weight:BOLD;" + "-fx-font-size:15");
series1.getData().clear(); // clear old values
for (int i = 0; i < months.length; i++) {
series1.getData().add(new XYChart.Data(months[i], i * 10 * (y-2000)));
// try {
// String a;
// if (i < 9) {
// a = y + "0" + (i + 1);
// } else {
// a = y + "" + (i + 1);
// }
// conn = DBConnection.connect();
// String sql = "select sum(montant_operation) from operations where (select Extract(YEAR_MONTH from date_operation)) = '" + a + "' and typ_operation ='Versement';";
// final ResultSet rs = conn.prepareStatement(sql).executeQuery();
// if (rs.next()) {
// series1.getData().add(new XYChart.Data<>(months[i], rs.getFloat("sum(montant_operation)")));
// }
// } catch (SQLException e) {
// System.out.println(e);
// }
}
}
}