Not able to insert in second table (Transaction) in android sqlite - sqliteopenhelper

I have two tables, category and transaction. I have single SQLiteOpenHelper class and two classes to insert and retrieve category and transaction. But I am not able to insert in transaction table. Getting negative number while inserting.
DatabaseHelper Class
package com.mm.bipin.mm;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME="mm";
private static final int DATABASE_VERSION=1;
public static final String CATEGORY_TABLE_NAME="category";
public static final String CATEGORY_CID="_id";
public static final String CATEGORY_TITLE= "title";
public static final String CATEGORY_DATE="date";
public static final String CATEGORY_TYPE="type";
public static final String CATEGORY_NOTE="note";
private static final String CATEGORY_CREATE_TABLE= "CREATE TABLE "+CATEGORY_TABLE_NAME+" ( "+CATEGORY_CID+" INTEGER PRIMARY KEY AUTOINCREMENT, "+
" "+CATEGORY_TITLE+" VARCHAR(255), "+CATEGORY_DATE+" VARCHAR(255),"+CATEGORY_TYPE+" INTEGER,"+CATEGORY_NOTE+" VARCHAR(255) )";
private static final String CATEGORY_DROP_TABLE=
" DROP TABLE IF EXISTS " +CATEGORY_TABLE_NAME;
public static final String TRANSACTION_TABLE_NAME="transaction";
public static final String TRANSACTION_TID="_id";
public static final String TRANSACTION_CATEGORY_ID="category_id";
public static final String TRANSACTION_TITLE="title";
public static final String TRANSACTION_AMOUNT="amount";
public static final String TRANSACTION_DATE="date";
public static final String TRANSACTION_NOTE="note";
private static final String TRANSACTION_CREATE_TABLE= "CREATE TABLE "+TRANSACTION_TABLE_NAME+" " +
" ("+TRANSACTION_TID+" INTEGER PRIMARY KEY AUTOINCREMENT, " +
" "+TRANSACTION_CATEGORY_ID+" INTEGER , " +
" "+TRANSACTION_TITLE+" VARCHAR(255) , " +
" "+TRANSACTION_AMOUNT+" VARCHAR(255) , " +
" "+TRANSACTION_DATE+" VARCHAR(255) , " +
" "+TRANSACTION_NOTE+" VARCHAR(255) ) ";
private static final String TRANSACTION_DROP_TABLE=
" DROP TABLE IF EXISTS " +TRANSACTION_TABLE_NAME;
private Context context;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME,null,DATABASE_VERSION);
this.context=context;
}
#Override
public void onCreate(SQLiteDatabase db) {
try {
//getWritableDatabase();
db.execSQL(CATEGORY_CREATE_TABLE);
db.execSQL(TRANSACTION_CREATE_TABLE);
Message.message(context, "DB created");
}
catch(android.database.SQLException e){
Message.message(context," "+e);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
try{
db.execSQL(CATEGORY_DROP_TABLE);
db.execSQL(TRANSACTION_DROP_TABLE);
Message.message(context,"DB dropped");
}
catch(android.database.SQLException e){
Message.message(context," "+e);
}
}
}
CategoryDatabaseAdapter class
package com.mm.bipin.mm.category;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.mm.bipin.mm.Category;
import com.mm.bipin.mm.DatabaseHelper;
import com.mm.bipin.mm.Message;
import java.util.ArrayList;
public class CategoryDatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
public static String[] columns={DatabaseHelper.CATEGORY_TITLE,DatabaseHelper.CATEGORY_DATE,DatabaseHelper.CATEGORY_NOTE};
public CategoryDatabaseAdapter(Context context){
helper=new DatabaseHelper(context);
}
Context context;
public long insertCategory(String title,int year,int month,int day,int type,String note){
db=helper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(DatabaseHelper.CATEGORY_TITLE,title);
String date= convertDateToString(year, month, day);
contentValues.put(DatabaseHelper.CATEGORY_DATE,date);
contentValues.put(DatabaseHelper.CATEGORY_TYPE,type);
contentValues.put(DatabaseHelper.CATEGORY_NOTE,note);
long id=db.insert(DatabaseHelper.CATEGORY_TABLE_NAME,null,contentValues);
return id;
}
public Cursor getAllRows(){
db=helper.getWritableDatabase();
String[] columns={DatabaseHelper.CATEGORY_CID,DatabaseHelper.CATEGORY_TITLE,DatabaseHelper.CATEGORY_DATE,
DatabaseHelper.CATEGORY_TYPE,DatabaseHelper.CATEGORY_NOTE};
Cursor mCursor=db.query(DatabaseHelper.CATEGORY_TABLE_NAME,columns,null,null,null,null,null);
if(mCursor!=null){
mCursor.moveToNext();
}
return mCursor;
}
public String convertDateToString(int year,int month,int day){
StringBuilder str=new StringBuilder();
str.append(year);
str.append("-");
str.append(month);
str.append("-");
str.append(day);
return str.toString();
}
}
TransactionDatabaseAdapter class
package com.mm.bipin.mm.transaction;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.widget.Toast;
import com.mm.bipin.mm.DatabaseHelper;
import com.mm.bipin.mm.Message;
import com.mm.bipin.mm.category.CategoryDatabaseAdapter;
public class TransactionDatabaseAdapter {
DatabaseHelper helper;
SQLiteDatabase db;
public static String[] columns= {DatabaseHelper.TRANSACTION_TITLE,DatabaseHelper.TRANSACTION_DATE,
DatabaseHelper.TRANSACTION_NOTE};
TransactionDatabaseAdapter(Context context){
helper=new DatabaseHelper(context);
}
public long insertTransaction(String title,int category_id ,String amount,int year,int month,int day,String note){
//SQLiteDatabase db=helper.getWritableDatabase();
db=helper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put(DatabaseHelper.TRANSACTION_CATEGORY_ID,category_id);
contentValues.put(DatabaseHelper.TRANSACTION_TITLE,title);
contentValues.put(DatabaseHelper.TRANSACTION_AMOUNT,amount);
String date= convertDateToString(year, month, day);
contentValues.put(DatabaseHelper.TRANSACTION_DATE,date);
contentValues.put(DatabaseHelper.TRANSACTION_NOTE,note);
long id=db.insert(DatabaseHelper.TRANSACTION_TABLE_NAME,null,contentValues);
return id;
}
public String convertDateToString(int year,int month,int day){
StringBuilder str=new StringBuilder();
str.append(year);
str.append("-");
str.append(month);
str.append("-");
str.append(day);
return str.toString();
}
public Cursor getAllTransaction(){
db=helper.getWritableDatabase();
String[] transactionColumns={DatabaseHelper.TRANSACTION_TID,DatabaseHelper.TRANSACTION_CATEGORY_ID, DatabaseHelper.TRANSACTION_TITLE,
DatabaseHelper.TRANSACTION_AMOUNT,DatabaseHelper.TRANSACTION_DATE,DatabaseHelper.TRANSACTION_NOTE};
Cursor mCursor=db.query(DatabaseHelper.TRANSACTION_TABLE_NAME,transactionColumns,null,null,null,null,null);
if(mCursor!=null) mCursor.moveToNext();
return mCursor;
}
}
These are my three classes of database functions. insertTransaction() is returning negative value which means data are not being inserted.
There might be problem due openhelper conflict. But I dont know how and where. Any help will be appreciated. Thanks!

