Flex Mobile Access List value from itemRenderer - list

I have a list which is populated by list.dataProvider:
<fx:Script>
<![CDATA[
list.dataProvider = new ArrayCollection(getClass.listArticles(group, subgroup));
]]>
</fx:Script>
<s:List id="list" x="0" y="0" width="100%" height="100%" labelField="ArticleName" change="navigator.pushView(DetailView, list.selectedItem)">
<s:itemRenderer>
<fx:Component>
<s:IconItemRenderer labelField="ArticleName"
messageField="EAN"/>
<s:Image source="#Embed('assets/images/{EAN}.jpg')" width="70" height="70" horizontalCenter="0" verticalCenter="0" />
</fx:Component>
</s:itemRenderer>
<s:layout>
<s:TileLayout columnWidth="200" rowHeight="200" columnAlign="justifyUsingWidth" horizontalGap="10" orientation="rows" verticalGap="10"/>
</s:layout>
</s:List>
labelField and messageField values are properly filled with the result of the dataProvider. The image source variable is not. How do I get/access this variable from the dataProvider ({EAN})?

Maybe by overriding set/get data?
override public function set data(value:Object):void {
super.data = value;
if (!data)
return;
img.source = data['EAN'];
// or maybe: var xml:XML = data as XML; etc.
}

Related

New Activity not opening on List Item Click

I am new to Android and found so many helpful threads on lists. But somehow I am not able to open a new activity on List Item Click.
Till now My app has 4 classes.
Splash- works fine
MyActivity- Works fine
Poems- Works fine
test
Till Poems my app works fine. But on Poems when i click a list item it doesn't do anything.
Here is my code.
Poems.class
package apps.panky.poemsnrhymes;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Poems extends ActionBarActivity implements AdapterView.OnItemClickListener {
ListView list;
String poems[] = {"Aiken Drum", "A Was an Apple Pie", "A Wise Old Owl", "A-Tisket, A-Tasket"};
#Override
protected void onCreate(Bundle savedInstanceState) {
/** Hiding Title bar of this activity screen */
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
/** Making this activity, full screen */
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_poems);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, poems);
list = (ListView) findViewById(R.id.listView);
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
Intent myIntent = new Intent(Poems.this, test.class);
startActivity(myIntent);
break;
case 1:
//code specific to 2nd list item
Intent myIntent1 = new Intent(Poems.this, test.class);
startActivity(myIntent1);
break;
default:
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_poems, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Here is activity_poems layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:background="#drawable/bg"
tools:context="apps.panky.poemsnrhymes.Poems">
<ListView
android:id="#+id/listView"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginTop="47dp">
</ListView>
Here is Manifest file:
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".splash"
android:label="#string/title_activity_splash"
android:theme="#style/Theme.AppCompat.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/Theme.AppCompat.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".Poems"
android:label="#string/title_activity_poems"
android:theme="#style/Theme.AppCompat.NoActionBar" >
<intent-filter>
<action android:name="apps.panky.poemsnrhymes.POEMS" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".test"
android:label="#string/title_activity_test" >
</activity>
</application>
Try assigning yourself as the onItemClickListener with:
list.setAdapter(adapter);
list.setTextFilterEnabled(true);
list.setOnItemClickListener(this);
(The last line is the only addition)
Your onItemClick is never hit because you don't have a way to reach it without that call to setOnItemClickListener. You need to explicitly set yourself as the listener since you implement AdapterView.OnItemClickListener

Workflow XAML Custom Activity Parsing issue?

