I am implementing recycler view in my Xamarin android application, But Items are not showing on debugging the application altough the InitData() Method is properly executed.
Here is the mainactivity.cs code in which recycler view is implemented:
using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace FinalProject_PU.Helper
{
class Data
{
public string IssueImage { get; set; }
public string UserImage { get; set; }
public string UserName { get; set; }
public DateTime IssueDate { get; set; }
public string IssueStatement { get; set; }
public int GetElevatedDates()
{
var ElevatedDays = (IssueDate.Date - DateTime.Now.Date).Days;
return ElevatedDays;
}
public string ElevatedDays
{
get { return ElevatedDays; }
set
{
if (GetElevatedDates() == 0)
{
ElevatedDays = "Today";
}
else
{
ElevatedDays = GetElevatedDates() + "Days";
}
}
}
}
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.Home);
byte[] arr = Convert.FromBase64String(UserInfoHolder.Profile_pic);
imgwriteIssue = (ImageView)FindViewById(Resource.Id.imgwriteIssue);
imgwriteIssue.Click += delegate
{
var i = new Intent(this, typeof(CreateIssue));
this.StartActivity(i);
};
CircleImageView img = FindViewById<CircleImageView>(Resource.Id.circleImageView1);
Android.Graphics.Bitmap bitmap = BitmapFactory.DecodeByteArray(arr, 0, arr.Length);
img.SetImageBitmap(bitmap);
iconfunds = (ImageView)FindViewById(Resource.Id.iconFunds);
iconfunds.Click += Iconfunds_Click;
notifications = (ImageView)FindViewById(Resource.Id.iconNotifications);
notifications.Click += Notifications_Click;
map = (ImageView)FindViewById(Resource.Id.iconMap);
map.Click += Map_Click;
setting = (ImageView)FindViewById(Resource.Id.iconSettings);
setting.Click += Setting_Click;
recycler = FindViewById<RecyclerView>(Resource.Id.recyclerView1);
recycler.HasFixedSize = true;
// layoutManager = new LinearLayoutManager(this);
layoutManager = new GridLayoutManager(this, 1, GridLayoutManager.Horizontal, false);
recycler.SetLayoutManager(layoutManager);
InitData();
adapter = new RecyclerViewAdapter(lstData);
recycler.SetAdapter(adapter);
}
private async void InitData()
{
lstData = await IssueController.FetchPostList();
}
fetchallpost() method fetch all the issues from data and return a list of it.
but it is not showing in recycler view and application is halting in a few seconds after opening Homeactivity.cs
Here is the recycler view adapter class on which my programs breaks automatially
RecyclerViewAdapter.cs
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using Refractored.Controls;
using System.Collections.Generic;
using System;
using Android.Content;
using AndroidX.Core.Graphics;
namespace FinalProject_PU.Helper
{
class RecyclerViewHolder : RecyclerView.ViewHolder
{
public ImageView imageview { get; set; }
public CircleImageView UserImage { get; set; }
public TextView UserName { get; set; }
public TextView IssueDate { get; set; }
public TextView IssueStatement { get; set; }
Android.Graphics.Typeface tf;
//
// public TextView Description { get; set; }
public RecyclerViewHolder(Android.Views.View itemView) : base(itemView)
{
imageview = itemView.FindViewById<ImageView>(Resource.Id.imageView1);
UserImage = itemView.FindViewById<CircleImageView>(Resource.Id.imgProfile);
UserName = itemView.FindViewById<TextView>(Resource.Id.tvname);
IssueDate = itemView.FindViewById<TextView>(Resource.Id.tvtime);
IssueStatement = itemView.FindViewById<TextView>(Resource.Id.tvinfo);
//beauttification
/*
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
IssueStatement.SetTypeface(tf, TypefaceStyle.Bold);
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
UserName.SetTypeface(tf, TypefaceStyle.Bold);
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
IssueDate.SetTypeface(tf, TypefaceStyle.Bold);
*/
}
}
class RecyclerViewAdapter : RecyclerView.Adapter
{
private List<Data> lstData = new List<Data>();
public RecyclerViewAdapter(List<Data> lstData)
{
this.lstData = lstData;
}
public override int ItemCount
{
get
{
return lstData.Count;
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
RecyclerViewHolder viewHolder = holder as RecyclerViewHolder;
byte[] arr0 = Convert.FromBase64String(lstData[position].IssueImage); //IssueImage
Bitmap b0 = BitmapFactory.DecodeByteArray(arr0, 0, arr0.Length);
viewHolder.imageview.SetImageBitmap(b0);
byte[] arr1 = Convert.FromBase64String(lstData[position].UserImage); //UserImage
Bitmap b1 = BitmapFactory.DecodeByteArray(arr1, 0, arr1.Length);
viewHolder.UserImage.SetImageBitmap(b1); //
viewHolder.UserName.Text = lstData[position].UserName;
viewHolder.IssueDate.Text = lstData[position].ElevatedDays;
viewHolder.IssueStatement.Text = lstData[position].IssueStatement;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
Android.Views.View itemView = inflater.Inflate(Resource.Layout.items, parent, false);
return new RecyclerViewHolder(itemView);
}
}
}```
I have tried debugging the application to see what is causing the problem and it was found out that application is breaking when it reaches on this line in recycler view constructor.
I have made sure that the fetchallpost() method is actually returning list with data.
imageview = itemView.FindViewById<ImageView>(Resource.Id.imageView1);
please help me with this
Related
I receive this error when trying to remove entries from the table with EFC
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: The database operation was expected to affect 1 row(s), but actually affected 30 row(s); data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding and handling optimistic concurrency exceptions.
This is my code:
https://paste.mod.gg/xlynuworjmmf/0
using MySqlConnector;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Conventions;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MySql.EntityFrameworkCore;
namespace Flanium_Agent
{
public class AgentContext : DbContext
{
public DbSet<Agent> agent { get; set; }
public DbSet<AgentRequest> agentRequest { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySQL("Server=localhost;User ID=root;Database=orchestration_db");
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
modelBuilder.Entity<Agent>().ToTable("agents");
modelBuilder.Entity<AgentRequest>().HasKey(a => a.Station);
modelBuilder.Entity<AgentRequest>().ToTable("agent_requests");
}
}
public class Agent
{
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
}
public class AgentRequest
{
public string Station { get; set; }
public string Request { get; set; }
}
public class Agency : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged = delegate { };
private bool ProcessRunning = false;
private List<string> RequestList = new List<string>();
public string Station { get; set; }
public string Process { get; set; }
public string Actions { get; set; }
public string Started { get; set; }
public string Finished { get; set; }
public string Status { get; set; }
public string Request { get; set; }
private Grid DisplayGrid { get; set; }
private Window appWindow { get; set; }
public Grid GetDisplayGrid()
{
return DisplayGrid;
}
public Agency InsertAgentToGrid(Window mainWindow)
{
DisplayGrid = new Grid();
var headerRowDefinition = new RowDefinition();
headerRowDefinition.Height = new GridLength(50);
DisplayGrid.RowDefinitions.Add(headerRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var property = GetType().GetProperties()[index];
var header = new TextBlock();
var column = new ColumnDefinition();
header.Text = property.Name;
header.HorizontalAlignment = HorizontalAlignment.Center;
header.VerticalAlignment = VerticalAlignment.Center;
header.FontSize = 16;
header.FontWeight = FontWeights.Medium;
Grid.SetRow(header, 0);
Grid.SetColumn(header, index);
DisplayGrid.ColumnDefinitions.Add(column);
DisplayGrid.Children.Add(header);
}
var contentRowDefinition = new RowDefinition();
contentRowDefinition.Height = GridLength.Auto;
DisplayGrid.RowDefinitions.Add(contentRowDefinition);
for (var index = 0; index < GetType().GetProperties().Length; index++)
{
var propertyValue = GetType().GetProperties()[index];
var content = new TextBlock();
content.HorizontalAlignment = HorizontalAlignment.Center;
content.VerticalAlignment = VerticalAlignment.Center;
content.FontSize = 12;
content.TextWrapping = TextWrapping.Wrap;
Grid.SetRow(content, 1);
Grid.SetColumn(content, index);
DisplayGrid.Children.Add(content);
var myBinding = new Binding(propertyValue.Name)
{
Source = this,
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
};
content.SetBinding(TextBlock.TextProperty, myBinding);
}
DisplayGrid.HorizontalAlignment = HorizontalAlignment.Stretch;
DisplayGrid.VerticalAlignment = VerticalAlignment.Top;
DisplayGrid.Margin = new Thickness(0, 25, 0, 0);
(mainWindow.Content as Grid).Children.Add(DisplayGrid);
appWindow = mainWindow;
return this;
}
private string[] GetPackages()
{
var packagesArray = new List<string>();
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathString = Path.Combine(desktopPath, "Flanium Agent Data");
var packageFolders = Directory.GetDirectories(pathString);
foreach (var packFolder in packageFolders)
{
var versions = Directory.GetDirectories(packFolder);
if (versions.Length != 0)
{
packagesArray.AddRange(versions.Select(version => version.Split('\\').Last())
.Select(versionName => packFolder.Split('\\').Last() + "\\" + versionName));
packagesArray = packagesArray.Select(x => x = pathString + "\\" + x).ToList();
}
}
return packagesArray.ToArray();
}
public Agency(string station, string process, string actions, string started, string finished, string status)
{
try
{
using (var context = new AgentContext())
{
context.agent.Add(new Agent
{Station = station, Process = process, Actions = actions, Started = started, Finished = finished, Status = status});
// Saves changes
context.SaveChanges();
}
Station = station;
Process = process;
Actions = actions;
Started = started;
Finished = finished;
Status = status;
}
catch (Exception e)
{
}
}
public void RemoveAgent()
{
using (var context = new AgentContext())
{
context.agent.Where(x=> x.Station == Station).ToList().ForEach(x=> context.agent.Remove(x));
// Saves changes
context.SaveChanges();
}
}
}
}
I followed a tutorial on the internet on how to use EFC by the teeth and for some euclidean reason, as always, the code works for others and the same code does not work when I try it out.
modelBuilder.Entity<Agent>().HasKey(a => a.Station);
So you have an entity Agent, about which you tell Entity Framework that it has a primary key column named "station".
You have a database with at least 30 records in it, and at least 30 of those records have the same value for the station column.
So despite you telling EF that station is the primary key, it isn't. So EF generates the query:
DELETE FROM agent WHERE station=#station
And the database engine happily removes all 30 records for which the station equals the station of the first record it encounters, and reports this, then EF throws, because it expected one record to be deleted, not 30.
The solution: configure the actual primary key as key, or if there isn't any, create one.
I am implementing recyclerview in my xamarin android application and it is working in a very weird way
first when I hardcode item(data) in list my application halts and when I put data into list using database it doesn't stop working but doeesn't show any view.
Here is my HomeActivity.cs Code
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your application here
SetContentView(Resource.Layout.Home);
InitData();
recycler = FindViewById<RecyclerView>(Resource.Id.recyclerView1);
recycler.HasFixedSize = true;
// layoutManager = new LinearLayoutManager(this);
layoutManager = new GridLayoutManager(this, 1, GridLayoutManager.Horizontal, false);
recycler.SetLayoutManager(layoutManager);
adapter = new RecyclerViewAdapter(lstData);
recycler.SetAdapter(adapter);
}
private void InitData()
{
//foreach (var item in await IssueController.FetchPostList())
//{
// lstData.Add(item);
//}
lstData.Add(new Data()
{
IssueImage = "base64stringofimage",
UserImage = "base64stringofimage",
IssueDate = DateTime.Now,
UserName = "asadullah",
IssueStatement = "some issue statement"
});
}
I tried debugging to be more specific what is causing in to halt and I realized that it is halting at the end of OnBindViewHolder() method in recyclerviewadapter class.
This is the RecyclerViewAdapter Class:
RecyclerViewAdapter.cs
using Android.Graphics;
using Android.Support.V7.Widget;
using Android.Views;
using Android.Widget;
using Refractored.Controls;
using System.Collections.Generic;
using System;
using Android.Content;
using AndroidX.Core.Graphics;
namespace FinalProject_PU.Helper
{
class RecyclerViewHolder : RecyclerView.ViewHolder
{
public ImageView imageview { get; set; }
public CircleImageView UserImage { get; set; }
public TextView UserName { get; set; }
public TextView IssueDate { get; set; }
public TextView IssueStatement { get; set; }
Android.Graphics.Typeface tf;
//
// public TextView Description { get; set; }
public RecyclerViewHolder(Android.Views.View itemView) : base(itemView)
{
imageview = itemView.FindViewById<ImageView>(Resource.Id.imageView1);
UserImage = itemView.FindViewById<CircleImageView>(Resource.Id.imgProfile);
UserName = itemView.FindViewById<TextView>(Resource.Id.tvname);
IssueDate = itemView.FindViewById<TextView>(Resource.Id.tvtime);
IssueStatement = itemView.FindViewById<TextView>(Resource.Id.tvinfo);
//beauttification
/*
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
IssueStatement.SetTypeface(tf, TypefaceStyle.Bold);
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
UserName.SetTypeface(tf, TypefaceStyle.Bold);
tf = Typeface.CreateFromAsset(Assets, "Quicksand-Bold.otf");
IssueDate.SetTypeface(tf, TypefaceStyle.Bold);
*/
}
}
class RecyclerViewAdapter : RecyclerView.Adapter
{
private List<Data> lstData = new List<Data>();
public RecyclerViewAdapter(List<Data> lstData)
{
this.lstData = lstData;
}
public override int ItemCount
{
get
{
return lstData.Count;
}
}
public override void OnBindViewHolder(RecyclerView.ViewHolder holder, int position)
{
RecyclerViewHolder viewHolder = holder as RecyclerViewHolder;
byte[] arr0 = Convert.FromBase64String(lstData[position].IssueImage); //IssueImage
Bitmap b0 = BitmapFactory.DecodeByteArray(arr0, 0, arr0.Length);
viewHolder.imageview.SetImageBitmap(b0);
byte[] arr1 = Convert.FromBase64String(lstData[position].UserImage); //UserImage
Bitmap b1 = BitmapFactory.DecodeByteArray(arr1, 0, arr1.Length);
viewHolder.UserImage.SetImageBitmap(b1); //
viewHolder.UserName.Text = lstData[position].UserName;
viewHolder.IssueDate.Text = lstData[position].ElevatedDays;
viewHolder.IssueStatement.Text = lstData[position].IssueStatement;
}
public override RecyclerView.ViewHolder OnCreateViewHolder(ViewGroup parent, int viewType)
{
LayoutInflater inflater = LayoutInflater.From(parent.Context);
Android.Views.View itemView = inflater.Inflate(Resource.Layout.items, parent, false);
return new RecyclerViewHolder(itemView);
}
}
}
so I am coding a desktop application for Mac OS using C# and Obj-c, but am struggling to get the text from an NSTextBox as a string.
This is the returned code from ViewController.Designer.Cs (the code returned to Visual Studio from Xcode after designing the interface.
using Foundation;
using System.CodeDom.Compiler;
using static System.Net.Mime.MediaTypeNames;
namespace ByteOrbitPrivacyCannonMacBuild
{
[Register("ViewController")]
partial class ViewController
{
[Outlet]
AppKit.NSImageView BackgroundImage { get; set; }
[Outlet]
AppKit.NSButton ClickButtonDecrypt { get; set; }
public static string dtime;
[Outlet]
public static AppKit.NSTextField DateCreated { get; set; }
[Outlet]
AppKit.NSButton Decrypt { get; set; }
[Outlet]
AppKit.NSButton Encrypt { get; set; }
[Outlet]
AppKit.NSTextField Message { get; set; }
[Action ("ClickDecrypt:")]
partial void ClickDecrypt (Foundation.NSObject sender);
[Action ("ClickEncrypt:")]
partial void ClickEncrypt (Foundation.NSObject sender);
[Action ("datecreated:")]
partial void datecreated (Foundation.NSObject sender);
[Action ("Okay:")]
partial void Okay (Foundation.NSObject sender);
void ReleaseDesignerOutlets ()
{
if (DateCreated != null) {
DateCreated.Dispose ();
DateCreated = null;
}
if (BackgroundImage != null) {
BackgroundImage.Dispose ();
BackgroundImage = null;
}
if (ClickButtonDecrypt != null) {
ClickButtonDecrypt.Dispose ();
ClickButtonDecrypt = null;
}
if (Decrypt != null) {
Decrypt.Dispose ();
Decrypt = null;
}
if (Encrypt != null) {
Encrypt.Dispose ();
Encrypt = null;
}
if (Message != null) {
Message.Dispose ();
Message = null;
}
}
}
}
And this the ViewController code.
The
public static AppKit.NSTextField DateCreated { get; set; }
Is the returned code for the NSTextBox called DateCreated, which I am attempting to get the text string from.
Here is the ViewController:
using System;
using System.IO;
using AppKit;
using Foundation;
using UserNotifications;
using static System.Net.Mime.MediaTypeNames;
namespace ByteOrbitPrivacyCannonMacBuild
{
public partial class ViewController : NSViewController
{
public ViewController(IntPtr handle) : base(handle)
{
}
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Do any additional setup after loading the view.
}
public override NSObject RepresentedObject
{
get
{
return base.RepresentedObject;
}
set
{
base.RepresentedObject = value;
// Update the view, if already loaded.
}
}
public static string ctime;
partial void ClickDecrypt(Foundation.NSObject sender)
{
string decrypt;
StreamReader sr = new StreamReader(#"/Users/bopc/encryptedmessagehere.txt");
string line = sr.ReadLine();
decrypt = Encryptor1.Decrypted(Convert.ToString(line));
Message.StringValue = line;
}
StreamReader sr = new StreamReader(#"encryptedmessagehere.txt");
public static string verify;
public static string verifytry;
partial void ClickEncrypt(Foundation.NSObject sender)
{
verify = DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss tt");
string enctxt = Encryptor1.Encrypt(Message + " Message Created at: " + verify);
string strPath = Environment.GetFolderPath(
System.Environment.SpecialFolder.DesktopDirectory);
System.IO.File.WriteAllText(#"/Users/bopc/encryptedmessagehere.txt", enctxt);
}
}
}
I am wondering where to put the NSString * = [DateCreated stringValue] in Obj-C? Everywhere I put it returns the error "stringValue does not exist in the current context". New to MacOS development. Thank you.
Edited code:
[Outlet]
public static AppKit.NSTextField DateCreated { get; set; }
unsafe
NSString* myStr = [DateCreated stringValue];
Added after advice:
[Outlet]
public AppKit.NSTextField DateCreated { get; private set; }
Console.WriteLine(DateCreated.StringValue)
When you use Xamarin you code it like so..
var textfield = new NSTextField(new CGRect(0, 0, 300, 100));
textfield.StringValue = "Hello World!";
//or
NSTextField textfield = new NSTextField();
textfield.BackgroundColor = NSColor.Clear;
textfield.Bordered = false;
textfield.Selectable = false;
textfield.Editable = false;
textfield.StringValue = NSString.Create("Hello World!")
and the other way around
NSString text = new NSString();
text = textfield.StringValue;
NSString text = null;
text = "Hello World!"
NSTextField textfield = new NSTextField();
textfield.StringValue = text;
//vs.
textfield.StringValue = NSString.Create(text);
spot the differences when NSString is used as setter and getter. And when C# string is involved.
I have try the following code to fire on activity result inside my atapter, when my button pressed without success. The activity TraEdit is starting correctly and updates my data. I can't refresh my list with NotifyDataSetChanged(), OnActivityResult never fires to control the result.
What i am doing wrong? Is there a way to NotifyDataSetChanged() inside my adapter or i have to try a different approach?
Any help appreciated.
using System.Collections.Generic;
using Android.App;
using Android.Content;
using Android.Views;
using Android.Widget;
namespace Cashier
{
[Activity(Label = "TraBaseAdapter")]
public partial class TraBaseAdapter : BaseAdapter<TraTable>
{
List<TraTable> TraListArrayList;
private LayoutInflater mInflater;
private Context activity;
public TraBaseAdapter(Context context, List<TraTable> results)
{
activity = context;
TraListArrayList = results;
mInflater = (LayoutInflater)activity.GetSystemService(Context.LayoutInflaterService);
}
public override int Count { get { return TraListArrayList.Count; } }
public override long GetItemId(int position) { return position; }
public override TraTable this[int position] { get { return TraListArrayList[position]; } }
public override View GetView(int position, View convertView, ViewGroup parent)
{
TraViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.Inflate(Resource.Layout.TraRecord_view, null);
holder = new TraViewHolder
{
TxtBtnEdit = convertView.FindViewById<Button>(Resource.Id.TraEditButtonHolder),
TxtTraName = convertView.FindViewById<TextView>(Resource.Id.TraNameHolder),
TxtTraCode = convertView.FindViewById<TextView>(Resource.Id.TraCodeHolder)
};
if (!holder.TxtBtnEdit.HasOnClickListeners)
{
holder.TxtBtnEdit.Click += (sender, e) =>
{
TraEditClick(holder);
};
}
convertView.Tag = holder;
}
else { holder = convertView.Tag as TraViewHolder; }
holder.LineId = position;
holder.TraId = TraListArrayList[position].Cs_Traid;
holder.TxtBtnEdit.Tag = holder.LineId + 1;
holder.TxtTraName.Text = TraListArrayList[position].Cs_Name;
holder.TxtTraCode.Text = TraListArrayList[position].Cs_Code;
return convertView;
}
private void TraEditClick(TraViewHolder LineHolder)
{
Intent ActivityAddEditTra = new Intent(this.activity, typeof(TraEdit));
ActivityAddEditTra.PutExtra("TraIdSel", TraListArrayList[LineHolder.LineId].Cs_Traid);
ActivityAddEditTra.PutExtra("NameSel", TraListArrayList[LineHolder.LineId].Cs_Name);
ActivityAddEditTra.PutExtra("TraCodeSel", TraListArrayList[LineHolder.LineId].Cs_Code);
((Activity)activity).StartActivityForResult(ActivityAddEditTra, 99);
}
public void OnActivityResult(int RequestCode, Result ResultCode, Intent Data)
{
if (ResultCode == Result.Ok & RequestCode == 99)
{
int RowUpdate = Data.GetIntExtra("RowUpdate", 0);
NotifyDataSetChanged();
Toast.MakeText(activity, "Data changes :" + RowUpdate.ToString(), ToastLength.Short).Show();
}
}
public class TraViewHolder : Java.Lang.Object
{
public TextView TxtTraCode { get; set; }
public TextView TxtTraName { get; set; }
public Button TxtBtnEdit { get; set; }
public int LineId { get; set; }
public int TraId { get; set; }
}
}
}
In TraEdit:
......
Intent RetunData = new Intent();
SetResult(Result.Ok, RetunData);
RetunData.PutExtra("RowUpdate", RowsUpd);
......
Maybe
RetunData.PutExtra("RowUpdate", RowsUpd);
should come before
SetResult(Result.Ok, RetunData);
Im not good with VS but maybe the OnActivityResult method must be in the Activity not in the adapater
I have written out some commands for my interface within my viewmodel for my Xamarin Forms project. I need to access these commands on my buttons so that they perform a task however I'm not sure how to do that.
My ViewModel
TheDemo/ViewModel/MenupageViewModel.cs
using System;
using System.Windows.Input;
using Xamarin.Forms;
namespace TheDemo
{
public class MenuPageViewModel
{
public ICommand GoDashboardCommand { get; set; }
public ICommand GoRequirementsCommand { get; set; }
public ICommand GoFixturesCommand { get; set; }
public ICommand GoVesselsCommand { get; set; }
public ICommand GoDutyBrokerCommand { get; set; }
public ICommand GoSettingsCommand { get; set; }
public ICommand GoInfoCommand { get; set; }
public MenuPageViewModel()
{
GoDashboardCommand = new Command(GoDashboard);
GoRequirementsCommand = new Command(GoRequirements);
GoFixturesCommand = new Command(GoFixtures);
GoVesselsCommand = new Command(GoVessels);
GoDutyBrokerCommand = new Command(GoBroker);
GoSettingsCommand = new Command(GoSettings);
GoInfoCommand = new Command(GoInfo);
}
void GoDashboard(object obj) {
App.NavigationPage.Navigation.PopToRootAsync();
App.MenuIsPresented = false;
}
void GoRequirements(object obj) {
App.NavigationPage.Navigation.PushAsync(new Requirements());
App.MenuIsPresented = false;
}
void GoFixtures(object obj) {
App.NavigationPage.Navigation.PushAsync(new Fixtures());
App.MenuIsPresented = false;
}
void GoVessels(object obj) {
App.NavigationPage.Navigation.PushAsync(new Vessels());
App.MenuIsPresented = false;
}
void GoBroker(object obj) {
App.NavigationPage.Navigation.PushAsync(new Duty());
App.MenuIsPresented = false;
}
void GoSettings(object obj) {
App.NavigationPage.Navigation.PushAsync(new Settings());
App.MenuIsPresented = false;
}
void GoInfo(object obj) {
App.NavigationPage.Navigation.PushAsync(new Information());
App.MenuIsPresented = false;
}
}
}
Menu
TheDemo/Menupage.cs
using System;
using System.Collections.Generic;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.Xamarin.Forms;
using System.Windows.Input;
using Xamarin.Forms;
namespace TheDemo
{
public partial class MenuPage : ContentPage
{
public MenuPage()
{
InitializeComponent();
BindingContext = new MenuPageViewModel();
Grid grid = new Grid();
grid.Children.Add(
new Button {
Text = "Requirements",
BackgroundColor = Color.Orange,
TextColor = Color.White,
Command = //How do I access my commands in my viewmmodel?
}, 0, 1);
}
}
}
You should set your Button in a variable and then bind it via SetBinding.
Example code:
var ButtonHolder = new Button {
Text = "Requirements",
BackgroundColor = Color.Orange,
TextColor = Color.White
};
ButtonHolder.SetBinding (Button.CommandProperty, "GoDashboardCommand");
grid.Children.Add(ButtonHolder, 0, 1);
First of all, map the view model to the view. To do that, add the following line to the ContentPage tag of your view in XAML like this.
The line to add
xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo"
Example
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:viewModels="clr-namespace:TheDemo.ViewModels; assembly=TheDemo">
Then add this snippet inside the content page tag
<ContentPage.BindingContext>
<viewModels:MenuPageViewModel/>
</ContentPage.BindingContext>
Then add the button and use the command property, like this
<Button Command="{Binding GoInfoCommand}"/>
Update the assembly and namespace according to your application. Hope this solved your issue.