I am trying to display an list in an listview in Visual Studio that was first serialized and then deserialized. Everything works fine but my problem is that the list is displayed in an very weird format you can see it in the picture below.
Heres my code so far:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
KalenderClass k1 = new KalenderClass();
k1.termin = TerminTextbox.Text;
k1.datum = DatePicker1.Date;
k1.person = PersonTextbox.Text;
kList.Add(k1);
SaveData(kList);
}
private async void SaveData(List<KalenderClass> kList)
{
StorageFolder ordner = ApplicationData.Current.LocalFolder;
StorageFile datei = await ordner.CreateFileAsync("Kalender.txt", CreationCollisionOption.OpenIfExists);
await FileIO.WriteTextAsync(datei, JsonConvert.SerializeObject(kList));
showDialog("Daten wurden in Datei geschrieben");
}
private async void ReadButton_Click(object sender, RoutedEventArgs e)
{
StorageFolder ordner = Windows.Storage.ApplicationData.Current.LocalFolder;
string path = ordner.Path;
StorageFile datei = await ordner.GetFileAsync("Kalender.txt");
string inhalt = await FileIO.ReadTextAsync(datei);
var k = JsonConvert.DeserializeObject(inhalt);
TerminListview.Items.Add(k);
}
I dont want to add the whole List k to the listview but just the new object.
And here is the way it is displayed:
I want it to be a format, for example:
Termin 1:
Date:
Person:
I hope you guys can help me
Change CreationCollisionOption from:
CreationCollisionOption.OpenIfExists
To:
CreationCollisionOption.ReplaceExisting
Or you can refresh the list inside the SaveButton_Click method as the following:
private void SaveButton_Click(object sender, RoutedEventArgs e)
{
kList = new List<KalenderClass>(); // <== This line will reset the list
KalenderClass k1 = new KalenderClass();
k1.termin = TerminTextbox.Text;
k1.datum = DatePicker1.Date;
k1.person = PersonTextbox.Text;
kList.Add(k1);
SaveData(kList);
}
Related
I have managed to pick an image from the phones library and display it. this is the code. Question is how do i Insert this image into my Sqlite database of contacts and retrieve it and display it again after getting the image? Here is my code. A detailed step by step instruction would be appreciated from here.
namespace Mobile_Life.Pages
{
public sealed partial class NextOFKin_Update_Delete : Page
{
int Selected_ContactId = 0;
DatabaseHelperClass Db_Helper = new DatabaseHelperClass();
Contacts currentcontact = new Contacts();
CoreApplicationView view;
public NextOFKin_Update_Delete()
{
this.InitializeComponent();
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
view = CoreApplication.GetCurrentView();
}
private void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
if (Frame.CanGoBack)
{
e.Handled = true;
Frame.GoBack();
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await StatusBar.GetForCurrentView().ShowAsync();
Selected_ContactId = int.Parse(e.Parameter.ToString());
currentcontact = Db_Helper.ReadContact(Selected_ContactId);//Read selected DB contact
namestxt.Text = currentcontact.Name;//get contact Name
relationtxt.Text = currentcontact.Relation;//get contact relation
phonetxt.Text = currentcontact.PhoneNumber;//get contact PhoneNumber
}
private void Update_click(object sender, RoutedEventArgs e)
{
currentcontact.Name = namestxt.Text;
currentcontact.Relation = relationtxt.Text;
currentcontact.PhoneNumber = phonetxt.Text;
Db_Helper.UpdateContact(currentcontact);//Update selected DB contact Id
Frame.Navigate(typeof(NextOfKin));
}
private void Delete_click(object sender, RoutedEventArgs e)
{
Db_Helper.DeleteContact(Selected_ContactId);//Delete selected DB contact Id.
Frame.Navigate(typeof(NextOfKin));
}
private void profile_img(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(FileAccessMode.Read);
var bitmapImage = new BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
profile.ImageSource = bitmapImage;
}
}
}
The best way would be NOT to store the image in SQLite. Just copy it to your ApplicationData.Current.LocalFolder and save the path.
If you really want to store the BitmapImage in SQLite, just convert it to byte array: Convert a bitmapimage to byte[] array for storage in sqlite database
I have 2 list views and I'm trying to drag an item from one to the other.
The typeof item is a storagefile.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items;
files.Add(file);
e.Data.SetStorageItems(files);
}
private void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
//if (e.DataView.Contains(StandardDataFormats.StorageItems))
//{
// var items = await e.DataView.GetStorageItemsAsync();
// if (items.Count > 0)
// {
// var storageFile = items[0] as StorageFile;
// ListC.Items.Add(storageFile);
// }
// }
}
I've tried everything I can think of to drop the storage file into the other listview and show the display name... All I've been able to display are types and stuff.
Can anyone help me?
I've solved it after hours or trying.
private async void ListA_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
//f.MessageBox(e.Items.First().GetType().ToString());
try
{
List<IStorageItem> files = new List<IStorageItem>();
StorageFile file = e.Items.First() as StorageFile;
files.Add(file);
e.Data.SetStorageItems(files);
//e.Data.SetData(StandardDataFormats.Text, e.Items.);
}catch(Exception ex)
{
f.MessageBox(ex.Message);
}
}
private async void ListC_DragEnter(object sender, DragEventArgs e)
{
e.AcceptedOperation = DataPackageOperation.Copy;
//IReadOnlyList<IStorageItem> files = await e.DataView.GetStorageItemsAsync();
}
private async void ListC_Drop(object sender, DragEventArgs e)
{
try
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
var storageFile = items[0] as StorageFile;
ListC.Items.Add(storageFile.Name);
}
}
}catch
{
f.MessageBox("nope");
}
I have a small doubt about using SQLite database and local settings. I have an idea about how to use local settings for an app. When we use Application data(local settings) in our application we can restore the previous state of the application. Can we use sqlite local database to store and retrieve the values while we use local settings.
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
if (data.Values["check"] != null)
{
this.Frame.Navigate(typeof(BlankPage1));
}
if (data.Values["add"] != null)
{
list_view.Items.Add(data.Values["add"].ToString());
}
if (data.Values["remove"] != null)
{
list_view.Items.Remove(data.Values["remove"]);
}
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
await con.CreateTableAsync<list>();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
if(!mypop.IsOpen)
{
mypop.IsOpen = true;
}
}
public async void Button_Click_1(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
list l = new list();
data.Values["add"] = l.list1;
l.list1 = text_input.Text.ToString();
await con.InsertAsync(l);
await con.UpdateAllAsync(l.list1);
data.Values["add"] = l.list1;
list_view.Items.Add(data.Values["add"].ToString());
mypop.IsOpen = false;
}
private void Button_Click_2(object sender, RoutedEventArgs e)
{
if(mypop.IsOpen)
{
mypop.IsOpen = false;
}
}
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
var dbpath = ApplicationData.Current.LocalFolder.Path + "/Mydb1.db";
var con = new SQLiteAsyncConnection(dbpath);
list l = new list();
data.Values["remove"] = l.list1;
l.list1 = list_view.SelectedItem.ToString();
list_view.Items.Remove(list_view.SelectedItem);
List<list> mylist = await con.QueryAsync<list>("delete from list where list1='" + list_view.SelectedItem + "'");
mylist.Remove(l);
Please check and verify the code. I can only store single value to local settings. When I restart my application only one value will be shown. It wont show the values inserted in the listview. Please also check delete query. It is not working.. please help me...
I am trying to import music files from your pc to make your own playlist.
code below:
public async void Button_Click(object sender, RoutedEventArgs e) // Pick directory
{
var openPicker = new Windows.Storage.Pickers.FileOpenPicker();
openPicker.FileTypeFilter.Add(".wmv");
openPicker.FileTypeFilter.Add(".mp4");
openPicker.FileTypeFilter.Add(".wma");
openPicker.FileTypeFilter.Add(".mp3");
var file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
// media is a MediaElement defined in XAML
if (null != file)
{
media.SetSource(stream, file.ContentType);
media.Play();
}
}
private async void Button_Click_1(object sender, RoutedEventArgs e) //Import file
{
this.Frame.Navigate(typeof(importedfile));
importedfile import = new importedfile(); // The imported file goes to that page.
//What do I do to get the imported file into a new grid (Picture below
}
For example: I Import a song and I hit the import button it will navigate me to the importedfile page but what do I do next?.
Newbie question here. I have this file picker:
public async void PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
StorageFile file = await ImagePicker.PickSingleFileAsync(); //
...
}
And I want to use the file set by this image picker in another method. Something like this:
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
... the one from PickImage()
v
StorageFile copyImage = await file.CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
It is obviously not working like this. How can I do it?
Ok, based on the answers I got, this is what I came up with:
public async Task<StorageFile> PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
ImagePicker.FileTypeFilter.Add(".jpg");
ImagePicker.FileTypeFilter.Add(".jpeg");
ImagePicker.FileTypeFilter.Add(".png");
ImagePicker.ViewMode = PickerViewMode.Thumbnail;
ImagePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
StorageFile file = await ImagePicker.PickSingleFileAsync();
if (file != null)
{
IRandomAccessStream imageStream = await file.OpenAsync(FileAccessMode.Read);
var bmpImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
bmpImage.DecodePixelHeight = 150;
bmpImage.DecodePixelWidth = 310;
bmpImage.SetSource(imageStream);
ImagePreview.Source = bmpImage;
}
return file;
}
////
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
...
string DateTimeNow = DateTime.Now.ToString("HHmmssddMMyyyy");
StorageFolder docs = KnownFolders.DocumentsLibrary;
StorageFolder myDir = await docs.CreateFolderAsync("My Dir", Windows.Storage.CreationCollisionOption.OpenIfExists);
StorageFolder DateTimeFolder = await myDir.CreateFolderAsync(DateTimeNow);
//StorageFile image = await PickImage();
StorageFile copyImage = await PickImage().CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
But the last line gives me an error:
'System.Threading.Tasks.Task' does not contain a definition for 'CopyAsync' and no extension method 'CopyAsync' accepting a first argument of type 'System.Threading.Tasks.Task' could be found (are you missing a using directive or an assembly reference?)
You need to either set a field in the class or return the StorageFile. I would suggest changing PickImage() to return the StorageFile so you're code would instead look like this;
public async StorageFile PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
return await ImagePicker.PickSingleFileAsync(); //
...
}
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
StorageFile pickedFile = await PickImage();
StorageFile copyImage = await file.CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
Or something to that effect. I'm slightly confused by the second line in your CreateButton_Click method because I thought you wanted to operate on the file from PickImage but instead you're creating a new file. If you want the StorageFile to persist just make it a field on the form class and set it in PickImage
As pointed by Andre in the comments, your PickImage should return the file, so you could do the following:
public async StorageFile PickImage()
{
FileOpenPicker ImagePicker = new FileOpenPicker();
...
StorageFile file = await ImagePicker.PickSingleFileAsync(); //
...
return file;
}
private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
...
StorageFile copyImage = await this.PickImage().CopyAsync(DateTimeFolder, "image", NameCollisionOption.ReplaceExisting);
...
}
Depending on the location of the two methods, there are two solutions:
If the methods are located in the same class file, you can declare StorageFile file as a local variable in the class file. In that way, you can reach it from the CreateButton_click function
If cross threading is involved (methods are working in separate threads), you need to use delegates and invoke them. Detailed information is available here through an example.