[Q] Writing in an XML File Problem - Windows Phone 7 Software Development

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?

Related

Turn off GPRS

I'm looking for a way to turn off the data (GRPS)
Search didn't brought me anything usefull, I'm sure there is somwhere the data but can't find it.
I'm especially need it for WM 6.5 (HD2)
Search around for Modaco's NoData program. It's late and I'm too tired to search it up for you right now.
kekkle said:
Search around for Modaco's NoData program. It's late and I'm too tired to search it up for you right now.
Click to expand...
Click to collapse
Thanks for the replay but it’s not what I meant, sorry for not be clarify.
I know the NoData app and actually i just finish writing something similar but more user friendly, hope to release it asap (Now I have problem with the icon )
What I’m looking is a way to turn off programmatically the data connection of the device, what the CommManager in the HTC sense do.
I tried to use the RAS api but it didn't work
look for jmlcomm.exe here at xda and use it in your app.simple command line call.and free to use.
MichelDiamond said:
look for jmlcomm.exe here at xda and use it in your app.simple command line call.and free to use.
Click to expand...
Click to collapse
Thanks for the idea, I'll try it.
But I prefer to do it directly from my app. without calling external tool.
I found a solution!
Its from few posts in the net, don't remember where exactly with some modification of me.
here is the code I use, if someone else will need it:
Code:
using System;
using System.Text;
using System.Runtime.InteropServices;
namespace RasHelper
{
class RasHelper
{
private const int SUCCESS = 0;
private const int ERROR_NOT_ENOUGH_MEMORY = 8;
private const int RASBASE = 600;
private const int ERROR_BUFFER_TOO_SMALL = RASBASE + 3;
private const int ERROR_INVALID_SIZE = RASBASE + 32;
// --- RASCONN data structure definition (refer to ras.h) --
private const int RAS_MaxEntryName = 20;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RASCONN
{
public int dwSize;
public IntPtr hrasconn;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = RAS_MaxEntryName + 1)]
public string szEntryName;
}
// --------------------------------------------
[DllImport("coredll.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern uint RasEnumConnections(
[In, Out] RASCONN[] rasconn,
[In, Out] ref int cb,
[Out] out int connections);
[DllImport("coredll.dll")]
private static extern uint RasHangUp(IntPtr pRasConn);
/// <summary>
/// Returns all active RAS connections as an array of data structure RASCONN
/// </summary>
/// <returns></returns>
public static RASCONN[] GetAllConnections()
{
RASCONN[] tempConn = new RASCONN[1];
RASCONN[] allConnections = tempConn;
tempConn[0].dwSize = Marshal.SizeOf(typeof(RASCONN));
int lpcb = tempConn[0].dwSize;
int lpcConnections = 0;
uint ret = RasEnumConnections(tempConn, ref lpcb, out lpcConnections);
if (ret == ERROR_INVALID_SIZE)
{
throw new Exception("RAS: RASCONN data structure has invalid format");
}
else if (ret == ERROR_BUFFER_TOO_SMALL && lpcb != 0)
{
// first call returned that there are more than one connections
// and more memory is required
allConnections = new RASCONN[lpcb / Marshal.SizeOf(typeof(RASCONN))];
allConnections[0] = tempConn[0];
ret = RasEnumConnections(allConnections, ref lpcb, out lpcConnections);
}
// Check errors
if (ret != SUCCESS)
{
throw new Exception("RAS returns error: " + ret);
}
if (lpcConnections > allConnections.Length)
{
throw new Exception("RAS: error retrieving correct connection count");
}
else if (lpcConnections == 0)
{
// if there are no connections resize the data structure
allConnections = new RASCONN[0];
}
return allConnections;
}
/// <summary>
/// Closes all active RAS connections
/// </summary>
/// <returns></returns>
public static void CloseAllConnections()
{
RASCONN[] connections = GetAllConnections();
for (int i = 0; i < connections.Length; ++i)
{
//MessageBox.Show(connections[i].ToString());
RasHangUp(connections[i].hrasconn);
}
}
/// <summary>
/// Check if there are open data connections
/// </summary>
/// <returns></returns>
public static bool IsConnectionsOpen()
{
RASCONN[] connections = GetAllConnections();
if (connections.Length > 0)
return true;
else
return false;
}
}
}

[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] [.net cf]Loopback

