How to delete root element from xml file using csharp for wp - C, C++, C# and Other Windows Phone Development

This the structure of my xml file
<?xml version="1.0" encoding="utf-8" ?>
<itemList>
<Item>
<Name></Name>
<Method></Method>
<Item>
</itemList>
I just entered some data into xml file through
var isoFileStream = new IsolatedStorageFileStream("itemList.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, store);
XDocument myData = XDocument.Load(isoFileStream);
var data = from query in myData.Descendants("Item")
select new itemList
{
TitleName = (string)query.Element("Name"),
LinkName = (string)query.Element("Method"),
};
lstShow.ItemsSource = data;
isoFileStream.Close();
Now i want to remove an element from an xml file dynamically,i just tried with
var isoFileStream = new IsolatedStorageFileStream("itemList.xml", FileMode.OpenOrCreate, FileAccess.ReadWrite, store);
XDocument xDoc = XDocument.Load(isoFileStream);
/* xDoc.Descendants("Item")
.Where(x => (string)x.Element("Name") == data.TitleName).Remove(); //How to remove the element from the xml
xDoc.Save(isoFileStream); */
isoFileStream.Close();
I couldn't figure the solution,need help.Thanqs in advance

Normally, you remove the element from its parent.
Also, stackoverflow is always great for programming questions.
This one answers your questions: http:stackoverflow.com/a/8382902/586754
(Not allowed to post links yet.)

Related

[REQ]How to retrive the Storage Card name

Hi all,
Does anyone know how to retrive (identify) the system name of the Storage Card using .Net C.F. and Visual Basic language?
This is because often changig the WM version or the localization of the device, can also change the name of the Storage Card (with related "Path not found" error in the program).
Thanks for help
using C#.net
Code:
private static string GetStorageCardPath()
{
DirectoryInfo di = new DirectoryInfo(@"\");
FileSystemInfo[] fsi = di.GetFileSystemInfos();
foreach (FileSystemInfo fileSystemInfo in fsi)
{
if ((fileSystemInfo.Attributes & FileAttributes.Temporary) == FileAttributes.Temporary)
{
return fileSystemInfo.FullName;
}
}
return null;
}
and with convert csharp to vb in VB.net
Code:
Private Shared Function GetStorageCardPath() As String
Dim di As New DirectoryInfo("\")
Dim fsi As FileSystemInfo() = di.GetFileSystemInfos()
For Each fileSystemInfo As FileSystemInfo In fsi
If (fileSystemInfo.Attributes And FileAttributes.Temporary) = FileAttributes.Temporary Then
Return fileSystemInfo.FullName
End If
Next
Return Nothing
End Function
Thanks HeliosDev!

[Code]C# - App.Config reader

I just want to share my code for reading app.config file. I wrote it earlier for my current project - JWMD Stuick.
I just want it simple and clean and my/an alternative of (I never used it though) OpenNETCF.Configuration.
here's the code
PHP:
using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.XPath;
using System.IO;
namespace ApplicationConfiguration
{
public class Configuration
{
XmlDocument xmldoc;
string _applicationname = string.Empty;
string _appconfigfile = string.Empty;
Dictionary<string, string> _appSettings = new Dictionary<string, string>();
public Dictionary<string, string> AppSettings
{
get { return _appSettings; }
}
public Configuration()
{
string startup = System.Reflection.Assembly.GetCallingAssembly().GetName().CodeBase;
FileInfo fi = new FileInfo(startup);
this._applicationname = System.IO.Path.GetFileNameWithoutExtension(startup);
this._appconfigfile = System.IO.Path.Combine(fi.DirectoryName.ToString(), _applicationname + ".exe.config");
Read();
}
void Read()
{
xmldoc = new XmlDocument();
xmldoc.Load(this._appconfigfile);
XmlNodeList nodeCol = xmldoc.SelectNodes("//add");
if (nodeCol != null)
{
foreach (XmlNode thisNode in nodeCol)
{
string key = thisNode.Attributes["key"].Value.ToString();
string value = thisNode.Attributes["value"].Value.ToString();
this._appSettings.Add(key, value);
System.Diagnostics.Debug.WriteLine(key + ", " + value);
}
}
}
}
}
to make this work, make sure app config file is named the way Windows Forms rename the app.config.
e.g. your application name is "mysuperapplication" then the app config file must be "mysuperapplication.exe.config"
below is a application test.

[Q] Writing in an XML File Problem

Hey Guys!
I'm sitting in front of an XML-Problem for five days now and really don't know what's to do. Expect of asking you.
I want to write a small shopping list application that manages the data in an XML-File looking like that:
Code:
<?xml version="1.0" encoding="utf-8" ?>
<Items>
<Item>
<Name>Bananas</Name>
<Store>supermarket</Store>
<Repeat>true</Repeat>
</Item>
<Item>
<Name>LG E900 Optimus 7</Name>
<Store>superhandy</Store>
<Repeat>false</Repeat>
</Item>
(...)
I have a ListBox called ItemShowcase that I fill with instances of my ShowCaseEntry-Class
Reading Data from the FIle works perfectly with this code:
Code:
private void updateItemList()
{
// load XML-File
var items = XElement.Load("MissingItems.xml");
foreach (var a in items.Elements())
{
ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
ItemShowcase.Items.Add(sce);
}
}
No Problem until here.
But now I want to add a new Iem to my XML-File.
I have 2 Textfields in what I ask for the Item-Name and Store-Name. Repeat is always true.
I tried that:
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
// XML-Datei Laden
var items = XDocument.Load("MissingItems.xml");
// neues Item erstellen
XElement newItem = new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat) );
// Hinzufügen und spreichern
items.Root.Add(newItem);
FileStream F = new FileStream("MissingItems.xml", FileMode.Open);
items.Save(F);
}
The last line give me the following Error:
Attempt to access the method failed: System.IO.FileStream..ctor(System.String, System.IO.FileMode)
Is anyone here who would help me?
You would save my weekend!
Thank you so much!
Best wishes and greets
Robby
Try something like this:
Code:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
xml.Save(isoStream);
isoStream.Close();
First of all thanks for your answer.
Unfortunately I don't really know how to add the XML-Items.
Like this?
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
var items = XDocument.Load("MissingItems.xml");
XElement newItem = new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat));
items.Root.Add(newItem);
items.Save(isoStream);
isoStream.Close();
}
Another answer would be very nice
Best regards
Robby
I don't have time to test it but hopefully this works for you.
Code:
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
//Add your xml items here.
XDocument items = XDocument.Load(isoStream);
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat)));
items.Save(isoStream);
isoStream.Close();
}
Thank you really much for your engangement, but there is still one problem.
In this line the program throws an XML-Error called "root element is missing":
XDocument items = XDocument.Load(isoStream);
How to explain the Load-Method that "Items" is my root Element?
Greets
Robby
Sorry my code had errors. This is tested and working.
Code:
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument items = XDocument.Load(isoStream);
isoStream.Close();
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat.ToString())));
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
items.Save(isoStream);
isoStream.Close();
That code results in this:
Code:
<?xml version="1.0" encoding="utf-8"?>
<Items>
<Item>
<Name>Bananas</Name>
<Store>supermarket</Store>
<Repeat>true</Repeat>
</Item>
<Item>
<Name>LG E900 Optimus 7</Name>
<Store>superhandy</Store>
<Repeat>false</Repeat>
</Item>
<Item>
<Name>Test Name</Name>
<Store>Test Store</Store>
<Repeat>False</Repeat>
</Item>
</Items>
I really, really thank you for your anxiety. Thank you for your time, but I just have one more error.
This line throwes an Isolated Storage Exception called "Operation not permitted on IsolatedStorageFileStream.":
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
You would save my week with a short answer!
Thank you so much till yet
Robby
It sounds like the file stream is already open somewhere else. If you are doing any other reads or writes to the file prior to your addxmlitem method you need to close the stream before calling addxmlitem.
Not really
Sorry, I am sure that I'm annoying but I really need to fix that problem.
My last try to solve ist is to send you the full code:
Code:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;
using System.Xml;
using System.Text;
using System.IO;
using System.IO.IsolatedStorage;
namespace MyShoppingList
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
Item[] itemArray = new Item[2];
CheckBox[] checkBoxArray = new CheckBox[2];
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
updateItemList();
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
/// <summary>
/// Adds new Item to the XML-File
/// </summary>
/// <param name="name">Itemname</param>
/// <param name="store">Storename</param>
/// <param name="repeat">Repeat</param>
public void addXMLItem(String name, String store, Boolean repeat)
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument items = XDocument.Load(isoStream);
isoStream.Close();
items.Element("Items").Add(
new XElement("Item",
new XElement("Name", name),
new XElement("Store", store),
new XElement("Repeat", repeat.ToString())));
isoStream = new IsolatedStorageFileStream("MissingItems.xml", FileMode.Create, FileAccess.Write, isoStore);
items.Save(isoStream);
isoStream.Close();
}
/// <summary>
/// Updates Item List
/// </summary>
private void updateItemList()
{
// XML-Datei Laden
var items = XElement.Load("MissingItems.xml");
foreach (var a in items.Elements())
{
ShowCaseEntry sce = new ShowCaseEntry(a.Element("Name").Value, "Store: " + a.Element("Store").Value, false);
ItemShowcase.Items.Add(sce);
}
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
private void btnAdd_Click(object sender, RoutedEventArgs e)
{
addXMLItem(tBoxAddItemName.Text, tBoxAddItemStore.Text, false);
//updateItemList();
}
}
}
Can you find any mistakes?
I'm getting desperate...
Thanks a lot for your engagement!
I'n not really sure why that's happening. The only thing I can think of is XElement.Load() is causing the problem so here's how to use XDocument.Load() instead. I really hope this works for you because I'm out of ideas.
Code:
private void updateItemList()
{
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
var items = from c in xml.Elements("Items").Elements("Item")
select new {
name = c.Element("Name").Value,
store = c.Element("Store").Value,
repeat = c.Element("Repeat").Value
};
foreach (var item in items)
{
ShowCaseEntry sce = new ShowCaseEntry(item.name, "Store: " + item.store, false);
ItemShowcase.Items.Add(sce);
}
isoStream.Close();
}
Same Error on this line:
isoStream = new IsolatedStorageFileStream("MissingItems.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
Operation not permitted on IsolatedStorageFileStream.
I'm at the end of my motivation
I really tried everything, you really tried everything and I cannot find anything helpful to this error message..
Does anyone has an idea?
Does this line works for you?
Big Thanks to Ren13B till yet!
Attached is my working test project. Maybe it will help you.
If you are accessing the Isolated Storage from within a referenced assembly, you will need to access the IsolatedStorageFile for that assembly
Thanks for your reply but how to do that?

[Q] WP7 - Removing an XElement from an XML file

Hi there,
I'm having a big issue, when trying to remove an XElement from an XML file created in IsolatedStorage.
--------------------------------------------------------------------------------------------
Code to CREATE the XML file
Dim File_to_Create As String = "Tracks.xml"
Dim file As XDocument = <?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlnsd="urn:schemas-microsoft-comfficedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Cartridges.xsd" generated="2010-11-23T14:26:55">
<Carts>
<CART_NAME>First</CART_NAME>
<CART_COLOR>White</CART_COLOR>
</Carts>
<Carts>
<CART_NAME>Second</CART_NAME>
<CART_COLOR>Black</CART_COLOR>
</Carts>
</dataroot>
Dim isoStore As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication()
Try
If isoStore.FileExists(File_to_Create) Then
MessageBox.Show(File_to_Create + " TRUE")
Else
MessageBox.Show(File_to_Create + " FALSE")
Dim oStream As New IsolatedStorageFileStream(File_to_Create, FileMode.Create, isoStore)
Dim writer As New StreamWriter(oStream)
writer.WriteLine(file)
writer.Close()
MessageBox.Show("OK")
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
Finally
'open selected file
Dim isoStream As IsolatedStorageFileStream
isoStream = New IsolatedStorageFileStream(File_to_Create, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore)
Dim XML_File As XDocument = XDocument.Load(isoStream)
Dim Cart_Query As System.Collections.IEnumerable = From query In XML_File.Descendants("Carts") Order By _
CStr(query.Element("CART_NAME")) Descending, CStr(query.Element("CART_NAME"))
Select New Class_Cartridge_Data With {.Cart_Name = CStr(query.Element("CART_NAME")), _
.Cart_Color = CStr(query.Element("CART_COLOR"))}
Me.ListBox_Cartridges.ItemsSource = Cart_Query
isoStore.Dispose()
isoStream.Close()
End Try
--------------------------------------------------------------------------------------------
Code to ADD / EDIT XElement
Dim File_to_Create As String = "Tracks.xml"
Dim XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication()
' Check that the file exists if not create it
If Not (XML_IsolatedStorage.FileExists(File_to_Create)) Then
Return
End If
Dim XML_StreamReader As New StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read))
Dim XML_Document As XDocument = XDocument.Parse(XML_StreamReader.ReadToEnd())
XML_StreamReader.Close()
' Update the element if it exist or create it if it doesn't
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c) c.Element("CART_NAME").Value.Equals("First")).FirstOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' Add new
Dim newProgress As New XElement("Cartridges", New XElement("CART_NAME", "Fourth"), New XElement("CART_COLOR", "Blue"))
Dim rootNode As XElement = XML_Document.Root
rootNode.Add(newProgress)
End If
Using XML_StreamWriter As New StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write))
XML_StreamWriter.Write(XML_Document.ToString())
XML_StreamWriter.Close()
End Using
--------------------------------------------------------------------------------------------
Now my issue and request for some help!
If I use
XML_XElement.Remove
then the following exception is raised whenever I try to "refresh" the bounded ListBox
System.Xml.XmlException was unhandled
LineNumber=37
LinePosition=12
Message=Data at the root level is invalid. Line 37, position 12.
SourceUri=""
StackTrace:
at System.Xml.XmlTextReaderImpl.Throw(Exception e)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString, String[] args)
at System.Xml.XmlTextReaderImpl.Throw(Int32 res, String resString)
at System.Xml.XmlTextReaderImpl.ParseRootLevelWhitespace()
at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r)
at System.Xml.Linq.XContainer.ReadContentFrom(XmlReader r, LoadOptions o)
at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream, LoadOptions options)
at System.Xml.Linq.XDocument.Load(Stream stream)
at ListBox_Data_from_XML_LINQ.MainPage.Button_Create_XML_Click(Object sender, RoutedEventArgs e)
at System.Windows.Controls.Primitives.ButtonBase.OnClick()
at System.Windows.Controls.Button.OnClick()
at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)
at System.Windows.Controls.Control.OnMouseLeftButtonUp(Control ctrl, EventArgs e)
at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName)
InnerException:
--------------------------------------------------------------------------------------------
In short, I can add or edit, but cannot DELETE an XElement...
Any ideas?
Thanks in advance!
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Ren13B said:
Can you post the code you are using for XElement.Remove and use code tags so the formatting is right. Its the # button on the post toolbar.
Click to expand...
Click to collapse
Well, I did nothing special, just the XML_Element.remove, instead of adding a new xelement.
Then the error raises whenever I try to reopen the XML file.
My point is, how can I delete an specific xelement?
As far as I know, the following code should work
Code:
Dim XML_XElement As XElement = XML_Document.Descendants("Carts").Where(Function(c ) c.Element("CART_NAME").Value.Equals("First")).Firs tOrDefault()
If XML_XElement IsNot Nothing Then
XML_XElement.SetElementValue("CART_NAME", "Third")
Else
' remove the selected record
XML_XElement.Remove
End If
Honestly I don't know if the foregoing code is correct or if the issue is related to how WP7 handles the removal thus corrupting the original file.
Please let me know if you need anything else.
Any help is very appreciated!
PS: Thanks for the other replies, helped a lot!
Here's how I did it in c#. My xml file is very different than yours so the query will be different but the important parts are where you load and close the file streams and then write.
Code:
//Get users private store info
IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();
IsolatedStorageFileStream isoStream;
//open selected file
isoStream = new IsolatedStorageFileStream(list, System.IO.FileMode.Open, System.IO.FileAccess.Read, isoStore);
XDocument xml = XDocument.Load(isoStream);
isoStream.Close();
//Find section
XElement sectionElement = xml.Descendants("section").Where(c => c.Attribute("name").Value.Equals(groupn)).FirstOrDefault();
//Find item and remove it
sectionElement.Elements("setting").Where(c => c.Attribute("name").Value.Equals(litem)).FirstOrDefault().Remove();
isoStream.Close(); //Seems unnecessary but it's needed.
//Write xml file
isoStream = new IsolatedStorageFileStream(list, FileMode.Create, FileAccess.Write, isoStore);
xml.Save(isoStream);
isoStream.Close();
Thanks again for your help, greatly appreciated.
However I'm still getting the same error.
Sorry for asking, but are you getting any errors when deleting in WP7 ?
My knowledge on XML is extremely new and I'm sure that I'm making some mistakes somewhere...
But so far, I cannot get past the same exception.
Seems that the XML gots "corrupted" after the delete operation.
On the other hand, if is not too much to ask for, using my current code, how will handle the delete of the selected record?
Thanks!
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Problem is my country is not listed so I cannot register...
Here is the C# version of my current code for adding/editing
Code:
public static void ADD_XML_Record()
{
string File_to_Create = "Tracks.xml";
var XML_IsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
// Check that the file exists if not create it
if (! (XML_IsolatedStorage.FileExists(File_to_Create)))
{
return;
}
StreamReader XML_StreamReader = new StreamReader(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Read));
XDocument XML_Document = XDocument.Parse(XML_StreamReader.ReadToEnd());
XML_StreamReader.Close();
// Update the element if it exist or create it if it doesn't
XElement XML_XElement = XML_Document.Descendants("Carts").Where((c) => c.Element["CART_NAME"].Value.Equals("dd")).FirstOrDefault();
if (XML_XElement != null)
{
XML_XElement.SetElementValue("CART_NAME", "bbbbb");
}
else
{
// Add new
XElement newProgress = new XElement("Carts", new XElement("CART_NAME", "dd"), new XElement("CART_COLOR", "ff"));
XElement rootNode = XML_Document.Root;
rootNode.Add(newProgress);
}
using (StreamWriter XML_StreamWriter = new StreamWriter(XML_IsolatedStorage.OpenFile(File_to_Create, FileMode.Open, FileAccess.Write)))
{
XML_StreamWriter.Write(XML_Document.ToString());
XML_StreamWriter.Close();
}
}
I tried your code but I'm having a bad time making it to work.
If not a big deal, please could you tell me how to modify it ?
I mean, if a record is found, instead of editing, to remove it?
Honestly I'm stuck and any help is more than apprecisted!
Ren13B said:
I have no problem at all removing elements in c#. I don't have vb support even installed right now. If you think it's a bug you should post on the forums at http://forums.create.msdn.com/forums/98.aspx
Click to expand...
Click to collapse
Ren,
Just to say thank you for your last code. I made a little mod and now it works ok!
Thanks a lot for helping me out!

