how to update jfree line chart in RCP View - eclipse-rcp

I have four views in Eclipse RCP App. In that 3 View are responsible to show the multiline graphs. i am using a switch case for drawing the graph continuously until other views are get focused. But the view are not showing the updated chart.
The following is the case for update the graph. i have two datasets for sample updation of the view.
All the replies are appreciated.
case 1:
System.out.println("in Case "+selectedViewId);
while(selectedViewId==1){
try {
Display.getDefault().syncExec(new Runnable() {
public void run() {
while(count<20) {
count++;
System.err.println("Countttttttt "+count);
if(count%2==0){
System.err.println(".....Oneeeeeeee");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e1) {
e1.printStackTrace();
}
int value = CPU.value=1;
CPU cpuView = CPUSingleton.getCPUObject();
}
else {
System.err.println(".....tWOOOOOOOOOOOOOO");
IViewPart vp = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().findView("RCP.CPU");
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().hideView(vp);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().resetPerspective();
try {
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("RCP.CPU");
} catch (PartInitException e) {
e.printStackTrace();
}
int value = CPU.value=2;
CPU cpuView = CPUSingleton.getCPUObject();
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
break;

Related

Caused by: org.eclipse.swt.SWTException: Invalid thread access

I get "Invalid thread access" in below code. I am not sure where I have written wrong code. My main intention to write the code is to just display subtask (what is happening behind the scene) so I have added subtask before method called.
#Override
public void handleEvent(Event event)
{
if((event.keyCode == SWT.CR || event.keyCode == 13 || event.type == SWT.Selection) && btnAdd.isEnabled())
{
final PreferencesMO permo = new PreferencesMO();
permo.updatePreferences();
permo.updateDocumentNumber();
final ProjectMO pmo = new ProjectMO();
final CoverSheetMO csmo = new CoverSheetMO();
final CommonError cmerror = new CommonError();
final ParameterConfigurationMO pamo = new ParameterConfigurationMO();
final SnippetNew s = new SnippetNew();
final String projName = txtpname.getText();
Display.getDefault().asyncExec(new Runnable()
{
public void run()
{
try
{
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
{
s.method1(i);
}
//monitor.worked(1);
try { Thread.sleep(2000); } catch (Exception e) { }
monitor.subTask("Analysing Data...");
try { Thread.sleep(2000); } catch (Exception e) { }
if(!projName.equals(""))
{
monitor.subTask("Updating coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
cmerror.updateCoverSheetStatusforNewProject();
monitor.subTask("Inserting Project ...");
try { Thread.sleep(2000); } catch (Exception e) { }
pmo.addProjectManager(projName,"T");
monitor.subTask("Searching Project ID ...");
try { Thread.sleep(2000); } catch (Exception e) { }
String p_id = pmo.searchprojectID(projName);
permo.insertDocumentNumber(p_id);
monitor.subTask("Inserting data into coversheet ...");
try { Thread.sleep(2000); } catch (Exception e) { }
csmo.insertCoversheet(p_id);
pamo.insertParameterConfiguration(p_id);
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell().setText("Demo Tool - "+projName);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
AuditLogs view = (AuditLogs) page.findView(AuditLogs.ID);
IEditorPart editorPart = page.getActiveEditor();
StackedLambdaChartInput input = new StackedLambdaChartInput();
AnalysisResult_MetricsChartInput metricsinput = new AnalysisResult_MetricsChartInput();
StackedLambdaChart_HorizantalInput stackedhorizantalinput = new StackedLambdaChart_HorizantalInput();
AnalysisResult_Metrics_HorizantalChartInput metricshorizantalinput = new AnalysisResult_Metrics_HorizantalChartInput();
BarChartInput inpuit = new BarChartInput();
BarChart_HorizantalInput barchart_horizantalinput = new BarChart_HorizantalInput();
AuditLogMO auditlog = new AuditLogMO();
monitor.subTask("Fetching audit logs to display ...");
try { Thread.sleep(2000); } catch (Exception e) { }
java.util.List<java.util.List<String>> auditlogs = auditlog.searchAuditLog(null,null);
view.table(auditlogs);
try
{
handlerService.executeCommand(AuditLogView.ID, new Event());
handlerService.executeCommand(ErrorLogView.ID, new Event());
handlerService.executeCommand(DesignHierarchyHandler.ID, new Event());
if(myeditor != null)
{
if(myeditor instanceof CoverSheet)
{
handlerService.executeCommand(CoverSheetHandler.ID, new Event());
}
else if(myeditor instanceof ParameterConfigurations)
{
handlerService.executeCommand(ParameterConfigurationHandler.ID, new Event());
}
}
}
catch (ExecutionException | NotDefinedException | NotEnabledException | PartInitException| NotHandledException e1)
{
e1.printStackTrace();
}
Constant con = new Constant();
con.createNewProject();
}
//shell.close();
monitor.done();
}
});
}
catch (InvocationTargetException | InterruptedException e)
{
e.printStackTrace();
}
}
});
}
}
Put your progress monitor as below :
Display.getDefault().asyncExec( new Runnable()
{
IWorkbenchWindow win = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
new ProgressMonitorDialog(shell).run(true, true, new IRunnableWithProgress() {
#Override
public void run(final IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException
{
monitor.beginTask("Import Data", IProgressMonitor.UNKNOWN);
monitor.subTask("Connecting to databse...");
for(int i=0;i<=100;i++)
}
If you want the workbench page, that also has to be called inside a UI thread like above.
You can't access UI code in the background thread used for the IRunnableWithProgress code.
So you must get the values of controls in the UI thread before you run the progress dialog.
You also can't access things like IWorkbenchPage in the background thread. If you want to update UI objects from a non-UI thread, you need to use Display.asyncExec or Display.syncExec to run the updating code in the UI thread.

Launching Dialog Box with Data from TableView Row

I'm attempting to launch an Edit Customer Window with text fields filled with reference from the rows of a table. The Table and Dialog both have different controller classes.
Here's the code snippet from the table in question that gives us the required customerID when a user double clicks on a row.
Table Controller: CustomersController:
#Override
public void initialize(URL location, ResourceBundle resources) {
populateCustomerTable();
tableListeners(null);
}
void tableListeners(CustomerData customerData){
tblcustomer.setRowFactory(tr -> {
TableRow<CustomerData> row = new TableRow<>();
row.setOnMouseClicked(event -> {
if (event.getClickCount() == 2 && (!row.isEmpty())) {
int selectedCustomerID = row.getItem().getCustomerID();
System.out.println("A certain row: " + selectedCustomerID + " has been clicked!");
Stage stage = new Stage();
FXMLLoader loader = new FXMLLoader();
try {
Parent root = loader.load(getClass().getResource("../view/popups/edit_customer.fxml"));
stage.setScene(new Scene(root));
stage.setTitle("Editing Existing Customer's Details");
stage.initModality(Modality.APPLICATION_MODAL);
stage.initOwner(btnEditCustomer.getScene().getWindow());
stage.showAndWait();
} catch (IOException e) {
e.printStackTrace();
}
}
});
return row;
});
}
I want selectedCustomerID from the above piece of code to be parsed into the EditCustomerController class hence when the dialog launches, it's text fields should be prepoulated with values suppled from the select query that queries the database with the where condition being tht selectedCustomerID from the CustomersController class.
Code snippet from EditCustomerController class:
#Override
public void initialize(URL location, ResourceBundle resources) {
//populateEditCustomerFields(1);
}
void populateEditCustomerFields(int customerID){
this.customer_ID=customerID;
System.out.println(customer_ID);
try {
con = DatabaseConnection.getConnected();
stmt = con.createStatement();
rs = con.createStatement().executeQuery("SELECT * FROM `h_customers` WHERE `customerID`=" + customer_ID);
while (rs.next()) {
title.setText(rs.getString("title"));
firstName.setText(rs.getString("firstName"));
lastName.setText(rs.getString("lastName"));
nationalID.setText(String.valueOf(rs.getInt("nationalID")));
//dob.setText(rs.getString("DOB"));
mobilePhone.setText(rs.getString("mobilePhone"));
workPhone.setText(rs.getString("workPhone"));
email.setText(rs.getString("email"));
}
} catch (SQLException ex) {
Logger.getLogger(NewRoomController.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
The Idea here is to parse selectedCustomerID from CustomersController into the initialize method of EditCustomerController so the Dialog can launch with the customer details that require editing. I've searched for solutions all over the web and here on StackOverflow, some come close to answering me, some are too complex for my newbie mind, but none has helped. Any solution would be highly appreciated. I will provide any further clarification required.
You can get the controller class and invoke its necessary methods. See this answer for getting controller, then do
editCustomerController.populateEditCustomerFields(selectedCustomerID);
on table row double click.
Further to improve performance, you can load the edit_customer.fxml only once and when the user double clicks, refresh its rendered data with editCustomerController.populateEditCustomerFields(selectedCustomerID).

Camera Zoom in/out null pointer exception

My code works fine when i add the zoom code it gives null pointer exception.
I have written the below code inside the preview class. I am new in android please help thanks in advance.
my code is
int currentZoomLevel = 0, maxZoomLevel = 0;
public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
int width, int height) {
// start preview with new settings
try {
parameters = mCamera.getParameters();
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
Display display = ((WindowManager) context
.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
if (display.getRotation() == Surface.ROTATION_0) {
try {
parameters.setPreviewSize(height, width);
mCamera.setDisplayOrientation(90);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_90) {
try {
parameters.setPreviewSize(width, height);
} catch (Exception e) {
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_180) {
try {
parameters.setPreviewSize(height, width);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (display.getRotation() == Surface.ROTATION_270) {
try {
parameters.setPreviewSize(width, height);
mCamera.setDisplayOrientation(180);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is whera i start zooming. i have add zoom control in side my layout
ZoomControls zoomControls = (ZoomControls) findViewById(R.id.zoom);
if (parameters.isZoomSupported()) {
final int maxZoomLevel = parameters.getMaxZoom();
Log.i("max ZOOM ", "is " + maxZoomLevel);
zoomControls.setIsZoomInEnabled(true);
zoomControls.setIsZoomOutEnabled(true);
zoomControls.setOnZoomInClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel < maxZoomLevel) {
currentZoomLevel++;
mCamera.startSmoothZoom(currentZoomLevel);
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
zoomControls.setOnZoomOutClickListener(new OnClickListener() {
public void onClick(View v) {
if (currentZoomLevel > 0) {
currentZoomLevel--;
parameters.setZoom(currentZoomLevel);
mCamera.setParameters(parameters);
}
}
});
} else
zoomControls.setVisibility(View.GONE);
try {
mCamera.setPreviewDisplay(surfaceHolder);
mCamera.startPreview();
} catch (Exception e) {
// intentionally left blank for a test
}
}

SWT/JFACE progress bar in splash screen stop update while running external process in application

I Have problem with application that invoke splash screen with progrss bar during initialization, this is part of code inside my app,
try {
Runtime runTime = Runtime.getRuntime();
pbaw = runTime.exec(cmdGen);
//pbaw = probuilder.start();
try {
String line;
BufferedReader input =
new BufferedReader(new InputStreamReader(pbaw.getInputStream()));
SplashScreen ss= new SplashScreen(Display.getCurrent(), getShell());
int progress = 0;
ss.show();
while ((line = input.readLine()) != null) {
ss.setLabel(line);
progress+=1;
ss.advance(progress);
//System.out.println(line); //<-- Parse data here.
}
input.close();
ss.destroy(pbaw.waitFor());
} catch (InterruptedException e) {
e.printStackTrace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
my question is why the progrss bar in splash screen can not update while i click in desktop or running other application, but my applicatin can run perfectly, please help ???
here part of my splash scrren code to make it clear,
void advance(final int progress) {
if (!progressBar.isDisposed()) {
progressBar.setSelection(progress);//progressBar.getSelection() + progress);
progressBar.redraw();
}
}
public void show() {
mainShell.pack();
mainShell.open();
}
void destroy(int val) {
if (val==0){
splashComposite.dispose();
if (appImage != null) {
appImage.dispose();
}
mainShell.dispose();
}
}
You are running your code in the User Interface thread and never giving SWT a chance to update. You need to run your reading code in a separate thread and use Display.asyncExec to update the splash screen in the UI thread.

How to show Custom Message in Place of Null Date of Birth

I am writing an app in which i am fetching List of Facebook friends with their profile picture, name and dob
but some of my friends have not given their Birthday Dates, so in place of Birthday i am getting null by default, but now in place of null i want to show: Birthday Not Mentioned.
see below screen shot of my existing app:
Like: Vikas Rana has given DOB on facebook and AJay November has not given DOB on Facebook
> VikY
January 1
> AJamber
Null
Here, in place Null i want to show : Birthday Not Mentioned
FriendsList.java:
public View getView(int position, View convertView, ViewGroup parent) {
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e) {
}
FriendItem friendItem;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.listfb_friends, null);
friendItem = new FriendItem();
convertView.setTag(friendItem);
} else {
friendItem = (FriendItem) convertView.getTag();
}
friendItem.friendPicture = (ImageView) convertView
.findViewById(R.id.picture);
friendItem.friendName = (TextView) convertView
.findViewById(R.id.name);
friendItem.friendDob = (TextView) convertView
.findViewById(R.id.dob);
friendItem.friendLayout = (RelativeLayout) convertView
.findViewById(R.id.friend_item);
try {
String uid = jsonObject.getString("uid");
String url = jsonObject.getString("pic_square");
friendItem.friendPicture.setImageBitmap(picturesGatherer
.getPicture(uid, url));
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
try {
friendItem.friendName.setText(jsonObject.getString("name"));
if(!friendItem.friendDob.equals(""))
{
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
else
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}
and if i am writing code something like this:
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
} catch (JSONException e) {
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
finally
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
so i am getting Birthday Not Mentioned for all facebook friends Birthdays, even for them also those have mentioned.
try this one.
try{
if(jsonObject.getString("birthday")!= null && !jsonObject.getString("birthday").equals("")){
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}else{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
}catch(JSONException e){
e.printStackTrace();
}
Where you are getting NullPointerException use try-catch over it.
You might have done it I think. Now just set the text "Birthday Not Mentioned" over the textview/edittext (whatever you are using to show d.o.b) by writing code in catch block.
Just use:-
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
catch (Exception e) {
friendItem.friendName.setText("Name"); // try it for now.
friendItem.friendDob.setText("Birthday Not Mentioned"); // Have to be here.
}
Just try with this code:
try
{
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
if(!(jsonObject.getString("birthday").equalsIgnoreCase("null")))
{
friendItem.friendDob.setText(jsonObject.getString("birthday"));
}
else
{
friendItem.friendDob.setText("Birthday Not Mentioned");
}
} catch (JSONException e)
{
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}