Get value from selected item - xamarin.android

I would like to get value from selected item in list. How can I do it?
private List<string> selected = new List<string>();`
var list = this.FindViewById<ListView>(Resource.Id.listOne);
adapterData = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1);
list.Adapter = adapterData;

By default, when you click on a ListView item it doesn't change its state to "selected". So, when the event fires and you do:
list.SelectedItem;
The method doesn't have anything to return. What you have to do is to use the position and obtain the underlying object by doing:
list.GetItemAtPosition(position);
UPDATE
Get you listView item click like below:
mListView.ItemClick += MListView_ItemClick;
And in your MainListView_ItemClick you will get your position as an integer when you do e.Position
Goodluck!

You just need listen the item click event,and then get the Value by its position.
For example:
private List<string> selected = new List<string>();
private ListView listView;
listView = FindViewById<ListView>(Resource.Id.listOne);
selected.Add("AAA");
selected.Add("BBB");
selected.Add("CCC");
selected.Add("DDD");
var adapterData = new ArrayAdapter<string>(this,Android.Resource.Layout.SimpleListItem1,selected);
listView.Adapter = adapterData;
listView.ItemClick += ListView_ItemClick;
private void ListView_ItemClick(object sender, AdapterView.ItemClickEventArgs e)
{
string s = (string)listView.GetItemAtPosition(e.Position);//here you could get the value
Toast.MakeText(this, s, ToastLength.Short).Show();
}

Related

How to add radio button to radio group in Xamarin for Android via code behind?

The title already describes what I want to do: I'm working with Xamarin for Android. Now I'd like to have a RadioGroup and fill it with RadioButtons via code behind and not via XAML. How can I do this? I don't find any setter...
Why do I need this? My small Android app has a Load button which loads entries from a web service. Each entry should be represented by a RadioButton so that the user has a flexible selection.
Here's an example I put together for you that creates the Radio Group and Radio Buttons dynamically along with how to determine which button is selected by the user at run-time.
protected override void OnCreate(Bundle savedInstanceState) {
base.OnCreate(savedInstanceState);
var layout = new LinearLayout(this) {
Orientation = Orientation.Vertical
};
// Create Radio Group
var rg = new RadioGroup(this);
layout.AddView(rg);
// Add Radio Buttons to Radio Group
for (int i = 1; i < 6; i++) {
var rb = new RadioButton(this) { Text = $"Radio Button {i}" };
rg.AddView(rb);
}
// Show Radio Button Selected
lblOutput = new TextView(this);
layout.AddView(lblOutput);
rg.CheckedChange += (s, e) => {
lblOutput.Text = $"Radio Button {e.CheckedId} Selected";
};
SetContentView(layout);
}
Output
As an alternative, I've implemented a solution using a ListView:
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.activity_main);
var toolbar = FindViewById<Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);
Speakers = new List<ISpeaker>();
FindViewById<Button>(Resource.Id.loadButton).Click += LoadButtonOnClick;
}
private async void LoadButtonOnClick(object sender, EventArgs e)
{
Speakers = await LoadSpeakersAsync();
var sourceListView = FindViewById<ListView>(Resource.Id.sourceListView);
sourceListView.Adapter = new ArrayAdapter<ISpeaker>(this, Android.Resource.Layout.SimpleListItem1, Speakers);
}

How to select an item from a List in flutter

I have list from a model like this
amount:"12000"
dateTime:"19/07/2018"
detail:"Soto"
hashCode:853818549
id:1
name:"Theodorus"
I want to just select amount and add it to another list of string, but I'm always getting this error A value of type 'String' can't be assigned to a variable of type 'List<String>'. , I thinks its because im not doing it right, here is my code below
void setupList() async {
DebtDatabase db = DebtDatabase();
listCache = await db.getMyDebt();
setState(() {
filtered = listCache;
});
List<String> amount = new List<String>();
listCache.map((value) {
amount = value.amount; } );
//print(amount);
}
can anyone help me, so I can get list of ammount from this model list and then sum all the ammount?
The map function returns an iterable and you can then transform it into a list.
You should try something like this:
void setupList() async {
DebtDatabase db = DebtDatabase();
listCache = await db.getMyDebt();
setState(() {
filtered = listCache;
});
List<String> amount = listCache.map((value) => value.amount).toList();
//print(amount);
}

Observing an object containing a list of observables?

I am using the observe package.
Consider this example:
class Product extends Object with ChangeNotifier {
double _price = 0.0;
#reflectable double get price => _price;
#reflectable void set price(double value) {
if (value == null) throw new ArgumentError();
_price = notifyPropertyChange(#price, price, value);
}
}
class Order extends Object with ChangeNotifier {
final ObservableList<Product> products = new ObservableList<Product>();
double get total {
double sum = 0.0;
for (var item in products) {
sum += item.price;
}
return sum;
}
}
// Synchronizes the view total with the order total.
// Or rather, I'd like it to do that.
var order = new Order();
order.changes.listen((records) {
view.total = order.total;
});
How would I rewrite this example to make it work?
I would like to be notified of any changes to the object's state, even if they happen to the list or the items of the list.
Do I have to manage change subscriptions to all items and the list itself? Inside or outside of the Order class? Through which property would I notify the change? It seems messy either way.
The elements in the ObservableList do not propagate the notification to the list that contains them. They can't because they have no reference to the list.
Also the list does not forward the notifications to the class it is referenced by.
Not really satisfying but the best I could come up with.
import 'dart:async' as async;
import 'package:observe/observe.dart';
class Product extends Object with ChangeNotifier {
double _price = 0.0;
#reflectable double get price => _price;
#reflectable void set price(double value) {
if (value == null) throw new ArgumentError();
_price = notifyPropertyChange(#price, price, value);
}
#override
String toString() => 'Product - price: $price';
}
class Order extends Object with ChangeNotifier {
final ObservableList<Product> products = new ObservableList<Product>();
// keep listeners to be able to cancel them
final List<async.StreamSubscription> subscriptions = [];
Order() {
products.changes.listen((cr) {
// only react to length changes (isEmpty, isNotempty changes are redundant)
var lengthChanges = cr.where((c) => c.name == #length);
if(lengthChanges.isNotEmpty) {
lengthChanges.forEach((lc) =>
notifyChange(lc));
// we can't know if only additions/removals were done therefore we
// cancel all existing listeners and set up new ones for all items
// after each length change
_updateProductsListeners();
}
});
// initial setup
_updateProductsListeners();
}
// cancel all product change listeners and create new ones
void _updateProductsListeners() {
print('updateListeners');
subscriptions.forEach((s) => s.cancel());
subscriptions.clear();
products.forEach((p)
=> subscriptions.add(p.changes.listen((crs) =>
crs.forEach((cr) =>
notifyPropertyChange(cr.name, cr.oldValue, cr.newValue)))));
}
double get total {
double sum = 0.0;
for (var item in products) {
sum += item.price;
}
return sum;
}
}
void main() {
// Synchronizes the view total with the order total.
// Or rather, I'd like it to do that.
var order = new Order();
order.changes.listen((records) {
//view.total = order.total;
records.forEach(print);
});
// a PathObserver example but it doesn't seem to be more convenient
var op = new PathObserver(order, 'products[3].price')..open((c) =>
print(c));
var prods = [new Product()..price = 1.0, new Product()..price = 2.0, new Product()..price = 3.0, new Product()..price= 4.0];
var prods2 = [new Product()..price = 5.0, new Product()..price = 6.0];
order.products.addAll(prods);
// use Future to allow change notification propagate between changes
new async.Future(() =>
order.products..addAll(prods2)..removeWhere((p) => p.price < 3.0))
.then((_) => new async.Future(() => order.products[3].price = 7.0));
new async.Future.delayed(new Duration(seconds: 1), () => print('done'));
}
I suggest to use something like an event bus for this where the objects that want/should to notify about something just send and event and objects that are interested in something listen for that without any knowledge of where the other object exists.
For example https://pub.dartlang.org/packages/event_bus
Another solution is to use the ListPathObserver. The class is deprecated but you can copy his code and reuse it. With that class you can listen for specific changes in the contained items. The field to watch is specified by path.

Monotouch.Dialog Generate from db and retain values

I'm have a settings view where I'm using MT.D to build out my UI. I just got it to read elements from a database to populate the elements in a section.
What I don't know how to do is access each elements properties or values. I want to style the element with a different background color for each item based on it's value in the database. I also want to be able to get the selected value so that I can update it in the db. Here's the rendering of the code that does the UI stuff with MT.D. I can get the values to show up and slide out like their supposed to... but, styling or adding delegates to them to handle clicks I'm lost.
List<StyledStringElement> clientTypes = SettingsController.GetClientTypes ();
public SettingsiPhoneView () : base (new RootElement("Home"), true)
{
Root = new RootElement("Settings") {
new Section ("Types") {
new RootElement ("Types") {
new Section ("Client Types") {
from ct in clientTypes
select (Element) ct
}
},
new StringElement ("Other Types")
}
Here's how I handled it below. Basically you have to create the element in a foreach loop and then populate the delegate with whatever you want to do there. Like so:
public static List<StyledStringElement> GetClientTypesAsElement ()
{
List<ClientType> clientTypes = new List<ClientType> ();
List<StyledStringElement> ctStringElements = new List<StyledStringElement> ();
using (var db = new SQLite.SQLiteConnection(Database.db)) {
var query = db.Table<ClientType> ().Where (ct => ct.IsActive == true && ct.Description != "Default");
foreach (ClientType ct in query)
clientTypes.Add (ct);
}
foreach (ClientType ct in clientTypes) {
// Build RGB values from the hex stored in the db (Hex example : #0E40BF)
UIColor bgColor = UIColor.Clear.FromHexString(ct.Color, 1.0f);
var localRef = ct;
StyledStringElement element = new StyledStringElement(ct.Type, delegate {
ClientTypeView.EditClientTypeView(localRef.Type, localRef.ClientTypeId);
});
element.BackgroundColor = bgColor;
ctStringElements.Add (element);
}
return ctStringElements;
}

smartgwt - listgrid editing by cell having some problem

I made listgid which can be edited by cell.
For testing I added save button. When I click on save button then listgrid's first record(updated first column value on first row) should be appear on pop up, but its not showing updated value on pop up.
For example in this case there is first listgrid record name->jon, i edited jon to shobhit and then click on save button. After clicking on save button I should get name shobhit but its showing jon which is the old value.
Please have a look on below my code and help me to accomplish this interesting task.
public void onModuleLoad() {
VLayout vLayout = new VLayout(10);
final ListGrid listGrid = new ListGrid();
ListGridField nameField = new ListGridField("name","Name");
nameField.setWidth(100);
nameField.setAlign(Alignment.CENTER);
ListGridField ageField = new ListGridField("age","Age");
ageField.setWidth(100);
ageField.setAlign(Alignment.CENTER);
ListGridField locationField = new ListGridField("location","Location");
locationField.setWidth(100);
locationField.setAlign(Alignment.CENTER);
listGrid.setFields(nameField, ageField, locationField);
listGrid.setDataSource(getDS());
listGrid.setWidth(310);
listGrid.setHeight(224);
listGrid.setAutoFetchData(true);
listGrid.setCanEdit(true);
listGrid.setEditEvent(ListGridEditEvent.CLICK);
listGrid.setEditByCell(true);
vLayout.addMember(listGrid);
IButton saveButton = new IButton("Save");
saveButton.addClickHandler(new ClickHandler() {
#Override
public void onClick(ClickEvent event) {
ListGridRecord[] record = listGrid.getRecords();
Record r = record[0];
SC.say(r.getAttributeAsString("name"));
}
});
vLayout.addMember(saveButton);
RootPanel.get("gwtContent").add(vLayout);
}
private RestDataSource getDS() {
RestDataSource ds = new RestDataSource();
DataSourceTextField nameField=new DataSourceTextField("name", "Name");
DataSourceIntegerField ageField=new DataSourceIntegerField("age", "Age");
DataSourceTextField locationField=new DataSourceTextField("location", "Location");
ds.setFields(nameField, ageField, locationField);
ds.setDataFormat(DSDataFormat.JSON);
OperationBinding fetchOB = new OperationBinding();
fetchOB.setOperationType(DSOperationType.FETCH);
OperationBinding addOB = new OperationBinding();
addOB.setOperationType(DSOperationType.ADD);
addOB.setDataProtocol(DSProtocol.POSTPARAMS);
OperationBinding updateOB = new OperationBinding();
updateOB.setOperationType(DSOperationType.UPDATE);
updateOB.setDataProtocol(DSProtocol.POSTPARAMS);
OperationBinding removeOB = new OperationBinding();
removeOB.setOperationType(DSOperationType.REMOVE);
removeOB.setDataProtocol(DSProtocol.POSTPARAMS);
ds.setOperationBindings(fetchOB, addOB, updateOB, removeOB);
if (!GWT.isScript()){
ds.setFetchDataURL("data/dataIntegration/json/data-fetch.js");
ds.setJsonRecordXPath("response/data");
}else{
}
return ds;
}
JSON data file:
{
response: {
status: 0,
startRow: 0,
endRow: 4,
totalRows: 5,
data: [
{"name":"Jon", "age":40, "location":"USA"},
{"name":"Tom", "age":30, "location":"USA"},
{"name":"Frank", "age":35, "location":"USA"},
{"name":"Deb", "age":24, "location":"USA"},
{"name":"Leroy", "age":70, "location":"USA"}
]
}
}
Use the addRowEditorExitHandler for listgrid.This will not require a save button.
Once you make changes and click any where outside grid, control will automatically come to addRowEditorExitHandler.
ListGrid listGrid = new ListGrid();
listGrid.setCanEdit(true);
listGrid.setAutoSaveEdits(false);
listGrid.setDataSource(getDS());
listGrid.addRowEditorExitHandler(new RowEditorExitHandler() {
#Override
public void onRowEditorExit(final RowEditorExitEvent event) {
SC.say(event.getNewValues().get("name"));
//event.getNewValues gives a map of unsaved edits in edited row
//This values u can put to a new record and save it
}
});

Resources