Hey guys
I'm developing a little webserver for WM with the .net cf. it's easy and works fine as long as I don't try to access it from the same device it's running on. Nothing works: localhost,127.0.0.1 or even if I'm connected to a wifi network and I use this IP. Has anyone the solution for this issue?
ta you
a yeah I use the TcpListener-Class and I implemted some simple HTTP.
chabun
Code
Hey guys
Noone has an idea??
Here is the code which I use to setup the HttpListener and answer connections.
Code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using StedySoft.SenseSDK;
using System.Threading;
using System.IO;
namespace WebServer
{
public partial class ServerForm : Form
{
IPEndPoint local;
TcpListener listener;
private volatile bool stop;
private volatile bool handled;
SensePanelItem state;
SensePanelTextboxItem response;
Thread serverThread;
public ServerForm(IPEndPoint local)
{
InitializeComponent();
this.local = local;
SetupList();
}
private void SetupList()
{
SensePanelDividerItem infos = new SensePanelDividerItem("infd", "Infos");
mainList.AddItem(infos);
mainList.AddItem(new SensePanelItem("Local-Endpoint") { PrimaryText = "Local-Endpoint", SecondaryText = local.ToString() });
mainList.AddItem(state = new SensePanelItem("Status") { PrimaryText = "Status", SecondaryText = "Wird gestartet..." });
mainList.AddItem(new SensePanelDividerItem("Response", "Response"));
mainList.AddItem(response = new SensePanelTextboxItem("body") { LabelText = "HTML-Body, welcher auf Requests gesendet wird.", Text = "<span style =\"color:red;font-size:30pt\">It works!!</span>" });
mainList.AddItem(new SensePanelDividerItem("Requests", "Requests"));
}
private void StartServer()
{
if (listener != null)
{
StopServer(true);
}
listener = new TcpListener(local.Port);
listener.Start();
serverThread = new Thread(listen);
serverThread.IsBackground = true;
stop = false;
serverThread.Start();
state.SecondaryText = "Gestartet...";
}
private void listen()
{
while (!stop)
{
while (listener.Pending())
{
handled = false;
Thread handlingThread = new Thread(handler);
handlingThread.Start();
while (!handled)
Thread.Sleep(50);
}
Thread.Sleep(200);
}
}
private void handler()
{
// Get the current connection
TcpClient client = (TcpClient)this.Invoke(new Func<TcpClient>(listener.AcceptTcpClient));
IPEndPoint remote = (IPEndPoint)client.Client.RemoteEndPoint;
handled = true;
NetworkStream stream = client.GetStream();
StreamReader reader = new StreamReader(stream);
ReadHttpRequest(reader);
StreamWriter writer = new StreamWriter(stream);
StringBuilder response = new StringBuilder(); ;
StartHTML(response);
response.AppendLine((string)this.Invoke(new Func<IPEndPoint, string>(GetResponse), remote));
EndHTML(response);
WriteHTTPResponse(writer, response.Length);
writer.WriteLine(response.ToString());
writer.Flush();
stream.Close();
client.Close();
}
private void WriteHTTPResponse(StreamWriter writer, int length)
{
writer.WriteLine("HTTP/1.1 200 OK");
writer.WriteLine("Date: " + DateTime.Now.ToString());
writer.WriteLine("Content-Length: "+ length.ToString());
writer.WriteLine("Connection: close");
writer.WriteLine("Content-Type: text/html; charset=utf-8");
writer.WriteLine();
}
private void ReadHttpRequest(StreamReader reader)
{
string buffer = null;
while (buffer != "")
buffer = reader.ReadLine();
}
int counter = 0;
private string GetResponse(IPEndPoint remote)
{
counter++;
mainList.AddItem(new SensePanelItem(counter.ToString()) { PrimaryText = remote.ToString(), SecondaryText = "Response:" + counter.ToString() });
return response.Text;
}
private void EndHTML(StringBuilder writer)
{
writer.AppendLine("</body>");
writer.AppendLine("</html>");
}
private void StartHTML(StringBuilder writer)
{
writer.AppendLine("<?xml version=\"1.0\"?>");
writer.AppendLine("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
writer.AppendLine("<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"de\" lang=\"de\">");
writer.AppendLine("<head>");
writer.AppendLine("<title>SmartWebServer</title>");
writer.AppendLine("<meta name=\"author\" content=\"Alexander Kayed\">");
writer.AppendLine("</head>");
writer.AppendLine("<body>");
}
private void StopServer(bool restart)
{
stop = true;
serverThread.Join();
if (restart)
StartServer();
}
private void ServerForm_Load(object sender, EventArgs e)
{
StartServer();
}
private void ServerForm_Closed(object sender, EventArgs e)
{
StopServer(false);
}
private void menuItem1_Click(object sender, EventArgs e)
{
this.Close();
}
}
}
The user can choose the IPEndPoint(constructor), which the server will be bound to, in a prevouis form:
Code:
foreach (IPAddress ip in Dns.GetHostEntry(Dns.GetHostName()).AddressList)
{
item = new SensePanelRadioItem(ip.ToString());
item.PrimaryText = ip.ToString();
item.SecondaryText = ip.AddressFamily.ToString();
item.Tag = ChoosedIp = ip;
item.OnStatusChanged += new SensePanelRadioItem.StatusEventHandler(item_OnStatusChanged);
IPList.AddItem(item);
}
So the user can choose between IPs I got from the DNS (e.g. 127.0.0.1, 192.168.0.1) and type a free (valid) port number (eg. 80, 8080, 8888)
Thanks for Your help!!
Still no answer...
I will post my experiences with this issue as long as I solved it - like small blog. Maybe some of you have the same problem...
I found another strange thing:
I'm able to connect to my Server from a TcpClient from another self-written App (own exectuable, different AppDomain):
Code:
void test()
{
Action<string> setText = new Action<string>(setTestText);
try
{
this.Invoke(setText, "Connect...");
TcpClient client = new TcpClient();
client.Connect(local);
this.Invoke(setText, "Connected...");
NetworkStream stream = client.GetStream();
StreamWriter writer = new StreamWriter(stream);
StreamReader reader = new StreamReader(stream);
writer.WriteLine();
writer.Flush();
this.Invoke(setText, "Read answer");
string buffer = reader.ReadToEnd();
this.Invoke(setText, "Test succeeded");
testing = false;
}
catch
{
this.Invoke(setText, "Test failed");
}
}
And I got a the right answer as well. It's strange, really strange that the browsers (IE,Opera etc.) can't loopback to it?

[Q] Developing app that requires root - freezes after asking for su

I am new to android development and am having an issue. I am working on an app that requires root and when I request it using this code:
Code:
Runtime.getRuntime().exec(new String[] {"su"});
I get the request, Allow it then the app locks up and doesn't go to the next item. I am trying to figure out the debugging environment in eclipse, but have not figured out a way to debug this. Is there something I need to do after acquiring root? The next line of code is a simple Toast, so I know it is locking up at the su command. Is there any documentation on writing root apps anybody can point me to? Or is there a simple answer? Thanks in advance.
EDIT: Just in case the whole code will help, here it is:
Code:
public class toggle extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.main);
String[] results = executeShellCommand(new String[] {"su"});
Toast toast = Toast.makeText(this, results[0], Toast.LENGTH_SHORT);
toast.show();
finish();
}
public String[] executeShellCommand(String[] args) {
Process mLogcatProc = null;
BufferedReader reader = null;
BufferedReader errorReader = null;
String logResult = null;
String errorLogResult = null;
String separator = System.getProperty("line.separator");
try
{
mLogcatProc = Runtime.getRuntime().exec(args);
reader = new BufferedReader(new InputStreamReader(mLogcatProc.getInputStream()));
errorReader = new BufferedReader(new InputStreamReader(mLogcatProc.getErrorStream()));
String line;
final StringBuilder log = new StringBuilder();
while ((line = reader.readLine()) != null)
{
log.append(line);
log.append(separator);
}
logResult = log.toString();
String errorLine;
final StringBuilder errorLog = new StringBuilder();
while ((errorLine = errorReader.readLine()) != null)
{
errorLog.append(errorLine);
errorLog.append(separator);
}
errorLogResult = errorLog.toString();
if((logResult.length() == 0) || (errorLogResult.length() > 0))
{
if(errorLogResult.length() > 0)
{
return errorLogResult.split(separator);
}
else
{
return (new String[] {"null_result"});
}
}
else
{
return logResult.split(separator);
}
}
catch (Exception e)
{
return (new String[] {e.toString()});
}
finally
{
if (reader != null)
try
{
reader.close();
}
catch (IOException e)
{
}
}
}
}
I do this a bunch in my RogueTools app.
Take a peek here:
https://github.com/myn/RogueTools/blob/master/src/com/logicvoid/roguetools/OverClock.java
Let me know if you need a hand.
myn said:
I do this a bunch in my RogueTools app.
Take a peek here:
https://github.com/myn/RogueTools/blob/master/src/com/logicvoid/roguetools/OverClock.java
Let me know if you need a hand.
Click to expand...
Click to collapse
Thanks a ton, I should be able to get it from here....I'll let you know if not.
Myn always on top of things
Sent from my unrEVOked using xda app