I've created a custom XAML Activity inherited from NativeActivity and IActivityTemplateFactory
The Designer shows the correct look and feel inside the Library I've defined.
However when I drop it on the Flow Surface of a workflow Console Application I don't see it rendered. The CPU pegs at 50% and if I run procmon.exe I see BUFFEROVERFLOW on the .XAML file and a NOT REPARSE error on the exe itself.
I do have the typeof Designer defined as the attribute of the class.
I've turned on Exceptions in the VS debug to see if an exception is being thrown but nothing ever comes out.
--CODE-- CS
[Designer(typeof(ITCRetryActivityDesigner))]
public sealed class ITCRetryActivity : NativeActivity, IActivityTemplateFactory
{
private static readonly TimeSpan DefaultRetryInterval = new TimeSpan(0, 0, 0, 1);
private readonly Variable<Int32> _attemptCount = new Variable<Int32>();
private readonly Variable<TimeSpan> _delayDuration = new Variable<TimeSpan>();
private readonly Delay _internalDelay;
public ITCRetryActivity()
{
_internalDelay = new Delay
{
Duration = new InArgument<TimeSpan>(_delayDuration)
};
Body = new ActivityAction();
MaxAttempts = 5;
ExceptionType = typeof(TimeoutException);
RetryInterval = DefaultRetryInterval;
}
[DebuggerNonUserCode]
public Activity Create(DependencyObject target)
{
return new ITCRetryActivity
{
Body =
{
Handler = new Sequence()
}
};
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
metadata.AddDelegate(Body);
metadata.AddImplementationChild(_internalDelay);
metadata.AddImplementationVariable(_attemptCount);
metadata.AddImplementationVariable(_delayDuration);
RuntimeArgument maxAttemptsArgument = new RuntimeArgument("MaxAttempts", typeof(Int32), ArgumentDirection.In, true);
RuntimeArgument retryIntervalArgument = new RuntimeArgument("RetryInterval", typeof(TimeSpan), ArgumentDirection.In, true);
metadata.Bind(MaxAttempts, maxAttemptsArgument);
metadata.Bind(RetryInterval, retryIntervalArgument);
Collection<RuntimeArgument> arguments = new Collection<RuntimeArgument>
{
maxAttemptsArgument,
retryIntervalArgument
};
metadata.SetArgumentsCollection(arguments);
ValidationError validationError;
if (Body == null)
{
validationError = new ValidationError("No Children are defined in this Retry Activity", true, "Body");
metadata.AddValidationError(validationError);
}
if (typeof (Exception).IsAssignableFrom(ExceptionType) != false) return;
validationError = new ValidationError("Exception type does not match", false, "ExceptionType");
metadata.AddValidationError(validationError);
}
protected override void Execute(NativeActivityContext context)
{
ExecuteAttempt(context);
}
private static Boolean ShouldRetryAction(Type exceptionType, Exception thrownException)
{
return exceptionType != null && exceptionType.IsInstanceOfType(thrownException);
}
private void ActionFailed(NativeActivityFaultContext faultcontext, Exception propagatedexception, ActivityInstance propagatedfrom)
{
Int32 currentAttemptCount = _attemptCount.Get(faultcontext);
currentAttemptCount++;
_attemptCount.Set(faultcontext, currentAttemptCount);
Int32 maxAttempts = MaxAttempts.Get(faultcontext);
if (currentAttemptCount >= maxAttempts)
{
// There are no further attempts to make
return;
}
if (ShouldRetryAction(ExceptionType, propagatedexception) == false)
{
return;
}
faultcontext.CancelChild(propagatedfrom);
faultcontext.HandleFault();
TimeSpan retryInterval = RetryInterval.Get(faultcontext);
if (retryInterval == TimeSpan.Zero)
{
ExecuteAttempt(faultcontext);
}
else
{
// We are going to wait before trying again
_delayDuration.Set(faultcontext, retryInterval);
faultcontext.ScheduleActivity(_internalDelay, DelayCompleted);
}
}
private void DelayCompleted(NativeActivityContext context, ActivityInstance completedinstance)
{
ExecuteAttempt(context);
}
private void ExecuteAttempt(NativeActivityContext context)
{
if (Body == null)
{
return;
}
context.ScheduleAction(Body, null, ActionFailed);
}
[Browsable(false)]
public ActivityAction Body
{
get;
set;
}
[DefaultValue(typeof(TimeoutException))]
public Type ExceptionType
{
get;
set;
}
public InArgument<Int32> MaxAttempts
{
get;
set;
}
public InArgument<TimeSpan> RetryInterval
{
get;
set;
}
}
}
--XAML--
<sap:ActivityDesigner x:Class="ITC.Common.Workflow.ITCRetryActivityDesigner"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:sap="clr-namespace:System.Activities.Presentation;assembly=System.Activities.Presentation"
xmlns:sapv="clr-namespace:System.Activities.Presentation.View;assembly=System.Activities.Presentation"
xmlns:conv="clr-namespace:System.Activities.Presentation.Converters;assembly=System.Activities.Presentation">
<sap:ActivityDesigner.Icon>
<DrawingBrush>
<DrawingBrush.Drawing>
<ImageDrawing>
<ImageDrawing.Rect>
<Rect Location="0,0"
Size="16,16">
</Rect>
</ImageDrawing.Rect>
<ImageDrawing.ImageSource>
<BitmapImage UriSource="d-metal-reload-arrows.jpg"></BitmapImage>
</ImageDrawing.ImageSource>
</ImageDrawing>
</DrawingBrush.Drawing>
</DrawingBrush>
</sap:ActivityDesigner.Icon>
<sap:ActivityDesigner.Resources>
<conv:ModelToObjectValueConverter x:Key="ModelItemConverter"
x:Uid="sadm:ModelToObjectValueConverter_1" />
<DataTemplate x:Key="Collapsed">
<TextBlock HorizontalAlignment="Center"
FontStyle="Italic"
Foreground="Gray">
Double-Click to View
</TextBlock>
</DataTemplate>
<DataTemplate x:Key="Expanded">
<StackPanel Orientation="Vertical">
<Grid Name="contentGrid">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<TextBlock Grid.Row="0"
Grid.Column="0"
HorizontalAlignment="Left"
VerticalAlignment="Center">
Exception Type:
</TextBlock>
<sapv:TypePresenter HorizontalAlignment="Left"
VerticalAlignment="Center"
Margin="6"
Grid.Row="0"
Grid.Column="1"
Filter="ExceptionTypeFilter"
AllowNull="false"
BrowseTypeDirectly="false"
Label="Exception Type"
Type="{Binding Path=ModelItem.ExceptionType, Mode=TwoWay, Converter={StaticResource ModelItemConverter}}"
Context="{Binding Context}" />
</Grid>
<sap:WorkflowItemPresenter Item="{Binding ModelItem.Body.Handler}"
HintText="Drop Activity"
Margin="6" />
</StackPanel>
</DataTemplate>
<Style x:Key="ExpandOrCollapsedStyle"
TargetType="{x:Type ContentPresenter}">
<Setter Property="ContentTemplate"
Value="{DynamicResource Collapsed}" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=ShowExpanded}"
Value="true">
<Setter Property="ContentTemplate"
Value="{DynamicResource Expanded}" />
</DataTrigger>
</Style.Triggers>
</Style>
</sap:ActivityDesigner.Resources>
<Grid>
<ContentPresenter Style="{DynamicResource ExpandOrCollapsedStyle}"
Content="{Binding}" Height="16" VerticalAlignment="Top" />
</Grid>
How can I debug this situation?
Thanks.
I resolved my issue by removing the Exception type as stated in comments and not having the icon graphic (using the default since it's not all that important.

Flex List displays key value pair from Web service

How to display a list of data in Flex by getting key value pair from a wsdl web service? Please help.
It depends on your web service and data types it provides.
Many web services can return you a response as a list of objects.
Others give you a structured string.
In my example I use a simple public weather web service, which returns its XML as a string.
This is a service description: http://www.webservicex.com/globalweather.asmx?wsdl
This is a test page: http://www.webservicex.com/globalweather.asmx?test
I use the GetCitiesByCountry method to get this list:
//source code
<?xml version="1.0" encoding="utf-8"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
minWidth="955" minHeight="600" creationComplete="init()">
<fx:Script>
<![CDATA[
import mx.controls.Alert;
import mx.rpc.CallResponder;
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
import services.globalweather.Globalweather;
private var ws:Globalweather = new Globalweather();
private var getCitiesByCountryCR:CallResponder;
private function init():void
{
getCitiesByCountryCR = new CallResponder();
getCitiesByCountryCR.addEventListener(ResultEvent.RESULT, onResult);
getCitiesByCountryCR.addEventListener(FaultEvent.FAULT, onFault);
}
private function onResult(evt:ResultEvent):void
{
var xml:XML = new XML(evt.result);
var xmlList:XMLList = xml.Table.City;
taCities.text = "";
for each (var item:XML in xmlList)
{
taCities.text += item.toString() + String.fromCharCode(13);
}
}
private function onFault(evt:FaultEvent):void
{
Alert.show("Fault!");
}
protected function getCities(event:MouseEvent):void
{
getCitiesByCountryCR.token = ws.GetCitiesByCountry(tiCountry.text);
}
]]>
</fx:Script>
<s:VGroup x="20" y="20" width="330" height="200">
<s:HGroup verticalAlign="bottom">
<s:Label text="Enter country name:"/>
<s:TextInput id="tiCountry" text="France"/>
<s:Button x="202" y="10" label="Get cities!" click="getCities(event)"/>
</s:HGroup>
<s:TextArea id="taCities" height="100%" width="100%"/>
</s:VGroup>
</s:Application>

JSF: Adding a String to List

I have an JSF 2.0 application that has a bean that holds a list of Strings.
I want to add the String from an <h:inputText>/> to my List and display my list.
The following code just put references in my List. So every element from my List is set to the last input.
#ManagedBean
#ApplicationScoped
public class Bean {
private String name;
private ArrayList<String> test = new ArrayList<String>();
public Bean() {
}
public Bean(String name) {
this.name = name;
}
public String addtoList(String _name){
test.add(_name);
return "./index.xhtml";
}
/***************GETTER/SETTER/HASHCODE/EQUALS**************************/
...
}
here a part of my index.xhtml:
<h:inputText id="name"
value="#{bean.name}"
required="true">
</h:inputText>
<h:commandButton value="Post"
action="#{bean.addtoList(name)}"/>
<br/>
<h:dataTable var="bean"
value="#{bean.test}">
<h:column>
<h:outputText value="#{bean.name}"/>
</h:column>
</h:dataTable>
Try this:
public String addtoList() { // no parameter
test.add(this.name); // add value of bean's property
return "./index.xhtml";
}
and in the facelet:
<h:commandButton
value="Post"
action="#{bean.addtoList}"/> <!-- no parameter passed -->
The point is to have the addToList method without parameters and the string you add to the list should be the value of the name property of the backing bean.
And also, in the datatable, do not name the var the same as the backing bean. It's confusing and potentially leads to bugs. Use something like this:
<h:dataTable
var="it"
value="#{bean.test}">
<h:column>
<h:outputText value="#{it}" />
</h:column>
</h:dataTable>
<h:dataTable var="beany"
value="#{bean.test}">
<h:column>
<h:outputText value="#{beany}"/>
</h:column>
</h:dataTable>
the prob was that var="bean" is the same name of my class bean
better should be another name for var

Grails g:select setting selectedIndex

How do you set the selectedIndex on a <g:select> tag with a value from the list? I have a page that allows you to add a record. the page then goes to a view containing a g:select and i want the g:select to default to that item i just inserted into the database.
I tried passing the new object in the flash but i can't figure out how to get it's index in the list being used to generate the g:select data.
Supposing you store a Book object in flash.book at the controller level, your second page could look like this :
<html>
<head>
<g:javascript library="prototype" />
<g:javascript>
function showLast(selectedId) {
if (selectedId) {
$$('#books option[value=' + selectedId + "]")[0].selected = true;
} else {
$('books').selectedIndex = 0;
}
};
Event.observe(window, 'load', init, false);
function init() {
showLast(${flash?.book?.id});
}
</g:javascript>
</head>
<body>
<g:select id="books" name="id"
from="${Book.list()}"
value="title"
optionValue="title"
optionKey="id"
/>
</body>
</html>