Sorry for lame and easy question but I failed to find an answer to it.
Every time I print something to the System.Diagnostics.Debug.WriteLine I have my message tripled:
System.Diagnostics.Debug.WriteLine("test");
Output:
[0:]
test
[0:] test
10-22 19:57:13.981 I/mono-stdout( 1026): test
I'm stick to System.Diagnostic.Debug because I write messages from both UI part (monodroid) and business logic (PCL)
Is there any way to descrease level of debug noise of Xamarin.Android?
Thank you for any suggestions.
Make your own little abstraction. We have the same issue in our project, this little Interface helps:
public interface ILogger
{
void Write(LogLevel level, String tag, String message);
}
Then you have your Loggers for each platform, for example:
public class AndroidLogger: ILogger
{
public void Write(LogLevel level, string tag, string message)
{
Android.Util.Log.WriteLine(ConvertLogLevel(level), tag, message);
}
}
You inject the logger in the iOS/Android project and you can even create fancy logger like e.g. a nice file-logger for iOS:
#if DEBUG
LOG.AddLogger(new TouchFileLogger());
LOG.AddLogger(new ConsoleLogger());
#endif
The LOG-class is static and needs not to know about the implementations, thats why it can be easily used in your shared PCL library.
Hope that helps, despite your problem might be solved by now ;-)
You can use Android.Util.Log instead, this greatly decreases it. It also has different levels of logging which you can filter in logcat.
Info: Log.Info()
Debug: Log.Debug()
Warning: Log.Warn()
Error: Log.Error()
Verbose: Log.Verbose()
and additionally a WriteLine, which does all of the above:
Log.WriteLine()
Related
I have been trying a ( i hope) simple bit of Android hyperloop code directly within a titanium project (using SDK 7.0.1.GA and hyperloop 3).
var sysProp = require('android.os.SystemProperties');
var serialNumber = sysProp.get("sys.serialnumber", "none");
But when the app is run it reports
Requested module not found:android.os.SystemProperties
I think this maybe due to the fact that when compiling the app (using the cli) it reports
hyperloop:generateSources: Skipping Hyperloop wrapper generation, no usage found ...
I have similar code in a jar and if I use this then it does work, so I am wondering why the hyperloop generation is not being triggered, as I assume that is the issue.
Sorry should have explained better.
This is the jar source that I use, the extraction of the serial number was just an example (I need access to other info manufacturer specific data as well), I wanted to see if I could replicate the JAR functionality using just hyperloop rather that including the JAR file. Guess if it's not broke don't fix it, but was curious to see if it could be done.
So with the feedback from #miga and a bit of trial and error, I have come up with a solution that works really well and will do the method reflection that is required. My new Hyperloop function is
function getData(data){
var result = false;
var Class = require("java.lang.Class");
var String = require("java.lang.String");
var c = Class.forName("android.os.SystemProperties");
var get = c.getMethod("get", String.class, String.class);
result = get.invoke(c, data, "Error");
return result;
}
Where data is a string of the system property I want.
I am using it to extract and match a serial number from a Samsung device that is a System Property call "ril.serialnumber" or "sys.serialnumber". Now I can use the above function to do what I was using the JAR file for. Just thought I'd share in case anyone else needed something similar.
It is because android.os.SystemProperties is not class you can import. Check the android documentation at https://developer.android.com/reference/android/os/package-summary.html
You could use
var build = require('android.os.Build');
console.log(build.SERIAL);
to access the serial number.
So some background information. I am tasked with exploring writing cross platform native applications using Xamarin. Seems pretty basic so far and I'm liking what I'm reading. I have my Visual Studio 2015 Enterprise all set up and my remote mac configured on the network. I created a cross platform native app through the project creation wizard in Visual Studio. When I launch a debug session for the iOS app, it does start the target app in the simulator on the remote Mac. However, it never actually thinks it is running fully. It will hang at this output:
Launching 'PersonalProject.iOS' on 'iPhone 6 iOS 10.2'...
Loaded assembly: /Users/plm/Library/Developer/CoreSimulator/Devices/B5A038B6-056F-4E6C-A59C-29ABD8C04CD0/data/Containers/Bundle/Application/2A1B11FF-6C59-4A9B-9CE3-7B8446B1AD48/PersonalProject.iOS.app/Xamarin.iOS.dll
Loaded assembly: /Users/plm/Library/Developer/CoreSimulator/Devices/B5A038B6-056F-4E6C-A59C-29ABD8C04CD0/data/Containers/Bundle/Application/2A1B11FF-6C59-4A9B-9CE3-7B8446B1AD48/PersonalProject.iOS.app/System.dll
Thread started: #2
Loaded assembly: /Users/plm/Library/Developer/CoreSimulator/Devices/B5A038B6-056F-4E6C-A59C-29ABD8C04CD0/data/Containers/Bundle/Application/2A1B11FF-6C59-4A9B-9CE3-7B8446B1AD48/PersonalProject.iOS.app/PersonalProject.iOS.exe
Loaded assembly: /Users/plm/Library/Developer/CoreSimulator/Devices/B5A038B6-056F-4E6C-A59C-29ABD8C04CD0/data/Containers/Bundle/Application/2A1B11FF-6C59-4A9B-9CE3-7B8446B1AD48/PersonalProject.iOS.app/System.Xml.dll
Eventually, it will fail with something along these lines:
The app has been terminated.
Launch failed. The app 'PersonalProject.iOS' could not be launched on 'iPhone 6 iOS 10.2'. Error: An error occurred while executing MTouch. Please check the logs for more details.
I've checked the log file in question and it contains nothing more than the same exact phrase.
If I try and put a simple line of Console writing on the action of pressing the button:
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Perform any additional setup after loading the view, typically from a nib.
Button.AccessibilityIdentifier = "myButton";
Button.TouchUpInside += delegate {
var title = string.Format ("{0} clicks!", count++);
Button.SetTitle (title, UIControlState.Normal);
Console.WriteLine(string.Format("{0} clicks!"));
};
}
the debug session actually errors on this line 17 (UIApplication.Main) in the Main.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using Foundation;
using UIKit;
namespace PersonalProject.iOS
{
public class Application
{
// This is the main entry point of the application.
static void Main (string[] args)
{
// if you want to use a different Application Delegate class from "AppDelegate"
// you can specify it here.
UIApplication.Main (args, null, "AppDelegate");
}
}
}
With Unhandled exception error:
Unhandled Exception:
System.FormatException: Index (zero based) must be greater than or equal to zero and less than the size of the argument list.
Error while resolving expression: One or more errors occurred.
If I don't have the console log it will launch the app, but still hanges at those Loaded assembly lines. At this point, I can't hit any breakpoints in my code. I tried adding a breakpoint in the shared code for the button click but it would never hit it, even though the action was being carried out by the simulator.
I'm completely at a loss for how to proceed. I haven't touched anything out of the box of the wizard creation. I was hoping I could at least see the starter project working.
Any help is appreciated.
You are using
Console.WriteLine(string.Format("{0} clicks!"));
The {0} is a placeholder for a value to output, but you never specify that value, that's why you are getting an error.
Use something like this instead:
Console.WriteLine(string.Format("{0} clicks!", count));
or in C#6 syntax:
Console.WriteLine($"{count} clicks!");
I got a very annoying issue. All of my Android plugins in Unity just work if I dont use parameters in the calling functions. I am working on this issue since 2 days and I am slowly running out of ideas. Even a minimal project doesnt work. I am sure Iam doing it right because my functions are working fine without parameters.
Unity:
void Start (){
AndroidJavaClass pluginClass = new AndroidJavaClass("tnbrtrm.lications.de.myplugin.MyPlugin");
String test = pluginClass.CallStatic<string>("getMessage", new object[] { "alalalalala" });
Debug.Log("callShareAppAARPlugin: " + test);}
Android:
public class MyPlugin extends UnityPlayerActivity {
public static String getMessage(String text)
{ return "Hello World! " + text; }
}
My plugin prints "Hello world" correctly when I delete the parameter "String text", but with parameter I get this annoying error:
AndroidJavaException: java.lang.NoSuchMethodError: no static method "Ltnbrtrm/lications/de/myplugin/MyPlugin;.getMessage(Ljava/lang/String;)Ljava/lang/String;"
I see this error using Plugins as *.jar or *.aar. And I also had a look into this packages and my Classes and Functions are there. Otherwise it wouldnt work without parameters... I tried AndroidJavaClass and AndroidJavaObject.
Can anyone please help me? I tried a lot of things... (older JDK versions, etc.) I seems so easy in all the turorials so I assume it has something to do with my system or unity (5.3.5 pro).
Kind regards,
Tino
I'm having a confusing problem. I'm trying to make a Web cleint that uses WSDL.
I'm using C++ RAD Studio 10 Seattle, but the same problem occured in RAD Studio XE8(older version).
1.I create a Multi-Device Application, add one Edit component and one Button.
2.I create a WSDL Importer by changing the location of the WSDL file to : "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL" and leave all other setting to default.
3.On ButtonClick event of the button I write two lines of code :
_di_TempConvertSoap Converter = GetTempConvertSoap(true,
"http://www.w3schools.com/webservices/tempconvert.asmx?WSDL");
Edit1->Text = Converter->CelsiusToFahrenheit("32");
So after these three steps I have one unit, which is the main Unit with the Form and with the button event. And one file "tempconvert.cpp" that the WSDL Importer has generated. It quite actually just translates the WSDL code to a C++ one and defines the method to communicate with the server. In my case I have two methods : FahrenheitToCelsius() and CelsiusToFahrenheit(), in the example I use CelsiusToFahrenheit().
I compile it to 32-bit Windows platform, run it and when I click the button, the result "89.6" appears in the text of the Edit component. So this is working as expected.
But when I change the target platform to "Android" and use my mobile phone "Samsung GT-I8262" with Android 4.1.2 and run the project, it just stops and exits. I debugged the problem and it stops at the first command in "tempconvert.cpp" in RegTypes() method.
// ************************************************************************
//
// This routine registers the interfaces and types exposed by the WebService.
// ************************************************************************ //
static void RegTypes()
{
/* TempConvertSoap */
InvRegistry()->RegisterInterface(__delphirtti(TempConvertSoap), L"http://www.w3schools.com/webservices/", L"utf-8");
InvRegistry()->RegisterDefaultSOAPAction(__delphirtti(TempConvertSoap), L"http://www.w3schools.com/webservices/%operationName%");
InvRegistry()->RegisterInvokeOptions(__delphirtti(TempConvertSoap), ioDocument);
/* TempConvertSoap.FahrenheitToCelsius */
InvRegistry()->RegisterMethodInfo(__delphirtti(TempConvertSoap), "FahrenheitToCelsius", "",
"[ReturnName='FahrenheitToCelsiusResult']", IS_OPTN);
/* TempConvertSoap.CelsiusToFahrenheit */
InvRegistry()->RegisterMethodInfo(__delphirtti(TempConvertSoap), "CelsiusToFahrenheit", "",
"[ReturnName='CelsiusToFahrenheitResult']", IS_OPTN);
/* TempConvertHttpPost */
InvRegistry()->RegisterInterface(__delphirtti(TempConvertHttpPost), L"http://www.w3schools.com/webservices/", L"utf-8");
InvRegistry()->RegisterDefaultSOAPAction(__delphirtti(TempConvertHttpPost), L"");
}
#pragma startup RegTypes 32
Does someone have any idea why this might be happening? I tried on two other Samsung phones and it didn't work. The error that shuts the program down is "Segmentation fault(11)", and more precisely it stops at the following line of code in "System.pas" file :
u_strFromUTF8(PUChar(Dest), MaxDestChars, DestLen, MarshaledAString(Source), SourceBytes, ErrorConv);
Here is some info that I've found about the function:
u_strFromUTF8 - function that converts a UTF-8 string to UTF-16.
UCHAR is a Byte(in Delphi), so PUCHAR is a pointer to Byte.
I cannot se what could possibly go wrong with this function which apparently only converts a string.
So my question is why does the project work on Windows 32 bit version, but on Android it throws Segmentation fault(11)?
I hope I could find a solution for this problem. I will keep looking.
Thank you,
Zdravko Donev :)
UPDATE:
I disassembled the line:
InvRegistry()->RegisterInterface(__delphirtti(TempConvertSoap), L"http://www.w3schools.com/webservices/", L"utf-16");
to get :
TInvokableClassRegistry *Class = InvRegistry();
TTypeInfo *Info = __delphirtti(TempConvertSoap);
UnicodeString Namespace = "http://www.w3schools.com/webservices/";
UnicodeString WSDLEncoding = "utf-8";
Class->RegisterInterface(Info, Namespace, WSDLEncoding);
And I saw that the problem occurs when calling InvRegistry() function, but I still haven't found the problem as I cannot reach the source code of the function.
I found a solution.
I deleted the line
#pragma startup RegTypes 32
and called the method RegTypes() on my own when I create the form and it worked.
I am using Log4j to log data in my android application. I have configured the log4j with the help of the following class, but the log files are not getting created.
console logging is enabled, maxfilesize and maxbackupsize are also good. please let me know what i am missing here.
public class ConfigureLog4J {
static LogConfigurator logConfigurator = new LogConfigurator();
private static final int maxFileSize = 1024 * 5; // 100KB
public static final int maxBackupSize = 2; // 2 backup files
public static final String LOG_FILE_NAME = "bitzer.log";
private static HashMap<Integer, Level> logLevelMap = new HashMap<Integer, Level>();
static {
logLevelMap.put(0, Level.OFF);
logLevelMap.put(1, Level.ERROR);
logLevelMap.put(2, Level.INFO);
logLevelMap.put(3, Level.WARN);
logLevelMap.put(4, Level.DEBUG);
logLevelMap.put(5, Level.ALL);
}
public static void startWithLogLevel(int logLevel) {
logConfigurator.setFileName(getLogFileName());
logConfigurator.setRootLevel(getLevelFromInt(logLevel));
logConfigurator.setUseFileAppender(true);
logConfigurator.setUseLogCatAppender(isConsoleLoggingEnabled());
logConfigurator.setMaxFileSize(getMaxFileSize());
logConfigurator.setMaxBackupSize(maxBackupSize);
// Set log level of a specific logger
// logConfigurator.setLevel("org.apache", Level.ERROR);
logConfigurator.setResetConfiguration(true);
logConfigurator.configure();
}
private static long getMaxFileSize() {
return CompanySettings.getInstance().getValueAsInteger(R.string.max_log_size);
}
private static boolean isConsoleLoggingEnabled() {
return CompanySettings.getInstance().getValueAsBoolean(R.string.consoleLoggingEnabled);
}
private static Level getLevelFromInt(int newLogLevel) {
return logLevelMap.get(newLogLevel);
}
public static String getLogsDirectory() {
if(AppData.getInstance().getContext()!=null)
{ String packageName = AppData.getInstance().getContext().getPackageName();
System.out.println("sundeep package name is not null and it's"+packageName);
return "data/data/" + packageName + "/logs/";
}
return null;
}
public static String getLogFileName() {
return getLogsDirectory() + LOG_FILE_NAME;
}
}
SLF4J Overview
I highly recommend you use SLF4J, which is log4j's "older brother" of sorts; the same developers who made log4j made SLF4J to address the shortcomings of log4j.
The difference is, whereas log4j is a full-fledged logging framework, SLF4J is a facade which you use directly in your Java code. The facade aspect allows you to plugin a concrete logging implementation — such as log4j, logback, Android's Log utility, etc. — at runtime.
It allows you to write code that can be used between different projects without having to go through your code and convert your logging statements to use the target project's logging framework. If you have several thousand lines of code which use log4j, but the target you're importing them into uses Apache Commons logging, you'll soon find yourself with a headache if you manually make the changes... even with the assistance of a capable IDE.
Using log4j in Android
There's a great Android library for logging to log4j — as well as many other logging frameworks as well — called android-logging-log4j. Check out the very excellent section on "Using log4j over slf4j", which is the route I take in my Android projects.
Examples from my own projects
Here are some examples from my own projects, such as my Awnry News & Weather app. (Yeah, shameless plug :P)
Required JARs on classpath
Basically these are the JARs I'll typically have in my project's classpath (version numbers vary as new releases come about, of course).
android-logging-log4j-1.0.3.jar
log4j-1.2.17.jar
slf4j-api-1.7.6.jar
slf4j-log4j12-1.7.6.jar
Instantiating a class's logger
And here's how I instantiate my general logger in each of my classes that require logging:
package com.awnry.android.naw;
...
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
...
public class NawApplication extends Application
{
private static final Logger log = LoggerFactory.getLogger(NawApplication.class);
As you can see, I'm only referencing SLF4J's Logger and LoggerFactory interfaces, even though the actual logging may eventually be accomplished using log4j or Android's Log.
That's the beauty of SLF4J's facade design: You aren't tied down to any specific logging implementation/framework; you can change your mind in the future without having to change a line of your code. If you're using log4j over SLF4J now, but in the future you want to use the Apache Commons Logging framework all you have to do is switch out the SLF4J-to-log4j bridge to a SLF4J-to-ACL bridge, and none of your Java code will be any wiser as it only calls SLF4J interfaces. The time-honored adage to code to an interface, not an implementation holds true once again, and SLF4J is a superb example of that.
Configuring the Android app's logging
In my Application.onCreate() method, I configure my logging like this:
#Override
public void onCreate()
{
...
String logFile = getFilesDir().getAbsolutePath() + File.separator + "logs" + File.separator + "debug.log";
log.info("Application log file: " + logFile);
LogConfigurator logConfigurator = new LogConfigurator(logFile, Level.TRACE);
logConfigurator.configure();
...
}
This part is actually optional, I believe. In my case I do this because I use the ACRA library to help catch unexpected program crashes and report the details back to me for debugging, so you might not need to define your android-logging-log4j's LogConfigurator as I do here.
Why you are using log4j.
There are efficient Log utility is available specially designed for android.
Use LogCat. Its very simple to use and standard way of putting log in your android app.