save button error in AS project - apache-flex

Whats wrong with the following code,There is an error at
saveButton.visible = false;
discardButton.visible = false;
package
{
import flash.display.Sprite;
import flash.media.Camera;
import flash.media.Video;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.utils.ByteArray;
import com.adobe.images.JPGEncoder;
public class caml extends Sprite
{
private var camera:Camera = Camera.getCamera();
private var video:Video = new Video();
private var bmd:BitmapData = new BitmapData(320,240);
private var bmp:Bitmap;
private var fileReference:FileReference = new FileReference();
private var byteArray:ByteArray;
private var jpg:JPGEncoder = new JPGEncoder();
public function caml()
{
saveButton.visible = false;
discardButton.visible = false;
saveButton.addEventListener(MouseEvent.MOUSE_UP, saveImage);
discardButton.addEventListener(MouseEvent.MOUSE_UP, discard);
capture.addEventListener(MouseEvent.MOUSE_UP, captureImage);
if (camera != null)
{
video.smoothing = true;
video.attachCamera(camera);
video.x = 140;
video.y = 40;
addChild(video);
}
else
{
trace("No Camera Detected");
}
}
private function captureImage(e:MouseEvent):void
{
bmd.draw(video);
bmp = new Bitmap(bmd);
bmp.x = 140;
bmp.y = 40;
addChild(bmp);
capture.visible = false;
saveButton.visible = true;
discardButton.visible = true;
}
private function saveImage(e:MouseEvent):void
{
byteArray = jpg.encode(bmd);
fileReference.save(byteArray, "Image.jpg");
removeChild(bmp);
saveButton.visible = false;
discardButton.visible = false;
capture.visible = true;
}
private function discard(e:MouseEvent):void
{
removeChild(bmp);
saveButton.visible = false;
discardButton.visible = false;
capture.visible = true;
}
}
}

I guess this is a document root class and the buttons is added to stage in the flash fla file. In that case you need to add the buttons to your declaration as public members:
public var saveButton : Button;
public var discardButton : Button;
UPDATE
I never use the flash components myself but you might find an answer here on how to use Flash components in Flashbuilder:
http://www.moock.org/blog/archives/000253.html
http://www.ruttencutter.com/?p=20

Related

Get current location (city name) without gps and mobile network

