Click handler of button - gwt

I want to add a button and add click handler to it after entering the values in database.
I want that button to be on onSucess of greeting service.
help me
public static void edit1(String fnme,String lnme,String clgn,String scn){
greetingService.enter(fnme,lnme,clgn,scn, new AsyncCallback<String>()
{
public void onSuccess(String result)
{
Window.alert("successfully entered");
// TODO Auto-generated method stub
Button bt =new Button("submit");
RootPanel.get().add(bt);
bt.addClickHandler(new MyClickHandler);
}
public void onFailure(Throwable caught)
{
Window.alert("fail");
}
});
}
class MyClickHandler implements ClickHandler
{
public void onClick(ClickEvent e)
{
//create();
}
}
but this is not working.

Do you need the click handler?
Anyway this is what I think you're trying to do:
Button bt =new Button("submit");
RootPanel.get().add(bt);
bt.addClickHandler(new MyClickHandler);
public static void edit1(String fnme,String lnme,String clgn,String scn)
{
greetingService.enter(fnme,lnme,clgn,scn, new AsyncCallback<String>()
{
public void onSuccess(String result)
{
Window.alert("successfully entered");
// TODO Auto-generated method stub
create();
}
public void onFailure(Throwable caught)
{
Window.alert("fail");
}
});
}
class MyClickHandler implements ClickHandler
{
public void onClick(ClickEvent e)
{
// create();
}
}

Your MyClickHandler does nothing inside the onClick() method. It should work as long as you put code. Try this:
public static void edit1(String fnme,String lnme,String clgn,String scn){
greetingService.enter(fnme,lnme,clgn,scn, new AsyncCallback<String>() {
public void onSuccess(String result) {
Window.alert("successfully entered");
// TODO Auto-generated method stub
Button bt =new Button("submit");
RootPanel.get().add(bt);
bt.addClickHandler(new MyClickHandler() {
public void onClick(ClickEvent e) {
//DO SOMETHING HERE
}
});
}
public void onFailure(Throwable caught) {
Window.alert("fail");
}
});
}
class MyClickHandler implements ClickHandler {
public void onClick(ClickEvent e) {
/* OR DO SOMETHING HERE, BUT THAT WILL AFFECT ALL
* INSTANCES OF MyClickHandler
*/
}
}

Related

getting parse initialization error while unit testing activity with Robolectrics framework and eclipse

