In below code null pointer exception is thrown when we set the adapter into the spinner - android-widget

ArrayList<String> nameArray=new ArrayList<String>();
do
{
nameArray.add(cursor.getString(cursor.getColumnIndex("Name")));
System.out.println(cursor.getString(cursor.getColumnIndex("Name")));
}while(cursor.moveToNext());
//set up the spinner
Spinner spinner = (Spinner)this.findViewById(R.id.Spinner01);
MyAdapter adapter = new MyAdapter(nameArray);
// apply the Adapter:
spinner.setAdapter(adapter);
i have written above code to add string array into spinner.
but null pointer exception is thrown on last line.
i am not able to add string values to the spinner.
any one plz help me out of this.

spinner is probably null. Maybe you have no element with that specific id?

Related

How to pass data from listview to next(details) screen

I have created one sstatic Arraylist and displayed the data in listview using the custom adapter. My requirement is when i click on the listitem, i have to show the details of particular listitem in the next screen. How can i pass the selected listitem data from listview screen to details screen.
I have tried to pass the data using the parcelable concept. But when I click on the listitem, i am getting "Null pointer exception"
Any complete example will be very helpful.
Thanks in advance.
It can be acheived in following way.I'm assuming that your list item is a text view.
Add onItemClick Listener to your listview,get Selected Item's text on click and pass it with itent extras to NextActivity.
listview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View p_view,
int p_pos, long arg3) {
TextView text= (TextView ) p_view.findViewById(R.id.textview1); //id of textview from layout file that you are inflating.
String mytext=text.getText();
Intent i = new Intent(Context context,NextActivity.class);
i.putExtra("text",mytext);
startActivity(i);
}
});
And on the next activity,retreive the text from extras.
Bundle extras = getIntent().getExtras();
String text_value= extras.getString("text");

How to don't validate form with Ajax buttons

I have a problem with validation on form actually sub-form.
In my website I have some kind of table and "Add row" button (BlockingAjaxSubmitLink).
When I try add let say 2 rows, I get validation error (because row in this table has Required=True parameter) and I can't add another row. I tried use simple AjaxLink but it doesn't have reference to form in onClick method and when I complete some rows and click "Add row" this data get lost.
I want to enable validation only after "save" button click.
Any idea how to deal with this problem?
I do something like you want using an AjaxLink.
My AjaxLink:
private AjaxLink addNewRow = new AjaxLink("addNewRow") {
#Override
public void onClick(AjaxRequestTarget target) {
MyEntityObject newTableRowObject = new MyEntityObject(irrelevantParameter);
entityObjectTableService.createNewRowInDB(newTableRowObject );
target.add(listViewContainer);
}
};
In this code the listViewContainer is a WebMarkupContainer which contains a ListView holding the table rows.
When i click this AjaxLink a new object representing a row in my table is added to the database and then the container containing the ListView is being refreshed refreshing the ListView and the new empty object is being fetched from the DB and shown as a new row in my table at the end.
Depending on your structure maybe you are looking after disabling validation using setDefaultFormProcessing(true); - http://ci.apache.org/projects/wicket/apidocs/6.x/org/apache/wicket/markup/html/form/AbstractSubmitLink.html#setDefaultFormProcessing%28boolean%29
For now I write some kind of hack
First I set
addKnowledgeLink.setDefaultFormProcessing(false);
and next
BlockingAjaxSubmitLink<Object> addKnowledgeLink = new BlockingAjaxSubmitLink<Object>(
"link_knowledge_add") {
#Override
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
ChangeDataForm.this.process(this);
/* some code */
target.add(form.get(MY_CONTAINER_ID));
}
(...)
and my hack...
//HACK
public void process(IFormSubmitter object){
if (!isEnabledInHierarchy() || !isVisibleInHierarchy())
{
return;
}
// run validation
validate();
/*if (hasError())
{
// mark all children as invalid
markFormComponentsInvalid();
// let subclass handle error
callOnError(object);
}
else
{*/
// mark all children as valid
markFormComponentsValid();
// before updating, call the interception method for clients
beforeUpdateFormComponentModels();
// Update model using form data
updateFormComponentModels();
// validate model objects after input values have been bound
onValidateModelObjects();
if (hasError())
{
callOnError(object);
return;
}
// Form has no error
delegateSubmit(object);
//}
}
and I ovveride one method
#Override
protected void onError(){
super.onError();
this.updateFormComponentModels();
}
I know it is ugly solution but I couldn't figure out anything better..
And I couldn't shutdown feedback messages

