pass data from one from to another in codenameone - codenameone

In android we can use intent to pass data from one Acitivity to another .
Generally I use showForm("formname",null) method to shift form.
Is there any class for passing data from one form to another in codenameone ?
And how can I pass data to another form in codenameone?

Just store the data in the state machine class as variables. You can also add the data to the navigation stack using the methods getFormState/setFormState but that's not essential.

If you want to pass data to another form without the GUI Builder you can use getters and setters.
To pass data e.g username from Form A to Form B, create a private variable username in Form B and create getters and setters for the variable.
Then create an instance of Form B in Form A and call the setter method for variable username (setUsername method in Form B) and pass the data as a parameter, and lastly call the show() function on Form B
In Form B:
class FormB extends Form {
private String username;
public String getUsername() {
return this.username;
}
public void setUsername(String name) {
this.username = name;
}
}
In Form A:
class FormA extends Form {
public static void main(String[] args) {
String someName = "Aiotouch Softwares";
Form nextForm = new FormB();
nextForm.setUsername(someName);
nextForm.show();
}
}

Related

Use of Wrapper class for deserialization in callout?

I found the following use of a wrapper class, and was wondering if it is a good practice or whether its just duplication of code for no reason.
//Class:
public class SomeClass{
public Integer someInt;
public String someString;
}
//Callout Class:
public class CalloutClass{
public SomeClass someMethod(){
//...code to do a callout to an api
SomeClass someClassObj = (SomeClass)JSON.Deserialize(APIResponse.getBody(), SomeClass.class);
return someClassObj;
}
}
//Controller:
public class SomeController {
public SomeController(){
someClassObj = calloutClassObj.someMethod();
SomeWrapper wrapperObj = new SomeWrapper();
for(SomeClass iterObj : someClassObj){
wrapperObj.someWrapperInt = iterObj.someInt;
wrapperObj.someWrapperString = iterObj.someString;
}
}
public class someWrapper{
public Integer someWrapperInt{get;set;}
public String someWrapperString{get;set;}
}
}
The wrapper class "someWrapper" could be eliminated if we just use getters and setters ({get;set;}) in "SomeClass."
Could anyone explain if there could be a reason for following this procedure?
Thanks,
James
My assumption (because, code in controller is extra pseudo) is
SomeClass is a business entity, purpose of which is to store/work with business data. By work I mean using it's values to display it (using wrapper in controller), to calculate smth in other entities or build reports... Such kind of object should be as lightweight as possible. You usually iterate through them. You don't need any methods in such kind of objects. Exception is constructor with parameter(s). You might want to have SomeObject__c as parameter or someWrapper.
someWrapper is a entity to display business entity. As for wrapper classes in controllers. Imagine, that when you display entity on edit page and enter a value for someWrapperInt property, you want to update someWrapperString property (or you can just put validation there, for example, checking if it is really Integer). Usually, as for business entity, you don't want such kind of functionality. But when user create or edit it, you may want smth like this.

What is the design pattern name that used to create an object by passing an engine object

I have a class called DatabaseModel.
And an interface called DatabaseEngineInterface that have a methods such as:
insert
update
delete
select
So I can on running time determine which engine to use mysql or oracle which are a classes that implements the DatabaseEngineInterface
EngineDatabase engine = new MySQLEngine();
DatabaseModel db = new DatabaseModel(engine);
What is this design pattern called?
Specifically, this is the Constructor Injection pattern (described in my book), which is a special case of the Strategy pattern.
Isn't it an implementation of the strategy pattern? Wikipedia states that the strategy pattern is:
>a software design pattern that enables an algorithm's behavior to be selected at runtime
It also says that the strategy pattern:
defines a family of algorithms,
encapsulates each algorithm, and
makes the algorithms interchangeable within that family.
You are allowing the database which will be used (and so the behaviour) to be selected at run time. You have defined a family of algorithms (your interface), encapsulated each algorithm (by creating a class per provider) and they can be used interchangeably as the DatabaseModel depends only on the interface.
DaoFactory design pattern fits well for your implementation.
Interface
public interface DatabaseEngineInterface {
public void insert(User user);
public void update(User user);
public void delete(int userId);
}
Class which implements the above methods:
public class DatabaseModel implements DatabaseEngineInterface {
#Override
public void delete(int userId) {
// delete user from user table
}
#Override
public User[] findAll() {
// get a list of all users from user table
return null;
}
#Override
public User findByKey(int userId) {
// get a user information if we supply unique userid
return null;
}
#Override
public void insert(User user) {
// insert user into user table
}
#Override
public void update(User user) {
// update user information in user table
}
}
Factory
public class DatabaseModelDAOFactory {
public static UserDAO getUserDAO(String type) {
if (type.equalsIgnoreCase("mysql")) {
return new UserDAOMySQLImpl();
} else {
return new UserDAOORACLEImpl();
}
}
}
Client side code:
Then, in the client side instead of a hardcoded line like:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDAODatabaseEngineInterface("jdbc");
You could have a properties file to be able to switch between DAOs dynamically, having retrieved that string from the properties file you can simply do:
DatabaseModel userDAO=DatabaseModelDAOFactory.getUserDaoDatabaseEngineInterface(myStringFromPropertiesFile);
myStringFromPropertiesFile would contain "mysql" or "oracle" according to the definition in your properties file.