I found the answer myself. I had created table name 'transaction' which happened to be sqlite keyword. I should have paid attention to sql keyword. Now I changed my table name to 'transactions' and it's working now.
Thankyou.

Related

want to delete database file in my app. .tried with a program, that did not work

I am trying to delete database table either programmatically or manually.
I created my own app which is under development.
My app is named SWULJ CT Conductor
But I do not find it under android/data/data folder with any com.xxx.xxx name format
code:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "BusDetails.db";
public static final String TABLE_NAME = "bus_details_table";
public static final String COL_1 = "ID";
public static final String COL_2 = "NUMBER";
public static final String COL_3 = "ROUTE";
public static final String COL_4 = "CITY";
public static final String COL_5 = "STATUS";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String myPath = TABLE_NAME + DATABASE_NAME;
SQLiteDatabase.deleteDatabase(new File(myPath));
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT,NUMBER TEXT,ROUTE TEXT,CITY TEXT,STATUS INTEGER)");
}
It is the partial code for the databasehelper class
It is called from Activity like this:
public class GenerateQrCodeActivity extends AppCompatActivity {
ImageButton imgButtonGenerateBulk;
ImageButton imgButtonGenerateSingle;
DatabaseHelper myDb;
EditText edit;
boolean flag = false;
String data_bus_number=null;
int ID_bus_number = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generate_qr_code);
myDb = new DatabaseHelper(this);
imgButtonGenerateBulk =(ImageButton)findViewById(R.id.imageButtonGenerateBulk);
imgButtonGenerateSingle =(ImageButton)findViewById(R.id.imageButtonGenerateSingle);
edit = (EditText) findViewById(R.id.bus_number);
.....
.....
I placed lines
String myPath = TABLE_NAME + DATABASE_NAME;
SQLiteDatabase.deleteDatabase(new File(myPath));
But the old data from the database shows up. It is not deleted. Why? how to fix?
done using the function->
public void deleteDatabase() {
// Are you sure? (y/n)
final SQLiteDatabase db = this.getWritableDatabase();
final File dbFile = new File(db.getPath());
db.close();
Toast.makeText(cntxt, "db deleted", Toast.LENGTH_SHORT).show();
edit.setText("db deleted");
if (dbFile.exists()) {
SQLiteDatabase.deleteDatabase(dbFile);
}
//mOpenHelper = new DatabaseHelper(getContext());
}