Inserting GWT widget into a div element

I'm using a GWT library (gwt-openlayers) which allows me to create a map popup containing arbitrary HTML, similar to Google Maps. I need this HTML to contain a GWT Button widget.
I'm creating some HTML elements on-the-fly like this:
Element outerDiv = DOM.createDiv();
outerDiv.getStyle().setOverflow(Overflow.HIDDEN);
outerDiv.getStyle().setWidth(100, Unit.PCT);
outerDiv.appendChild(new HTML(mapPOI.getHtmlDetails()).getElement());
Button popupButton = new Button("View Property");
popupButton.getElement().getStyle().setFloat(com.google.gwt.dom.client.Style.Float.RIGHT);
outerDiv.appendChild(popupButton.getElement());
Then I'm getting the source HTML for these elements by calling
String src = outerDiv.toString();
and inserting this html into my map marker. Now my map marker displays the content ok, including the button. However, the button won't respond to any events! From what I can gather, this is because the buttons onAttach() method is never being called.
Is there a better way to do this?
Thanks,
Jon
~~~~EDIT~~~~
I'm now trying a new way of doing this, which seems to be the accepted method looking at other similar posts.
First I'm creating my div:
String divId = "popup-" + ref;
String innerHTML = "<div id=\"" +divId + "\"></div>";
Then I'm adding this to my map popup and displaying it (which adds it to the DOM). After the popup has been displayed, I'm getting the Element as follows and trying to wrap a HTMLPanel around it:
Element element = Document.get().getElementById(divId);
HTMLPanel popupHTML = HTMLPanel.wrap(element);
My div element is successfully retrieved. However, HTMLPanel.wrap(element); doesn't complete. The reason for this is that wrap(..) calls RootPanel.detachOnWindowClose(Widget widget), which includes the following assertions:
assert !widgetsToDetach.contains(widget) : "detachOnUnload() called twice "
+ "for the same widget";
assert !isElementChildOfWidget(widget.getElement()) : "A widget that has "
+ "an existing parent widget may not be added to the detach list";
I put some breakpoints in and it seems that the 2nd assertion is failing!
Does anybody have any idea why this might be the case? Should failing this assertion really result in a complete failure of the method (no return)?
Your first approach is good, you just need to register onClick event for your button like this:
DOM.sinkEvents(popupButton.getElement(), Event.ONCLICK);
DOM.setEventListener(popupButton.getElement(), new EventListener() {
#Override
public void onBrowserEvent(Event event) {
//implement the logic after click
}
});
I have checked this, it works 100%!
You might try something like
RootPanel.get("idOfYourMapMarker").add(popupButton);
See RootPanel.get()
Unfortunately, RootPanels are AbsolutePanels which aren't so nice for layout but could work if you just have a simple button to add. You could also try RootLayoutPanel which will give you a LayoutPanel (also not so nice when you just want things to flow). You might end up creating a container widget that does the layout for you, and adding that to the RootPanel.
SimplePanel is a DIV. Perhaps that can be used instead?
You added the element, but you have to keep the hierarchy of the actual GWT Widgets too.
I don't see a clean way to do this, but you could use something like jQuery to grab the button by and ID and add a click handler back to it that would call the original click handler.
private static native void registerEvents(String buttonId, MyClass instance)/*-{
var $ = $wnd.$;
//check click
$('#'+buttonId).live('click', function(e) {
e.preventDefault();
instance.#com.package.MyClass::handleButtonClick(Lcom/google/gwt/event/dom/client/ClickEvent;)(null);
});
}-*/;
Call this registerEvents() either in your onAttach or constructor.
I once had a similar problem. You can use the gwt-openlayer's MapWidget as follows:
private MapWidget createMapWidget() {
final MapOptions defaultMapOptions = new MapOptions();
defaultMapOptions.setDisplayProjection(DEFAULT_PROJECTION);
defaultMapOptions.setNumZoomLevels(TOTAL_ZOOM_LEVELS);
MapWidget mapWidget = new MapWidget(MAP_WIDGET_WIDTH, MAP_WIDGET_HEIGHT, defaultMapOptions);
map = mapWidget.getMap();
return mapWidget;
}
And then add it to any panel be it vertical or horizontal.
MapWidget mapWgt = createMapWidget();
VerticalPanel mainPanel = new VerticalPanel();
mainPanel.add(mapWgt);
...
... add whatever you want
...
You can finally add the created Panel(containing the MapWidget and the gwt widget) to the PopupPanel. Also, you should now be able to add handlers to the gwt button.