Registration form with new fields related

i am trying to add fields to my registration form with FosUserBundle.
Adding normal fields to the Userclass like "name", "age" e.g is easy to do:
class RegistrationFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder
->add('name')
;
}
public function getParent()
{
return 'fos_user_registration';
}
public function getName()
{
return 'acme_user_registration';
}
}
This is all working and the new fields are written to my database table.
But how do i add there a new FormType into the Registration type of the Fos Bundle, like:
A user can have an Address, which is related OneToMany.
I tried it with the following, by first creating the address class and giving him one user:
/**
* #ORM\ManyToOne(targetEntity="User", inversedBy="addresses")
* #ORM\JoinColumn(name="user_id", referencedColumnName="id")
*/
protected $user;
And then by adding addresses to the User class:
/**
* #ORM\OneToMany(targetEntity="Address", mappedBy="user")
*/
protected $addresses;
public function __construct()
{
parent::__construct();
// your own logic
$this->addresses= new ArrayCollection();
}
Adding the AddressType:
class AddressType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('state', 'text')
->add('city','text')
->add('zipcode', 'text')
->add('street', 'text');
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme\UserBundle\Entity\Address',
));
}
public function getName()
{
return 'address';
}
}
to the RegistrationFormType works and the fields are displayed in the browser:
public function buildForm(FormBuilderInterface $builder, array $options)
{
// add your custom field
$builder
->add('name')
->add('addresses', new AddressType())
;
}
But when i try to submit the form with new data, i don't know how to say symfony that the address entered should be related to the User.
Im always getting the error:
"The form's view data is expected to be an instance of class Acme\UserBundle\Entity\Address, but is an instance of class Doctrine\Common\Collections\ArrayCollection. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms an instance of class Doctrine\Common\Collections\ArrayCollection to an instance of Acme\UserBundle\Entity\Address."
What am I doing wrong here?
Regards.
you're trying to add a collection as a single field, when you give a "data_class" you're saying "here this is the form for this entity", but as the error says the system has to manage a collection of forms each one related to a single entity, you need to data transform them to something he can manage in a simple (or prebuilt) way (look for DataTransformers)
or you can use the colletion field type and pass them the address form type
-- edited after the comment --
no, sorry i've missed that, you need an entity form type because you state that a user has one address (and many user can be mapped to the same address, i.e. a family), so there's no need of a collection, though you're in the owning side persisting the user you don't have to worry, if you say cascade persist in your mapping schema for the ManyToOne relation, Doctrine will store the address for you (or use an existing one in case of a matching one)
btw i was fuzzed by your sentence "A user can have an Address, which is related OneToMany." that's misleading, a user can have an address, which is related to a ManyToOne relation (many user can have an address), the address is in a oneToMany relation with users (an address is own by many users)

Passing variables from main form to input form