Drools : Getting the catched word in a list in THEN

Below is my pojo class
-----------------------------------pojo_Classes2.RootDoc.java-----------------------------------
package pojo_Classes2;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"content",
"person"
})
public class RootDoc {
#JsonProperty("content")
private String content;
#JsonProperty("person")
private List<String> person = null;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("content")
public String getContent() {
return content;
}
#JsonProperty("content")
public void setContent(String content) {
this.content = content;
}
#JsonProperty("person")
public List<String> getPerson() {
return person;
}
#JsonProperty("person")
public void setPerson(List<String> person) {
this.person = person;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
Here is the type of rule which i want to apply
$list1=[gaurav,gagan,anshu....]
...................................................................................................................
Rule1
If
content contains any of the above $list1
Then
Retrieve which name was captured in content and set person the person name in then
............................................................................................................
For eg. gaurav and gagan were captured in content then set get that gaurav and gagan were matched in content and get them back in then part.
Is it possible in drools
Yes, but create object of your class like:
when
$rd : Rootdoc(****your query****);
then
rd.setPerson(query);
end

JavaFx: Table view with different cell data type by row on the same column, HOW TO?

How to get different data class type on each row of the same column for a JavaFx table view?
Based on this post, here is a simple example that demonstrate how to get different data class type by row on the same column in a javaFx table view:
package application;
import java.time.LocalDateTime;
import javafx.application.Application;
import javafx.beans.property.IntegerProperty;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.stage.Stage;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.layout.VBox;
public class Main extends Application {
private final TableView<Person<?>> tableView = new TableView<>();
private Person<Integer> person1 = new Person<>("Jacob", "Smith", 28, 4);
private Person<Integer> person2 = new Person<>("Isabella", "Johnson", 19, 5);
private Person<String> person3 = new Person<>("Bob", "The Sponge", 13, "Say Hi!");
private Person<LocalDateTime> person4 = new Person<>("Time", "Is Money", 45, LocalDateTime.now());
private Person<Double> person5 = new Person<>("John", "Doe", 32, 457.89);
private final ObservableList<Person<?>> data = FXCollections.observableArrayList(person1, person2, person3, person4,
person5);
#SuppressWarnings("unchecked")
#Override
public void start(Stage primaryStage) {
TableColumn<Person<?>, String> firstNameCol = new TableColumn<>("First Name");
firstNameCol.setMinWidth(100);
firstNameCol.setCellValueFactory(new PropertyValueFactory<>("firstName"));
TableColumn<Person<?>, String> lastNameCol = new TableColumn<>("Last Name");
lastNameCol.setMinWidth(100);
lastNameCol.setCellValueFactory(new PropertyValueFactory<>("lastName"));
TableColumn<Person<?>, Integer> ageCol = new TableColumn<>("Age");
ageCol.setMinWidth(50);
ageCol.setCellValueFactory(new PropertyValueFactory<>("age"));
TableColumn<Person<?>, ?> particularValueCol = new TableColumn<>("Particular Value");
particularValueCol.setMinWidth(200);
particularValueCol.setCellValueFactory(new PropertyValueFactory<>("particularValue"));
tableView.setItems(data);
// Type safety: A generic array of Table... is created for a varargs
// parameter
// -> #SuppressWarnings("unchecked") to start method!
tableView.getColumns().addAll(firstNameCol, lastNameCol, ageCol, particularValueCol);
// Output in console the selected table view's cell value/class to check
// that the data type is correct.
SystemOutTableViewSelectedCell.set(tableView);
// To check that table view is correctly refreshed on data changed..
final Button agePlusOneButton = new Button("Age +1");
agePlusOneButton.setOnAction((ActionEvent e) -> {
Person<?> person = tableView.getSelectionModel().getSelectedItem();
try {
person.setAge(person.getAge() + 1);
} catch (NullPointerException npe) {
//
}
});
final VBox vbox = new VBox();
vbox.setSpacing(5);
vbox.setPadding(new Insets(10, 0, 0, 10));
vbox.getChildren().addAll(tableView, agePlusOneButton);
Scene scene = new Scene(new Group());
((Group) scene.getRoot()).getChildren().addAll(vbox);
primaryStage.setWidth(600);
primaryStage.setHeight(750);
primaryStage.setScene(scene);
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
public static class Person<T> {
private final StringProperty firstName;
private final StringProperty lastName;
private final IntegerProperty age;
private final ObjectProperty<T> particularValue;
private Person(String firstName, String lastName, Integer age, T particularValue) {
this.firstName = new SimpleStringProperty(firstName);
this.lastName = new SimpleStringProperty(lastName);
this.age = new SimpleIntegerProperty(age);
this.particularValue = new SimpleObjectProperty<T>(particularValue);
}
public String getFirstName() {
return firstName.get();
}
public void setFirstName(String firstName) {
this.firstName.set(firstName);
}
public StringProperty firstNameProperty() {
return firstName;
}
public String getLastName() {
return lastName.get();
}
public void setLastName(String lastName) {
this.lastName.set(lastName);
}
public StringProperty lastNameProperty() {
return lastName;
}
public Integer getAge() {
return age.get();
}
public void setAge(Integer age) {
this.age.set(age);
}
public IntegerProperty ageProperty() {
return age;
}
public T getParticularValue() {
return particularValue.get();
}
public void setParticularValue(T particularValue) {
this.particularValue.set(particularValue);
}
public ObjectProperty<T> particularValueProperty() {
return particularValue;
}
}
public static final class SystemOutTableViewSelectedCell {
#SuppressWarnings({ "rawtypes", "unchecked" })
public static void set(TableView tableView) {
tableView.getSelectionModel().setCellSelectionEnabled(true);
ObservableList selectedCells = tableView.getSelectionModel().getSelectedCells();
selectedCells.addListener(new ListChangeListener() {
#Override
public void onChanged(Change c) {
TablePosition tablePosition = (TablePosition) selectedCells.get(0);
Object val = tablePosition.getTableColumn().getCellData(tablePosition.getRow());
System.out.println("Selected Cell (Row: " + tablePosition.getRow() + " / Col: "
+ tablePosition.getColumn() + ") Value: " + val + " / " + val.getClass());
}
});
}
}
}

Execute Stored Procedure in JPA 2.0

I have the following problem and I do not how to solve it.
I have a stored procedure with one parameter ( a date in the format: yyyy-MM-dd ) on my MSSQL Server 2008.
Then I have an #Entity class with a #NamedNativeQuery:
#NamedNativeQuery(name = "my_stored_proc",query = "? = exec EMIR_GUI.get_OTCLite_ACKNACK_Report ?", resultClass = EmirFacade.class)
#Entity
public class EmirFacade {
#Column(name="MessageType", nullable=false)
#Basic(fetch = FetchType.EAGER)
private String mesageType;
My Bean class looks like this:
#PersistenceContext(unitName=Globals.__TWHUNITNAME)
private EntityManager em;
public List<EmirFacade> get_EmirReport(Date date) {
try {
#SuppressWarnings("unchecked")
Query q = em.createNamedQuery("my_stored_proc").setParameter(1, date);
List<EmirFacade> emir_report = q.getResultList();
//List emir_report = q.getResultList();
return emir_report;
} catch (Exception e) {
return Collections.emptyList();
}
}
Now, I always get back the following error message ( it is in german, so I have to translate it as good as I can )
Index "0" is out of range.
I tried nearly everything but I cannot find any way to solve my problem.
Maybe, somebody has a good suggestion for me?
Thank you very much!
JPA 2.0 has no explicit support for stored procedures (JPA 2.1 has).
One workaround is to use native queries (like {CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}), but that doesn’t work when the procedure has out-parameters.
Here is a sample implementation that uses Hibernate’s Work interface:
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Types;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.hibernate.Session;
import org.hibernate.jdbc.Work;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
#Service
public class CampanhaBrindesStoredProcedure {
#PersistenceContext
private EntityManager entityManager;
private String mensagem;
private String geroubrinde;
#Transactional
public void apurarCampamha(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
try {
MyStoredProc storedProc = new MyStoredProc(numeroPedido, codigoFilialNF,
cgcEntCGCENT, numeroSequencia, integradora);
entityManager.unwrap(Session.class).doWork(storedProc);
setGeroubrinde(storedProc.getGeroubrinde());
setMensagem(storedProc.getMensagem());
} catch (Exception e) {
e.printStackTrace();
}
}
public String getGeroubrinde() {
return geroubrinde;
}
public void setGeroubrinde(String geroubrinde) {
this.geroubrinde = geroubrinde;
}
public String getMensagem() {
return mensagem;
}
public void setMensagem(String mensagem) {
this.mensagem = mensagem;
}
private static final class MyStoredProc implements Work {
private final Long numeroPedido;
private final String codigoFilialNF;
private final String cgcEntCGCENT;
private final Long numeroSequencia;
private final String integradora;
private String mensagem;
private String geroubrinde;
private MyStoredProc(Long numeroPedido, String codigoFilialNF,
String cgcEntCGCENT, Long numeroSequencia, String integradora) {
this.numeroPedido = numeroPedido;
this.codigoFilialNF = codigoFilialNF;
this.cgcEntCGCENT = cgcEntCGCENT;
this.numeroSequencia = numeroSequencia;
this.integradora = integradora;
}
#Override
public void execute(Connection conn) throws SQLException {
try (CallableStatement stmt = conn
.prepareCall("{CALL APURARCAMPANHASBRINDES.PROC_APURARCAMPANHA(?1, ?2, ?3, ?4, ?5, ?6, ?7)}")) {
stmt.setLong(1, numeroPedido);
stmt.setString(2, codigoFilialNF);
stmt.setString(3, cgcEntCGCENT);
stmt.setLong(4, numeroSequencia);
stmt.setString(5, integradora);
stmt.registerOutParameter(6, Types.VARCHAR);
stmt.registerOutParameter(7, Types.VARCHAR);
stmt.executeUpdate();
mensagem = stmt.getString(6);
geroubrinde = stmt.getString(7);
if (stmt.wasNull()) {
geroubrinde = null;
mensagem = null;
}
}
}
public String getMensagem() {
return mensagem;
}
public String getGeroubrinde() {
return geroubrinde;
}
}
}
If you can switch to JPA 2.1 (and I strongly suggest you to do so) you can simply do:
StoredProcedureQuery storedProcedure = em.createStoredProcedureQuery("yourStoredprocedure");
// set parameters
storedProcedure.registerStoredProcedureParameter("parameterName", String.class, ParameterMode.IN);
storedProcedure.setParameter("parameterName", "yourParameter");
// execute stored procedure
storedProcedure.execute();
otherwise it's a bit more convoluted, simply follow this tutorial.

GWT: gwt-exporter: passing objects

I've been struggling with passing Java objects from Java through JSNI (gwt-exporter generated) into Java and wonder if anybody can help?
I am creating an object in Java ("Person"), passing it to a JSNI method ("displayPerson") that invokes a Java method exposed with gwt-exporter ("CommonService.displayPerson"); however the parameter to the last stage becomes null.
If I pass a String it works OK; it's just with my objects I hit the problem.
Person is defined in a GWT application JAR inherited by the other GWT application.
Thanks for looking,
Mike
GWT application
package com.anstis.pluginserver.client;
import com.anstis.plugincommon.shared.Person;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
public class PluginServer implements EntryPoint {
public void onModuleLoad() {
GWT.create(CommonService.class);
onLoadImpl();
RootPanel.get("container").add(getButton());
}
private native void onLoadImpl() /*-{
if ($wnd.jscOnLoad && typeof $wnd.jscOnLoad == 'function') $wnd.jscOnLoad();
}-*/;
private Button getButton() {
Button btn = new Button("Click!");
btn.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
Person p = new Person();
p.setName("Smurf");
p.setAge(500);
displayPerson(p);
}
});
return btn;
}
private native void displayPerson(Person person) /*-{
// The below displays shows 'person' is not null
alert("PluginServer.displayPerson.person is " + (person != null ? "not " : "") + "null");
try {
var pluginServer = new $wnd.com.anstis.pluginserver.CommonService();
// The below displays shows 'pluginServer' is not null
alert("PluginServer.displayPerson.pluginServer = " + pluginServer);
pluginServer.displayPerson(person);
} catch(err) {
alert(err);
}
}-*/;
}
CommonService.java
package com.anstis.pluginserver.client;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.Exportable;
import com.anstis.plugincommon.shared.Person;
import com.anstis.plugincommon.shared.PluginCallback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Window;
#Export
public class CommonService implements Exportable {
public void displayPerson(Person person) {
//The below shows 'person' *IS* null
Window.alert("CommonService.displayPerson.person is "
+ (person != null ? "not " : "") + "null");
Window.alert("Name=" + person.getName());
}
}
Person.java
package com.anstis.plugincommon.shared;
import org.timepedia.exporter.client.Exportable;
public class Person implements Exportable {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
You need no to implement Exportable for Person class.
public class Person {
and it works.
If anybody else stumbles across this question, I now have a working example at git://github.com/manstis/gwt-plugins.git