This is a xamarin application for android to compress or extract a given file entered by user in the textbox. I placed the sample file in the assets folder. The function zip on button click is supposed to compress the file On entering the filename and clicking the button it is throwing a filenotfound exception even after providing path of the file located.
namespace zipfile
{
[Activity (Label = "zipfile", MainLauncher = true)]
public class MainActivity : Activity
{
string t;
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button> (Resource.Id.button1);
button1.Click += delegate {
EditText text = FindViewById<EditText>
(Resource.Id.editText2);
if (null == text)
return;
t="\\zip\\zipfile\\Assets\\"+ text.Text;
//Toast.MakeText(this,"file
zipped",ToastLength.Long).Show();
ZipOutputStream.Zip(t, t, 128);
};
Button button2 = FindViewById<Button> (Resource.Id.button2);
button2.Click += delegate {
//Toast.MakeText(this,"file
unzipped",ToastLength.Long).Show();
ZipInputStream.UnZip (t, t, 128);
};
}
}
}
I am new To Xamarin Please suggest me way to handle this exception.
You can't write to paths inside of the APK.
A simple file IO example:
string path = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string filePath = Path.Combine(path, "file.txt");
using (var file = File.Open(filePath, FileMode.Create, FileAccess.Write))
using (var strm = new StreamWriter(file))
{
strm.Write(data);
}
Related
This app needs to play audio/video/ssml(xml) files using dispatcherTimer and TimePicker to choose when the file is played using the MediaElement Control.
Using FilePicker, the MediaElement plays files fine that are located Inside the project's Assets directory. But when I pick a file outside the project's directory,
like "C:\Users\Flazz\Music\AV\PlayLibray\Audio\Filename1.mp3" it does not do anything.
I tried the Add linked file, but option does no exist in VS 2017. Supposedly the VisualStudios team is aware they need to look into this oversight. Still, there has to be a simple solution.
Maybe my path is wrong so here is the code:
public UC_Mood()
{
this.InitializeComponent();
PickAFileButton.Click += new RoutedEventHandler(PickAFileButton_Click);
PickAFileButton2.Click += new RoutedEventHandler(PickAFileButton2_Click);
PickAFileButton3.Click += new RoutedEventHandler(PickAFileButton3_Click);
PickAFileButton4.Click += new RoutedEventHandler(PickAFileButton4_Click);
}
const string ENV_PROJ_PATH = "ms-appx:///Assets/AV/PlayLibray/Audio/";
const string ENV_CENTRAL_PATH = #"C:\Users\Flazz\Music\AV\PlayLibray\Audio\";
Click event handler with FileOpenPicker code:
private async void PickAFileButton_Click(object sender, RoutedEventArgs e)
{
// Clear previous returned file name, if it exists, between iterations of this scenario
tbFilePicked.Text = "";
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.MusicLibrary;
openPicker.FileTypeFilter.Add(".mp3");
openPicker.FileTypeFilter.Add(".m4a");
openPicker.FileTypeFilter.Add(".m4v");
openPicker.FileTypeFilter.Add(".avi");
openPicker.FileTypeFilter.Add(".wav");
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".xml");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
// Application now has read/write access to the picked file
tbFilePicked.Text = file.Name;
Debug.WriteLine(ENV_CENTRAL_PATH + tbFilePicked.Text);
}
else
{
tbFilePicked.Text = "Operation cancelled.";
}
}
Timer_Tick with MediaElement where any file path that is outside the Projects path does not play:
*note - Path that is declared above const string ENV_CENTRAL_PATH = #"C:\Users\Flazz\Music\AV\PlayLibray\Audio\";
private void timer_Tick(object sender, object e)
{
CountDown--;
txtCountDown.Text = CountDown.ToString();
if ((CountDown <= 0))
{
CountDown = 0;
try
{
MediaTool.Source = new Uri(ENV_CENTRAL_PATH + tbFilePicked.Text);
// MediaTool.Source = new Uri(ENV_PROJ_PATH + tbFilePicked.Text);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message.ToString());
}
MediaTool.Volume = 100;
MediaTool.Play();
timer.Stop();
}
}
I am using FileSystemWatcher to get the latest image from my Assets folder, i have a webcam to capture the image and save it in the Assets folder. After saving the image i get the latest image from FileSystemWatcher event.
Here is my code :
//FileWatcher
private void FileWatcher()
{
path = #"..\..\Assets\WebCamImage\";
System.IO.FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Changed += watcher_Changed;
watcher.EnableRaisingEvents = true;
}
//Event
void watcher_Changed(object sender, FileSystemEventArgs e)
{
CustomerImage.Dispatcher.Invoke(System.Windows.Threading.DispatcherPriority.Normal,
new Action(
delegate()
{
CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);
}
));
}
At page load event the source of CustomerImage control is set to a default picture which is nopictureavail.jpeg, when a changes made in that particular Directory the image should populate in CustomerImage, filewatcher event fires then the error throws at
CustomerImage.Source = (ImageSource)isc.ConvertFromString(e.FullPath);
NullReferenceException Occured in presentationCore.dll
Try to add this:
bitmap.CreateOption = BitmapCreateOptions.IgnoreImageCache
Here's some more
https://stackoverflow.com/a/1689808/2609288
You're getting this error because WPF holds on to the handle from its images. Try using this code instead:
BitmapImage image = new BitmapImage();
try
{
using (FileStream stream = File.OpenRead(filePath))
{
image.BeginInit();
image.StreamSource = stream;
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();
}
}
catch { return DependencyProperty.UnsetValue; }
I have this code in an IValueConverter to avoid a similar problem.
MainActivity.cs
namespace testApp
{
[Activity (Label = "DHS HotKeys", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Get our button from the layout resource,
// and attach an event to it
Button button1 = FindViewById<Button> (Resource.Id.button1);
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
var uri = Android.Net.Uri.Parse ("https://www.fridayparentportal.com/delran/");
var intent = new Intent (Intent.ActionView, uri);
StartActivity (intent);
};
button1.Click += (object sender, EventArgs e) => {
var uri2 = Android.Net.Uri.Parse ("http://dhs.delranschools.org/students/lunch_menu/");
var intent2 = new Intent (Intent.ActionView, uri2);
StartActivity (intent2);
};
}
}
}
Inside the resource designer:
public partial class Id
{
// aapt resource value: 0x7f050001
public const int button1 = 2131034113;
// aapt resource value: 0x7f050000
public const int myButton = 2131034112;
The 2nd button is set exactly like the first, but it does nothing when clicked, while the first one opens the webpage. The ID for 2nd button is #+id/button1
Thank you
write each button closer to their eventhandler, like this :
Button btn1 = FindViewById<Button>(Resource.Id.button1);
btn.Click += (object se,EventArgs e)
{
}
I am building an app where user can select which Language he wants to set when the app starts. A pop up will show "Select your Language" with two buttons one for Arabic and the other one for English.
The problem is that when I change the locale and execute this line
SetContentView (Resource.Layout.Main);
the app broke. there is no error or any exception but all controls stop capturing the events. I tried to declare an Intent using this and this.Class and when I call StartActivity it is like restarting the whole app and the pop comes again to select the language. I am new to android development as I spent my last two years working on SAP Abap so I might ask a stupid question :D
here is my code
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace Khums
{
[Activity (Label = "Khums", MainLauncher = true, Icon = "#drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
int r = Resource.Layout.Main;
SetContentView (Resource.Layout.Main);
var languageIso = "ar-SA";
AlertDialog.Builder alert = new AlertDialog.Builder (this);
//alert.SetTitle ("Selected Language");
AlertDialog alertDiaog = alert.Create ();
alertDiaog.SetTitle ("Select Language:");
alertDiaog.SetButton ("العربية", (s, EventArgs) => {
languageIso = "ar-SA";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
//base.SetContentView(r);
//Intent intent = new Intent(this, this.Class);
//StartActivity(intent);
SetContentView (Resource.Layout.Main);
});
alertDiaog.SetButton2 ("English", (s, EventArgs) => {
languageIso = "en-US";
var locale = new Java.Util.Locale(languageIso);
Java.Util.Locale.Default = locale;
var config = new Android.Content.Res.Configuration{Locale = locale };
BaseContext.Resources.UpdateConfiguration(config, BaseContext.Resources.DisplayMetrics);
SetContentView (Resource.Layout.Main);
});
alertDiaog.Show();
Button button = FindViewById<Button> (Resource.Id.myButton);
RadioButton rb_FirstTime = FindViewById<RadioButton> (Resource.Id.radioButton1);
RadioButton rb_Regular = FindViewById<RadioButton> (Resource.Id.radioButton2);
EditText ti_lyearBalance = FindViewById<EditText> (Resource.Id.ti_lastBalance);
EditText ti_Balance = FindViewById<EditText> (Resource.Id.ti_Balance);
EditText ti_Clothes = FindViewById<EditText> (Resource.Id.ti_Clothes);
EditText ti_Food = FindViewById<EditText> (Resource.Id.ti_Food);
EditText ti_Perfumes = FindViewById<EditText> (Resource.Id.ti_Perfumes);
EditText ti_Subscriptions = FindViewById<EditText> (Resource.Id.ti_Subscriptions);
EditText ti_Others = FindViewById<EditText> (Resource.Id.ti_Others);
TextView lbl_lyearBalance = FindViewById<TextView> (Resource.Id.lbl_lastBalance);
rb_FirstTime.Click += RadioButtonHandler;
rb_Regular.Click += RadioButtonHandler;
button.Click += MyButtoHandler;
}
private void RadioButtonHandler(object sender, EventArgs e)
{
}
private void MyButtoHandler(object sender, EventArgs e)
{
}
private double calculateKhumus (double[] amounts, Boolean isRegular)
{
}
private void LangSwitchHndler(Object sender, EventArgs e)
{
}
}
}
can you please show me what I'm doing wrong here. I tried to use togglebutton instead of alert and also standard button but ends up with the same issue. Thank you.
It is solved after trying for two days. All I did is to create a menu and change the target framework to Android 3.1 Honeycomb. Then I just start the activity and everything is working fine.
So the issue was only target framework!
I am trying to save a string to SharedPerferences like this:
Write
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var prefEditor = prefs.Edit ();
prefEditor.PutString ("SecurityToken", SecurityCode.Text);
prefEditor.Commit ();
Read
var prefs = Application.Context.GetSharedPreferences ("Janssen", FileCreationMode.WorldReadable);
var SecurityToken = prefs.GetString ("SecurityToken", null);
I am new to Android coming from iOS. I am trying to emulate NSUserDefaults in iOS. I am reading the SharedPreferences in a new activity, maybe that is what causes the problem? I am not sure. I also have no idea what to set as default value.
Are you re-deploying between writing your SharedPreferences and reading them? This often wipes the SharedPreferences.
I have just tested them and they work fine between two Activities:
WritePrefsAcitivity.cs
using Android.App;
using Android.Content;
using Android.Widget;
using Android.OS;
namespace Derrrp
{
[Activity (Label = "Derrrp", MainLauncher = true)]
public class WritePrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Write);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
var prefsEditor = prefs.Edit();
var ed = FindViewById<EditText>(Resource.Id.editText1);
ed.AfterTextChanged += (sender, e) => {
prefsEditor.PutString("MyPref", e.Editable.ToString());
prefsEditor.Commit();
};
Button button = FindViewById<Button> (Resource.Id.myButton);
button.Click += delegate {
var intent = new Intent(this, typeof(ReadPrefsActivity));
StartActivity(intent);
};
}
}
}
ReadPrefsActivity.cs
using Android.App;
using Android.Content;
using Android.OS;
using Android.Widget;
namespace Derrrp
{
[Activity (Label = "ReadPrefsActivity")]
public class ReadPrefsActivity : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView(Resource.Layout.Read);
var tv = FindViewById<TextView>(Resource.Id.myTextView);
var button = FindViewById<Button>(Resource.Id.myButton);
var prefs = Application.Context.GetSharedPreferences("MySharedPrefs", FileCreationMode.Private);
button.Click += (sender, e) => {
tv.Text = prefs.GetString("MyPref", "");
};
}
}
}
The defValue can be set to anything you want. This is the value that will be chosen if the preference you are trying to get is empty.
NOTE: If you are using it to store some secret information it is advised to use FileCreationMode.Private and even use something that makes it only readable by the application, such as encryption.
I am not sure what is the error you have, but below is an example i used before for saving a string using shared preferences.
I used to set default value to "", so that while reading, if the value was not saved before, it will set the variable to empty string. You can read the shared preferences in any new activity , shared preferences is per application not activity ..
example:
writing string:
String pass = "abcdefg";
SharedPreferences preferences = getSharedPreferences("pref", 0);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("savedPass", pass);
editor.commit();
reading string:
SharedPreferences preferences = getSharedPreferences("pref", 0);
String mypassword = preferences.getString("savedPass", "");