I am unit testing activity with Robolectric framework and getting the following error of parse initialization error.
MyActivity.java
public class WelcomeActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// hide action bar
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.hide();
//Checking Current User
ParseUser currentUser = ParseUser.getCurrentUser();
if (currentUser != null)
{
Intent i=new Intent(WelcomeActivity.this, ViewPagerStyleLandingActivity.class);
startActivity(i);
WelcomeActivity.this.finish();
}
setContentView(R.layout.actvity_welcome);
SharedPreferences pref = getSharedPreferences(Constants.SIGNUP_CHECK_PREF, MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(Constants.PREF_KEY_FIRST_RUN, false);
editor.commit();
Button loginbut=(Button) findViewById(R.id.login);
Button registerbut=(Button) findViewById(R.id.register);
loginbut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i=new Intent(WelcomeActivity.this,LoginActivity.class);
startActivity(i);
}
});
registerbut.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent i=new Intent(WelcomeActivity.this,RegisterActivity.class);
startActivity(i);
}
});
}
}
and have made the test case as
#RunWith(RobolectricTestRunner.class)
public class WelcomeActivityTest {
private WelcomeActivity activity;
private Button loginbut;
#Before
public void setup() {
activity = Robolectric.buildActivity(WelcomeActivity.class).create().get();
loginbut = (Button) activity.findViewById(R.id.button);`}
#Test
public void checkActivityNotNull() throws Exception {
assertNotNull(activity);
}
#Test
public void shouldHaveButtonThatSaysAudit() throws Exception{
assertThat((String) loginbut.getText(), equalTo("Login"));
}
#Test
public void pressingLaunchButtonForSecondActivity() throws Exception {
String resultValue = "Testing Text";
assertNotNull(loginbut);
loginbut.performClick();
Intent startedIntent = shadowOf(activity).getNextStartedActivity();
assertThat(resultValue, equalTo(startedIntent.getStringExtra("result")));
}
private ShadowContextWrapper shadowOf(WelcomeActivity activity2) {
return null;
}
#After
public void tearDown() throws Exception {
// Nothing Here
}
}
now getting the error
when running with jUnit

GWT Array of checklist click handler not working

i have been trying to generate an array of check boxes and dynamic click handler for them but the handler is not working. Any suggestion will be most welcomed. Thanks in Advance for the time.
private void addButtonListener() {
goButton.addClickHandler(new ClickHandler() {
#SuppressWarnings("rawtypes")
#Override
public void onClick(ClickEvent arg0) {
String strQuery="Select BRANCH_NAME from SAMPLE_ACC_BRANCH where GL_CODE='"+gll_textfield.getText().trim()+"'";
HibernateImplUtils.getSearchResult(strQuery, new AsyncCallback() {
private int i;
#Override
public void onFailure(Throwable arg0)
{arg0.printStackTrace();}
#Override
public void onSuccess(Object arg0) {
System.err.println("Inside Success");
List branchNameList=(List) arg0;
System.err.println("Branch List:::"+branchNameList);
for(i=0;i<branchNameList.size();i++){
checkbox[i]=new CheckBox((String) branchNameList.get(i));
vpanel.add(checkbox[i]);
checkbox[i].addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent arg0) {
if(checkbox[i].getValue()){
System.out.println("NAME::::"+checkbox[i].getText());
}
System.out.println("Selected check box ::::"+checkbox[i].getText());
}
});
}
}
});
}
});
}
The scope of "i" is dodgy. Quickest fix would be to make a "final" copy for your event handler. e.g. "final int i2 = i"
The inner class probably wants the index value during its creation.
I'd be tempted to do use a final reference to the checkbox you create or the reference passed to the event handler (that way you could also use a single instance).
(Modified)
final int i2=i;
checkbox[i2].addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent arg0) {
if(checkbox[i2].getValue()){
System.out.println("NAME::::"+checkbox[i2].getText());
}
}
});

Multiple Click handlers

I have different 3 Different Buttons with different onclick events :
add.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
add();
}
});
set.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
set();
}
});
get.addClickHandler(new ClickHandler()
{
#Override
public void onClick(ClickEvent event)
{
get();
}
});
So now if i extend this up to 10 Buttons my Script would be far to long,
is there a way to pass the Methode or do seperate the Handlers?
Suppose you have some view:
customview.ui.xml
<g:VerticalPanel>
<style:Button ui:field="addButton" text="Add"/>
<style:Button ui:field="setButton" text="Set"/>
<style:Button ui:field="getButton" text="Get"/>
</g:VerticalPanel>
In your View class define 3 fields and 3 handlers:
CustomView.java
public class CustomView extends ViewWithUiHandlers<CustomUiHandlers>
implements CustomPresenter.MyView {
#UiField
Button addButton;
#UiField
Button setButton;
#UiField
Button getButton;
// Here constructor and other code
#UiHandler("addButton")
void onAddButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onAddClicked();
}
}
#UiHandler("setButton")
void onSetButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onSetClicked();
}
}
#UiHandler("getButton")
void onGetButtonClicked(ClickEvent event) {
if (getUiHandlers() != null) {
getUiHandlers().onGetClicked();
}
}
}
CustomUiHandlers.java
public interface CustomUiHandlers extends UiHandlers {
void onAddClicked();
void onSetClicked();
void onGetClicked();
}
CustomPresenter.java
public class CustomPresenter extends
Presenter<CustomPresenter.MyView, CustomPresenter.MyProxy>
implements CustomUiHandlers {
// Some code
#Override
public void onAddClicked() {
// Here your code
}
#Override
public void onSetClicked() {
// Here your code
}
#Override
public void onGetClicked() {
// Here your code
}
}
You can bind event handler to a method by UiBinder, or alternatively wait for lambda support for GWT.

How to use same servlet for RPC and upload File in GWT.

i created a web application where i have to use fileUpload.
i have to send the file and their properties to server . For sending a file i used FormPanel and for properties i used RPC .
public void onModuleLoad() {
final FileServiceEndPoint serviceEndPoint = new FileServiceEndPoint();
new AddDocument();
Button b = new Button("addDocument");
b.addClickHandler(new ClickHandler() {
private Map<String, String> docProperty;
public void onClick(ClickEvent event) {
docProperty =getProperties();
AsyncCallback<String> callback = new AsyncCallback<String>() {
public void onSuccess(String result) {
System.out.println("he ha" +result);
}
public void onFailure(Throwable caught) {
}
};
serviceEndPoint.uploadAttachement(docProperty, callback);
}
});
RootPanel.get().add(b);
}
this new AddDocument(); contains code for uploading a file (formPanel code)
private FormPanel getFormPanel() {
if (uploadForm == null) {
uploadForm = new FormPanel();
uploadForm.setAction(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.setEncoding(FormPanel.ENCODING_MULTIPART);
uploadForm.setMethod(FormPanel.METHOD_POST);
uploadForm.setWidget(getFileUpload());
System.out.println(GWT.getHostPageBaseURL() +"TestUploadFileServlet");
uploadForm.addFormHandler(new FormHandler() {
public void onSubmitComplete(FormSubmitCompleteEvent event) {
AddDocument.this.hide(true);
}
public void onSubmit(FormSubmitEvent event) {
}
});
}
return uploadForm;
}
private Button getAddButton() {
if (addButton == null) {
addButton = new Button("ADD");
addButton.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
uploadForm.submit();
}
});
addButton.setText("Add");
}
Interface is created for Sending property.
EndPoints:
public class FileServiceEndPoint implements FileServiceAsync{
FileServiceAsync service = (FileServiceAsync)GWT.create(FileService.class);
ServiceDefTarget endpoint = (ServiceDefTarget) service;
public FileServiceEndPoint() {
endpoint.setServiceEntryPoint(GWT.getHostPageBaseURL() + “TestUploadFileServlet”);
}
public void uploadAttachement(Map docProperty,
AsyncCallback callback) {
service.uploadAttachement(docProperty, callback);
}
}
On Server:
public class FileUploadImpl extends RemoteServiceServlet implements FileService {
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger(FileUploadImpl.class
.getName());
String a;
protected void service(final HttpServletRequest request,HttpServletResponse response)
throws ServletException,IOException {
a=”5″;
System.out.println(“ServletWorking Fine “);
}
public String uploadAttachement(Map docProperty) {
// TODO Auto-generated method stub
return “Checked”;
}
}
When I debug formPanel.submit : the debugger goes in Server and print ServletWorking Fine(this is perfect)
and when i debug the addProperties button it goes to server and print ServletWorking Fine. but It should not go in service method.
the debugger should go in UploadAttachement.
Plz tell how to pass hashMap using same servlet.

Activity handlers don't get removed

I'm trying to get up to speed on using GWT Activities and Places. I'm testing with some source code originally found on this good blog post.
I'm finding the Handlers that get added during bind() never seem to removed. My little understanding of the Activity javadoc had me thinking they should get automagically removed by the time the Activity's onStop() method is invoked.
All event handlers it registered will have been removed before this
method is called.
But each time I click a button the corresponding handler is called n+1 times.
What am I missing? Please let me know if there is more info I can provide.
Here's a relevant snippet from the code:
public class ContactsActivity extends AbstractActivity {
private List<ContactDetails> contactDetails;
private final ContactsServiceAsync rpcService;
private final EventBus eventBus;
private final IContactsViewDisplay display;
private PlaceController placeController;
public interface IContactsViewDisplay {
HasClickHandlers getAddButton();
HasClickHandlers getDeleteButton();
HasClickHandlers getList();
void setData(List<String> data);
int getClickedRow(ClickEvent event);
List<Integer> getSelectedRows();
Widget asWidget();
}
public ContactsActivity(ClientFactory factory) {
GWT.log("ContactActivity: constructor");
this.rpcService = factory.getContactServiceRPC();
this.eventBus = factory.getEventBus();
this.display = factory.getContactsView();
this.placeController = factory.getPlaceController();
}
#Override
public void start(AcceptsOneWidget container, EventBus eventBus) {
GWT.log("ContactActivity: start()");
bind();
container.setWidget(display.asWidget());
fetchContactDetails();
}
public void bind() {
GWT.log("ContactActivity: bind()");
display.getAddButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("Add button clicked");
ContactsActivity.this.placeController.goTo(new NewContactPlace(""));
}
});
display.getDeleteButton().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("ContactActivity: Delete button clicked");
deleteSelectedContacts();
}
});
display.getList().addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {
GWT.log("ContactActivity: List clicked");
int selectedRow = display.getClickedRow(event);
if (selectedRow >= 0) {
String id = contactDetails.get(selectedRow).getId();
ContactsActivity.this.placeController.goTo(new EditContactPlace(id));
}
}
});
}
Events registered via. the EventBus passed to AbstractActivity#start() will be unregistered by the time onStop() is called. The event handlers registered in the above bind() method, however, are not registered via the EventBus and are not visible to the abstract base class. You need to unregister them yourself:
public class ContactsActivity extends AbstractActivity {
private List<HandlerRegistration> registrations = new ArrayList();
private void bind() {
registrations.add(display.getAddButton().
addClickHandler(new ClickHandler() { ... }));
registrations.add(display.getDeleteButton().
addClickHandler(new ClickHandler() { ... }));
registrations.add(display.getList().
addClickHandler(new ClickHandler() { ... }));
}
#Override
public void onStop() {
for (HandlerRegistration registration : registrations) {
registration.removeHandler();
}
registrations.clear();
}
}
I found it best to handle registration in the view - make it responsible for only keeping one click hander active for each button.
Instead of:
class View {
Button commitButton;
public HasClickHandlers getCommit () {return commitButton;}
}
..and link to this in the Activity:
view.getCommit.addClickHandler(new Clickhandler()...
Do this in the View:
class View {
private Button commitButton;
private HandlerRegistration commitRegistration = null;
public void setCommitHandler (ClickHandler c) {
commitRegistraion != null ? commitRegistration.removeRegistration ();
commitRegistration = commitButton.addClickHandler (c);
}
}
And the Activity:
view.setCommitHandler (new ClickHandler () ...
Hope that helps.