Development Guide for Integrating Share Kit on Huawei Phones

View attachment 5209541
What is Share Engine
As a cross-device file transfer solution, Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices. It delivers stable file transfer speeds that can exceed 80 Mbps if the third-party device and environment allow. Developers can use Huawei Share features using Share Engine.
The Huawei Share capabilities are sealed deep in the package, then presented in the form of a simplified engine for developers to integrate with apps and smart devices. By integrating these capabilities, PCs, printers, cameras, and other devices can easily share files with each other.
Three SDK development packages are offered to allow quick integration for Android, Linux, and Windows based apps and devices.
Working Principles
Huawei Share uses Bluetooth to discover nearby devices and authenticate connections, then sets up peer-to-peer Wi-Fi channels, so as to allow file transfers between phones, PCs, and other devices.
View attachment 5209543
To ensure user experience, Huawei Share uses reliable core technologies in each phase of file transfer.
Devices are detected using in-house bidirectional device discovery technology, without sacrificing the battery or security
Connection authentication using in-house developed password authenticated key exchange (PAKE) technology
File transfer using high-speed point-to-point transmission technologies, including Huawei-developed channel capability negotiation and actual channel adjustment
For more information you can follow this link.
Let’s get into codding.
Requirements
For development, we need Android Studio V3.0.1 or later.
EMUI 10.0 or later and API level 26 or later needed for Huawei phone.
Development
1 - First we need to add this permission to AndroidManifest.xml. So that we can ask user for our app to access files.
XML:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
2 - After let’s shape activity_main.xml as bellow. Thus we have one EditText for getting input and three Button in UI for using Share Engine’s features.
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/inputEditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="32dp"
android:hint="@string/hint"
tools:ignore="Autofill,TextFields" />
<Button
android:id="@+id/sendTextButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendText"
android:text="@string/btn1"
android:textAllCaps="false" />
<Button
android:id="@+id/sendFileButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendFile"
android:text="@string/btn2"
android:textAllCaps="false" />
<Button
android:id="@+id/sendFilesButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="sendMultipleFiles"
android:text="@string/btn3"
android:textAllCaps="false" />
</LinearLayout>
3 - By adding the following to strings.xml, we create button and alert texts.
XML:
<string name="btn1">Send text</string>
<string name="btn2">Send single file</string>
<string name="btn3">Send multiple files</string>
<string name="hint">Write something to send</string>
<string name="errorToast">Please write something before sending!</string>
4 - Later, let’s shape the MainActivity.java class. First of all, to provide access to files on the phone, we need to request permission from the user using the onResume method.
Java:
@Override
protected void onResume() {
super.onResume();
checkPermission();
}
private void checkPermission() {
if (checkSelfPermission(READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
String[] permissions = {READ_EXTERNAL_STORAGE};
requestPermissions(permissions, 0);
}
}
5 - Let’s initialize these parameters for later uses and call this function in onCreate method.
Java:
EditText input;
PackageManager manager;
private void initApp(){
input = findViewById(R.id.inputEditText);
manager = getApplicationContext().getPackageManager();
}
6 - We’re going to create Intent with the same structure over and over again, so let’s simply create a function and get rid of the repeated codes.
Java:
private Intent createNewIntent(String action){
Intent intent = new Intent(action);
intent.setType("*");
intent.setPackage("com.huawei.android.instantshare");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
We don’t need an SDK to transfer files between Huawei phones using the Share Engine, instead we can easily transfer files by naming the package “com.huawei.android.instantshare” to Intent as you see above.
7 - Let’s create the onClick method of sendTextButton to send text with Share Engine.
Java:
public void sendText(View v) {
String myInput = input.getText().toString();
if (myInput.equals("")){
Toast.makeText(getApplicationContext(), R.string.errorToast, Toast.LENGTH_SHORT).show();
return;
}
Intent intent = CreateNewIntent(Intent.ACTION_SEND);
List<ResolveInfo> info = manager.queryIntentActivities(intent, 0);
if (info.size() == 0) {
Log.d("Share", "share via intent not supported");
} else {
intent.putExtra(Intent.EXTRA_TEXT, myInput);
getApplicationContext().startActivity(intent);
}
}
8 - Let’s edit the onActivityResult method to get the file/s we choose from the file manager to send it with the Share Engine.
Java:
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
ArrayList<Uri> uris = new ArrayList<>();
Uri uri;
if (data.getClipData() != null) {
// Multiple files picked
for (int i = 0; i < data.getClipData().getItemCount(); i++) {
uri = data.getClipData().getItemAt(i).getUri();
uris.add(uri);
}
} else {
// Single file picked
uri = data.getData();
uris.add(uri);
}
handleSendFile(uris);
}
}
With handleSendFile method we can perform single or multiple file sending.
Java:
private void handleSendFile(ArrayList<Uri> uris) {
if (uris.isEmpty()) {
return;
}
Intent intent;
if (uris.size() == 1) {
// Sharing a file
intent = CreateNewIntent(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_STREAM, uris.get(0));
} else {
// Sharing multiple files
intent = CreateNewIntent(Intent.ACTION_SEND_MULTIPLE);
intent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, uris);
}
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
List<ResolveInfo> info = manager.queryIntentActivities(intent, 0);
if (info.size() == 0) {
Log.d("Share", "share via intent not supported");
} else {
getApplicationContext().startActivity(intent);
}
}
9 - Finally, let’s edit the onClick methods of file sending buttons.
Java:
public void sendFile(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(i, 10);
}
public void sendMultipleFiles(View v) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
i.setType("*/*");
startActivityForResult(i, 10);
}
We’ve prepared all the structures we need to create, so let’s see the output.
Text Sharing:
View attachment 5209563
Single File Sharing:
View attachment 5209565
Multiple File Sharing:
View attachment 5209567
With this guide, you can easily understand and integrate Share Engine to transfer file/s and text with your app.
For more information: https://developer.huawei.com/consumer/en/share-kit/
I'm not a coder and to old to learn. It is and will remain all Greek to me.
namitutonka said:
I'm not a coder and to old to learn. It is and will remain all Greek to me.
Click to expand...
Click to collapse
If you read it and follow as per instruction, its pretty simple
Dope
Wow! So nice i never think i wanna know about this thing...
Very nice and useful.

Categories

Resources