Can't change navigation bar buttons icons with my Xposed module

Hello friends!
I"m trying to build xposed module for educational purposes.
I want the module to:
1. Change the navigation bar color to green - this one works OK.
2. Change the navigation bar icons to custom icons i provide from my drawable resources - this one partially works, as described below.
The "home" button is changed, but the "recent apps" and "back" buttons didn't. Please see picture attached.
Can some one tell me why i can change the "home" button but not the "recent apps" and "back" buttons?
Any suggestion how to fix this?
module code:
Code:
import android.content.Context;
import android.content.res.XModuleResources;
import de.robv.android.xposed.IXposedHookInitPackageResources;
import de.robv.android.xposed.IXposedHookZygoteInit;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_InitPackageResources.InitPackageResourcesParam;
import de.robv.android.xposed.callbacks.XC_LayoutInflated;
import android.graphics.Color;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class TweakNavigationBar implements IXposedHookZygoteInit, IXposedHookInitPackageResources {
private static String MODULE_PATH = null;
@Override
public void initZygote(StartupParam startupParam) throws Throwable {
MODULE_PATH = startupParam.modulePath;
}
@Override
public void handleInitPackageResources(InitPackageResourcesParam resparam) throws Throwable {
if (!resparam.packageName.equals("com.android.systemui"))
return;
resparam.res.hookLayout("com.android.systemui", "layout", "navigation_bar", new XC_LayoutInflated() {
@Override
public void handleLayoutInflated(LayoutInflatedParam liparam) throws Throwable {
XModuleResources modRes = XModuleResources.createInstance(MODULE_PATH, liparam.res);
LinearLayout NavigationButtonsLayout = (LinearLayout) liparam.view.findViewById(
liparam.res.getIdentifier("nav_buttons", "id", "com.android.systemui"));
NavigationButtonsLayout.setBackgroundColor(Color.GREEN);
Context mContext = NavigationButtonsLayout.getContext();
ImageView backButton = (ImageView) liparam.view.findViewById(liparam.res.getIdentifier("back", "id", "com.android.systemui"));
ImageView homeButton = (ImageView) liparam.view.findViewById(liparam.res.getIdentifier("home", "id", "com.android.systemui"));
ImageView recentButton = (ImageView) liparam.view.findViewById(liparam.res.getIdentifier("recent_apps", "id", "com.android.systemui"));
//this also didn't work
//ImageView backButton = (ImageView) NavigationButtonsLayout.getChildAt(2);
//ImageView homeButton = (ImageView) NavigationButtonsLayout.getChildAt(3);
//ImageView recentButton = (ImageView) NavigationButtonsLayout.getChildAt(4);
recentButton.setImageDrawable(modRes.getDrawable(R.drawable.blue_button,null)); // didn't work!
homeButton.setImageDrawable(modRes.getDrawable(R.drawable.red_button,null)); // WORKS!
backButton.setImageDrawable(modRes.getDrawable(R.drawable,yellow_button,null)); // didn't work!
XposedBridge.log("start scan:");
for(int i=0; i< NavigationButtonsLayout.getChildCount() ; i++) {
View viewChild = (View) NavigationButtonsLayout.getChildAt(i);
XposedBridge.log(viewChild.toString());
if(viewChild instanceof ImageView)
XposedBridge.log("Child At " + i + " is instanceof ImageView" ) ;
}
}
});
}
}
Use this:
resparam.res.setReplacement(SYSTEM_UI, "drawable", "ic_sysbar_back_ime", modRes.fwd(R.drawable.n_back_down));
resparam.res.setReplacement(SYSTEM_UI, "drawable", "ic_sysbar_recent", modRes.fwd(R.drawable.n_recents));
resparam.res.setReplacement(SYSTEM_UI, "drawable", "ic_sysbar_back", modRes.fwd(R.drawable.n_back));
Note: SYSTEM_UI="com.android.systemui"
Using my method, i wasnt able to change the home button. But using your method, it did!
Thanks man!

Categories

Resources