Silverlight ChildWindow not disposed using MEF and MVVM

I'm not sure if what I'm experiencing is the same as here: Silverlight ChildWindow Memory Leak
but...:
I've got a Silverlight ChildWindow with 3 radio buttons in the same group with IsChecked all set to false in XAML, I don't want any of them selected upon opening. I open up the ChildWindow from my viewmodel:
if (_NewChildWindowCommand == null)
_NewChildWindowCommand = new RelayCommand(param => _cwService.ShowDialog(_newLocation, new NewViewModel(), closed =>
{
if (_newLocation.DialogResult.HasValue && _newLocation.DialogResult.Value)
{
//do something
}
_newLocation = null;
_newLocation = _container.GetExportedValue<INewChildWindow>();
}));
I then select one of the radio buttons hit OK. It Closes, I open it up again and the ChildWindow seems to have been disposed since upon opening, none of those radio buttons are selected (the way it should be). So I select a radio button again,hit OK, It Closes...But the third time I open the ChildWindow, it has the same radio button selected as when I closed it. This is what I don't understand. I thought by setting _newLocation=null like I did and then getting INewChildWindow from the container would give me a new ChildWindow but it doesn't seem to be the case. I tried calling GC.Collect() after setting _newLocation to null but that didn't work, and I tried setting the PartCreationPolicy to NonShared on the ChildWindow, however that doesn't make a difference since the instance of the ChildWindow is being stored in _newLocation and the class containing _newLocation isn't disposed of:
[ImportingConstructor]
public HomeViewModel(IChildWindowService cwService, INewLocationChildWindow newLocationChildWindow)
{
if (!IsDesignTime)
{
_cwService = cwService;
_newLocation = newLocationChildWindow;
_catalog = new AggregateCatalog();
_catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
_container = new CompositionContainer(_catalog);
}
}
Is there something else going on here?
Set the creation policy of the ChildWindow to NonShared. Then replace _container.GetExportedValue<INewChildWindow>() with _container.GetExport<INewChildWindow>(). This will give you a Lazy<INewChildWindow>, and you can use the Value property to get the child window. Then to release the export call _container.ReleaseExport, passing in the Lazy that was returned by the call to GetExport.

GWT 2.1 CellTable Shows Only Loading Bar

Following both the example from the GWT Showcase and the example found at GWT, I implemented a CellTable. The CellTable displays the first 15 results but subsequent pages only displays the loading bar. Attempting to return to the first 15 results shows only the loading bar as well. No errors in the JavaScript console or within the GWT developer console are raised.
Any help or insight that anyone can give would be greatly appreciated.
Further, I tried the following and it too suffered from the same thing happening:
List<String> stringsList = new ArrayList<String>();
for( int i = 0; i < 60; i++){
stringsList.add("" + i);
}
CellTable<String> cellTable = new CellTable();
TextColumn<String> nameColumn = new TextColumn<String>(){
#Override
public String getValue(String string){
return string;
}
};
SimplePager.Resources pagerResources = GWT.create(SimplePager.Resources.class);
SimplePager pager = new SimplePager(TextLocation.CENTER, pagerResources, false, 0, true);
pager.setDisplay(cellTable);
cellTable.addColumn(nameColumn, "App Name");
cellTable.setRowCount(stringsList.size(), true);
cellTable.setRowData(0, stringsList);
RootLayoutPanel.get().add(cellTable);
RootLayoutPanel.get().add(pager);
Why don't use a DataProvider and setList to fill the Table? Somewhere I read that this is the recommended approach and setRowData shouldn't be used (because it can cause some weird behaviour)
I think you need a data provider to push data into the cell table. Add the next code and it should work.
ListDataProvider dataProvider = new ListDataProvider();
dataProvider.setList(stringsList );
dataProvider.addDataDisplay(cellTable);
This happens when there's some problem with setVisibleRange or a similar method. I get this a lot when a list backing the data provider doesn't have enough values, or something. I recommend you trace your program to the point at which you're changing the visible range and check all the values that are going into your methods there.