I have an android tablet that does not hasve a SIM card and GPS set to save battery mode too.
Tablet is connected to the internet by ethernet (with cable) and connected to LAN by WIFI.
I write a code for find current location (city name) and it work good in my phone. (GPS of my phone is active and connected to the internet by wifi (modem) or mobile network).
package com.xenon.location;
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import static android.content.Context.LOCATION_SERVICE;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
private final Activity mActivity;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location;
double latitude;
double longitude;
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10;
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1;
protected LocationManager locationManager;
public GPSTracker(Activity activity) {
this.mContext = activity.getBaseContext();
this.mActivity = activity;
getLocation();
}
public Location getLocation() {
try {
//locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
}else{
this.canGetLocation = true;
if (isNetworkEnabled) {
if (ContextCompat.checkSelfPermission(
mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity
, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}
, 0);
}
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS() {
if (locationManager != null) {
if (ContextCompat.checkSelfPermission(mActivity, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(mActivity, new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION},
0);
locationManager.removeUpdates(GPSTracker.this);
}
}
}
public double getLatitude() {
if (location != null) {
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude() {
if (location != null) {
longitude = location.getLongitude();
}
return longitude;
}
public String getCityName() {
String result = "";
if (location != null) {
double latitude, longitude;
List<Address> list;
Locale locale = new Locale("tr");
Geocoder geocoder = new Geocoder(mContext, locale);
try {
list = geocoder.getFromLocation(getLatitude(), getLongitude(), 2);
Address address = list.get(0);
/*
String gpsMsg = "CountryCode: " + address.getCountryCode() +
" ,AdminArea : " + address.getAdminArea() +
" ,CountryName : " + address.getCountryName() +
" ,SubLocality : " + address.getSubLocality();
*/
result = address.getAdminArea();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception e){
}
}
return result;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
public void showSettingsAlert() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
alertDialog.setTitle("GPS is settings");
alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alertDialog.show();
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
when run it on Tablet :
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
locationManager = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
isNetworkEnabled and canGetLocation always return false;
You can't get location because you disable the GPS.
but if you want to get your location without GPS, try to get the CELL INFORMATION(MNC MCC CELLID AND LAC) where your device Connected then try to USE API (unwiredlab.com) to convert that Cell INFO into location.

Row renderer with height depending on row index

I have an IDropInListItemRenderer that is being used inside a List. The height of the row depends on both the data and it's position in the List's view.
How do I remeasure as soon as the row index changes?
updateDisplayList doesn't get called every time, and also by that point it's too late because the List has already measured it.
edit
The effect I'm trying to achieve is similar to iOS where the header for a section sticks to the top
Here is the basic renderer that doesn't measure correctly:
import mx.controls.Label;
import mx.controls.listClasses.BaseListData;
import mx.controls.listClasses.IDropInListItemRenderer;
import mx.controls.listClasses.IListItemRenderer;
import mx.core.UIComponent;
import mx.events.FlexEvent;
public class MyRowRenderer extends UIComponent implements IListItemRenderer, IDropInListItemRenderer {
private static const HEADER_HEIGHT:int = 20;
private static const LABEL_HEIGHT:int = 20;
private var _data:Object;
private var _label:Label;
private var _header:Label;
private var _listData:BaseListData;
public function MyRowRenderer() {
super();
}
[Bindable("dataChange")]
public function get data():Object {
return _data;
}
public function set data(value:Object):void {
this._data = value;
invalidateProperties();
dispatchEvent(new FlexEvent(FlexEvent.DATA_CHANGE));
}
[Bindable("dataChange")]
public function get listData():BaseListData {
return _listData;
}
public function set listData(value:BaseListData):void {
_listData = value;
}
override protected function createChildren():void {
super.createChildren();
_header = new Label();
addChild(_header);
_label = new Label();
addChild(_label);
}
override protected function measure():void {
super.measure();
if (_label == null || _header == null) {
return;
}
var h:Number = LABEL_HEIGHT;
if (_listData.rowIndex == 0) {
h += HEADER_HEIGHT;
}
explicitHeight = measuredHeight = height = h;
}
override protected function commitProperties():void {
super.commitProperties();
_label.text = _data.label;
_header.text = _data.header;
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
_header.visible = _header.includeInLayout = (_listData.rowIndex == 0);
if (_header.visible) {
_header.move(0, 0);
_header.setActualSize(unscaledWidth, HEADER_HEIGHT);
_label.move(0, HEADER_HEIGHT);
_label.setActualSize(unscaledWidth, LABEL_HEIGHT);
} else {
_label.move(0, 0);
_label.setActualSize(unscaledWidth, LABEL_HEIGHT);
}
}
}
}
I ended up creating a subclass of List and overriding the shiftRow function to dispatch a custom RowIndexChangeEvent. In the row renderer's set listData it adds an event listener to the owner for the RowIndexChangeEvent and invalidates it's properties, size and displaylist.

JavaFX stopwatch timer

This is a class for a simple stopwatch for JavaFX, style the Label object as desired
package aaa;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.beans.property.SimpleStringProperty;
/**
*
* #author D07114915
*/
public class KTimer extends Thread {
private Thread thread = null;
private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss:S");
private String[] split;
private SimpleStringProperty min, sec, millis, sspTime;
private long time;
public static void main(String[] args) {
KTimer t = new KTimer();
t.startTimer(00);
}
public KTimer() {
min = new SimpleStringProperty("00");
sec = new SimpleStringProperty("00");
millis = new SimpleStringProperty("00");
sspTime = new SimpleStringProperty("00:00:00");
}
public void startTimer(long time) {
this.time = time;
thread = new Thread(this);
thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
public void stopTimer(long time) {
if (thread != null) {
thread.interrupt();
}
this.time = time;
setTime(time);
}
public void setTime(long time) {
this.time = time;
split = sdf.format(new Date(time)).split(":");
min.set(split[0]);
sec.set(split[1]);
if (split[2].length() == 1) {
split[2] = "0" + split[2];
}
millis.set(split[2].substring(0, 2));
sspTime.set(min.get() + ":" + sec.get() + ":" + millis.get());
}
public long getTime() {
return time;
}
public SimpleStringProperty getSspTime() {
return sspTime;
}
#Override
public void run() {
try {
while (!thread.isInterrupted()) {
setTime(time);
sleep(10);
time = time + 10;
}
} catch (Exception e) {
}
}
}//end of class
Now just get a listener on the property for your GUI
Add vars
KTimer ktimer;
Label timeLabel;
in your class initialize the vars
//Clock
ktimer = new KTimer();
timeLabel = new Label(ktimer.getSspTime().get());
ktimer.getSspTime().addListener(new InvalidationListener() {
#Override
public void invalidated(Observable observable) {
timeLabel.setText(ktimer.getSspTime().get());
}
});
then call the method to start and stop wherever you need to
Stop and reset is
ktimer.stopTimer(0);
Start and Pause timer is
ktimer.startTimer(ktimer.getTime());
Any improvements appreciated as the class is a bit CPU hungry..., but you can adjust the run thread and setTime(time) functions to suit the application
Here's a slightly different version (maybe better) and I'm not sure the synchronized methods are really necessary
package aaa;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import javafx.beans.property.SimpleStringProperty;
/**
*
* #author D07114915
*/
public class KTimer {
private SimpleDateFormat sdf = new SimpleDateFormat("mm:ss:S");
private String[] split;
private SimpleStringProperty sspTime;
private long time;
private Timer t = new Timer("Metronome", true);
private TimerTask tt;
boolean timing = false;
public KTimer() {
sspTime = new SimpleStringProperty("00:00:00");
}
public void startTimer(final long time) {
this.time = time;
timing = true;
tt = new TimerTask() {
#Override
public void run() {
if (!timing) {
try {
tt.cancel();
} catch (Exception e) {
e.printStackTrace();
}
} else {
updateTime();
}
}
};
t.scheduleAtFixedRate(tt, 10, 10);
}
public synchronized void stopTimer() {
timing = false;
}
public synchronized void updateTime() {
this.time = this.time + 10;
split = sdf.format(new Date(this.time)).split(":");
sspTime.set(split[0] + ":" + split[1] + ":" + (split[2].length() == 1 ? "0" + split[2] : split[2].substring(0, 2)));
}
public synchronized void moveToTime(long time) {
stopTimer();
this.time = time;
split = sdf.format(new Date(time)).split(":");
sspTime.set(split[0] + ":" + split[1] + ":" + (split[2].length() == 1 ? "0" + split[2] : split[2].substring(0, 2)));
}
public synchronized long getTime() {
return time;
}
public synchronized SimpleStringProperty getSspTime() {
return sspTime;
}
}
Building on KEV's answer and various demos I found across the internet, here's a simple "count up" timer with 100ms precision:
package fxtimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.event.ActionEvent;
import javafx.event.Event;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import javafx.util.Duration;
public class FXTimer extends Application {
private Timeline timeline;
private Label timerLabel = new Label(), splitTimerLabel = new Label();
private DoubleProperty timeSeconds = new SimpleDoubleProperty(),
splitTimeSeconds = new SimpleDoubleProperty();
private Duration time = Duration.ZERO, splitTime = Duration.ZERO;
#Override
public void start(Stage primaryStage) {
// Configure the Label
// Bind the timerLabel text property to the timeSeconds property
timerLabel.textProperty().bind(timeSeconds.asString());
timerLabel.setTextFill(Color.RED);
timerLabel.setStyle("-fx-font-size: 4em;");
splitTimerLabel.textProperty().bind(splitTimeSeconds.asString());
splitTimerLabel.setTextFill(Color.BLUE);
splitTimerLabel.setStyle("-fx-font-size: 4em;");
// Create and configure the Button
Button button = new Button();
button.setText("Start / Split");
button.setOnAction(new EventHandler() {
#Override
public void handle(Event event) {
if (timeline != null) {
splitTime = Duration.ZERO;
splitTimeSeconds.set(splitTime.toSeconds());
} else {
timeline = new Timeline(
new KeyFrame(Duration.millis(100),
new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent t) {
Duration duration = ((KeyFrame)t.getSource()).getTime();
time = time.add(duration);
splitTime = splitTime.add(duration);
timeSeconds.set(time.toSeconds());
splitTimeSeconds.set(splitTime.toSeconds());
}
})
);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();
}
}
});
// Setup the Stage and the Scene (the scene graph)
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 250);
// Create and configure VBox
// gap between components is 20
VBox vb = new VBox(20);
// center the components within VBox
vb.setAlignment(Pos.CENTER);
// Make it as wide as the application frame (scene)
vb.setPrefWidth(scene.getWidth());
// Move the VBox down a bit
vb.setLayoutY(30);
// Add the button and timerLabel to the VBox
vb.getChildren().addAll(button, timerLabel, splitTimerLabel);
// Add the VBox to the root component
root.getChildren().add(vb);
primaryStage.setTitle("FX Timer");
primaryStage.setScene(scene);
primaryStage.show();
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
launch(args);
}
}

Linking a webcam in a flex application

i am having a very strange problem while linking a webcam i xperience following error
ArgumentError: Error #2126: NetConnection object must be connected.
at flash.net::NetStream/ctor()
at flash.net::NetStream()
Following is my code in main.mxml
<fx:Script>
<![CDATA[
import flash.media.Camera;
import flash.media.Video;
import flash.net.NetConnection;
import mx.core.UIComponent;
import com.kahaf.plutay.* ;
private var inVideo:Video;
private var outVideo:Video;
private var inVideoWrapper:UIComponent;
private var camera:Camera;
private var mic:Microphone;
private var inStream:NetStream;
private var outStream:NetStream;
private function defaultVideoMode(): void
{
VideoPanel.width = 726;
VideoPanel.height = 494;
inVideo.width = 726;
inVideo.height = 494;
}
private function showInComingVideo():void
{
inVideo = new Video(VideoPanel.width,VideoPanel.height);
inVideo.attachNetStream(inStream);
inVideoWrapper = new UIComponent();
inVideoWrapper.addChild(inVideo);
VideoPanel.addElement(inVideoWrapper);
defaultVideoMode();
}
private function setupVideo(event:MouseEvent): void
{
camera = Camera.getCamera();
mic = Microphone.getMicrophone();
mic.setLoopBack(false);
mic.setUseEchoSuppression(true);
camera.setMode(640,480,20);
camera.setQuality(65536,90);
var conn:NetConnection = Connection.getConnection().conn;
inStream = new NetStream(conn);
inStream.play(conn);
showInComingVideo();
}
]]>
<s:Group x="283" y="330" width="234" height="149" id="VideoPanel" >
</s:Group>
<s:Button x="447" y="151" label="Click Me." click="setupVideo(event)"/>
here is the code of my connection class :
import flash.net.NetConnection;
public class Connection extends NetConnection
{
public static var conObj:Connection;
public var conn:NetConnection;
public var target:Object;
public var selector:Function;
public function Connection()
{
conn = new NetConnection;
target = null;
selector = null;
conn.client = this;
}
public static function getConnection():Connection
{
if(conObj == null)
{
conObj = new Connection();
}
return conObj;
}
}
This the correct order when handling NetConnection and NetStreams:
Create and establish the NetConnection (NetConnection.connect())
Wait for the NetConnection.Connect.Success event (NetStatusEvent.NET_STATUS)
Create your NetStream and attach the connected NetConnection to it
Publish/play your stream

TouchEvents for Flash Builder 4.5

I have successfully made my first application and imported it into my iPhone, but I can't seem to get TouchEvents to work. What am I doing wrong? Here is the code that I have currently:
package
{
import flash.display.Graphics;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.MouseEvent;
import flash.events.TouchEvent;
import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
public class TestIos extends Sprite
{
private var boll:Sprite = new Sprite;
private var radius:Number = 40;
public function TestIos()
{
super();
// support autoOrients
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
this.addChild(boll);
this.drawBoll();
// Add events
boll.addEventListener(TouchEvent.TOUCH_BEGIN,onTouchBegin);
boll.addEventListener(TouchEvent.TOUCH_TAP,onTouchTap);
}
private function onTouchBegin(e:TouchEvent):void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0xcc66cc,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1.25;
boll.addEventListener(TouchEvent.TOUCH_END,onTouchEnds);
boll.addEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
}
private function onTouchMove(e:TouchEvent):void {
boll.x = e.stageX;
boll.y = e.stageY;
}
private function onTouchTap(e:TouchEvent):void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0x33cc33,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1;
}
private function onTouchEnds(e:TouchEvent):void {
this.drawBoll();
boll.removeEventListener(TouchEvent.TOUCH_MOVE,onTouchMove);
boll.removeEventListener(TouchEvent.TOUCH_END,onTouchEnds);
}
private function drawBoll():void {
var g:Graphics = boll.graphics;
g.clear();
g.beginFill(0x3399cc,1);
g.drawCircle(150,radius,radius);
boll.scaleX = boll.scaleY = 1;
}
}
}
I would recommend you look at the API and examples. In this case, it seems you're missing the Multitouch.inputMode = MultitouchInputMode.TOUCH_POINT; declaration.

Resources