I have a simple question. I have a main form, and then a startup form from where I can select a new 3D model to generate. When selecting a new 3D model from the startup form, I want to check first whether the previous model I worked on has been saved or not. I simply want to pass a boolean value from the main form to the startup form using a delegate, but I can't seem to access the main form or any of its variables. I thought it would be as simple as saying: <code>frmMain myForm = new frmMain();</code>, but typing frmMain doesn't show up anything in intellisense.
Any hints?
Add a public property on your main form
public bool IsDirty
{
get;set;
}
you can then access this.ParentForm.IsDirty in your startup form,
remember to pass a reference to the main form when you show the startup form ... startupForm.showDialog(this);
Your main form is not accessible to Startup form.You have to store it to something that is accessible at a point where you want to use it.
You can do it by following way also ( along with other ways :)
// This class is mainly used to transfer values in between different components of the system
public class CCurrent
{
public static Boolean Saved = false;
}
make sure you put this class in namespace which is accessible to both the forms.
Now In your frmMain form set the value of CCurrent.Saved and access it in your startup form.
Here's my suggestion:
place a 3DModel object property in your main form:
private Model _model;
Declare your startup form as a Dialog ( like OpenFileDialog) and do something like this:
public void OpenModel()
{
using(var frm=new StartUpForm())
{
if(frm.ShowDialog()==DialogResult.OK))
{
if(_model.IsDirty)
{
if(MessageBox.Show("Model is changed do you want to save it?","",MessageBoxButtons.YesNo)==DialogResult.Yes)
_model.Save();
_model=frm.SelectedModel;
}
}
}
}
your startup form should have a interface like this:
public interface IStartupForm:IDisposable
{
DialogResult ShowDialog(IWin32Window parent);
Model SelectedModel{get;}
}

Winforms: access class properties throughout application

I know this must be an age-old, tired question, but I cant seem to find anything thru my trusty friend (aka Google).
I have a .net 3.5 c# winforms app, that presents a user with a login form on application startup. After a successful login, I want to run off to the DB, pull in some user-specific data and hold them (in properties) in a class called AppCurrentUser.cs, that can thereafer be accessed across all classes in the assembly - the purpose here being that I can fill some properties with a once-off data read, instead of making a call to the DB everytime I need to. In a web app, I would usually use Session variables, and I know that the concept of that does not exist in WinForms.
The class structure resembles the following:
public class AppCurrentUser {
public AppCurrentUser() { }
public Guid UserName { get; set; }
public List<string> Roles { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
}
Now, I have some options that I need some expert advice on:
Being a "dumb" class, I should make the properties non-static, instantiate the class and then set the properties...but then I will only be able to access that instance from within the class that it was created in, right?
Logically, I believe that these properties should be static as I will only be using the class once throughout the application (and not creating new instances of it), and it's property values will be "reset" on application close. (If I create an instance of it, I can dispose of it on application close)
How should I structure my class and how do I access its properties across all classes in my assembly? I really would appreciate your honest and valued advice on this!!
Thanks!
Use the singleton pattern here:
public class AppUser
{
private static _current = null;
public static AppUser Current
{
get { return = _current; }
}
public static void Init()
{
if (_current == null)
{
_current = new AppUser();
// Load everything from the DB.
// Name = Dd.GetName();
}
}
public string Name { get; private set; }
}
// App startup.
AppUser.Init();
// Now any form / class / whatever can simply do:
var name = AppUser.Current.Name;
Now the "static" things are thread-unsafe. I'll leave it as an exercise of the reader to figure out how to properly use the lock() syntax to make it thread-safe. You should also handle the case if the Current property is accessed before the call to Init.
It depends on how you setup your architecture. If you're doing all your business logic code inside the actual form (e.g. coupling it to the UI), then you probably want to pass user information in as a parameter when you make a form, then keep a reference to it from within that form. In other words, you'd be implementing a Singleton pattern.
You could also use Dependency Injection, so that every time you request the user object, the dependency injection framework (like StructureMap) will provide you with the right object. -- you could probably use it like a session variable since you'll be working in a stateful environment.
The correct place to store this type of information is in a custom implementation of IIdentity. Any information that you need to identify a user or his access rights can be stored in that object, which is then associated with the current thread and can be queried from the current thread whenever needed.
This principal is illustrated in Rocky Lhotka's CLSA books, or google winforms custom identity.
I'm not convinced this is the right way but you could do something like this (seems to be what you're asking for anyway):
public class Sessions
{
// Variables
private static string _Username;
// properties
public static string Username
{
get
{
return _Username;
}
set
{
_Username = value;
}
}
}
in case the c# is wrong...i'm a vb.net developer...
then you'd just use Sessions.USername etc etc

Resources