Android Passing Variables to another activity with # not working as expected - android

Ok I'm trying to create a link to an activity and it works. However passint it a variable isn't working with # charters:
String hashTagString = tempValues.getDescription().replaceAll("[#]+[A-Za-z0-9-_]+\\b", "$0");
Log.i(Utils.TAG, "hashTagString: " + hashTagString);
The launched activity:
String tag = getIntent().getData().getQueryParameter("tag");
Log.i(Utils.TAG, "tag: " + tag);
Log Cat:
02-24 13:12:04.293: I/PROJECTCARUSO(29591): hashTagString: Everyone loves #hashtags ! Take advantage of them by using them and clicking to search by them.
The activity it launches show this:
02-24 13:13:48.885: I/PROJECTCARUSO(29591): tag:
However if I set it with hard coded values it shows:
02-24 13:14:41.176: I/PROJECTCARUSO(29883): hashTagString: Everyone loves #hashtags ! Take advantage of them by using them and clicking to search by them.
02-24 13:14:41.637: I/PROJECTCARUSO(29883): tag: test
I'd like to pass the whole value, but if i cannot how can I remove all special charaters?

I don't think your regex is being evaluated correctlyTry using the following regex
\\#[A-Za-z0-9\\-_]+
You may need to double escape (\). The \b (word-boundary) at the end of your sequence isn't needed because it will break when it reaches a " anyway and the - in your character class needs escaping otherwise the regex is trying to evaluate a nonsense range instead of treating it as a char
Edit
Now you've clarified your issue the issue with getting a blank tagis this:
String tag = getIntent().getData().getQueryParameter("tag");
It should be
String tag = getIntent().getExtras().getString("tag");
and should be sent as
new Intent(...).putExtra("tag", hashTagString);

Try (\s|\A)#(\w+) that as a Java string is "(\\s|\\A)#(\\w+)".
You can test it in the following site: http://www.regexplanet.com/advanced/java/index.html

Related

android: How to create an hyperlink to a code line using Log.d

I am learning logging in android code using android studio and emulator
I found that the following command shows a traceback with hyperlink to the code location
Log.d("TAG", "Message with stack trace info", new Throwable());
the image of logcat with hyperlink is
How can i create only the hyperlink part in my log message, without any traceback output
Try this, for example:
import android.util.Log;
public class Logger {
public static void log(String tag, String message) {
String caller = getCallerInfo(new Throwable().getStackTrace());
Log.d(tag, message + caller);
}
private static String getCallerInfo(StackTraceElement[] stacks) {
if (stacks == null || stacks.length < 1) {
return "";
}
StackTraceElement stack = stacks[1];
return String.format(" (%s:%s)", stack.getFileName(), stack.getLineNumber());
}
}
And call it from any where in your code
Logger.log("Manowar", "Today is the good day to die");
As of now the answer by #Cao Mạnh Quang was not giving me the Hyperlink.
The specific String format required for it's generation is this:
return String.format(" %s(%s:%s)", traceE.getClassName(), traceE.getFileName(), traceE.getLineNumber());
which is just the same as:
return stackTraceElement.toString();
so you may as well just do that.
Nothing was working for me...
My guess is that...
This hyperlink is generated by a preconfigured String specification format.
this format follows the className + "(" + fileName + ":" + lineNumber + ")"
If any of those parameters are missing, the hyperlink will not be generated.
There are a couple questions that arise from this:
Is this specification hard coded as a consensus of each LogCat display (IDE side interacts directly with String)
OR
Is this specification hardcoded into the Java code itself? (Java side interprets String generates hyperlink signal + IDE side interprets hyperlink signal and generates it)
The difference between which of these options is the one, would imply whether hyperlink generation is possible simply by changing the required configuration for the Logcat to generate the link either at IDE config level... OR at Java level.
Maybe it is not possible, and this configuration format cannot be changed....
Btw I am sure there must be some super hacky way to achieve this, maybe a way not so intuitive... or maybe it just requires some digging on the IDE config options...

Android Logcat very strange behavior when getting empty string

So I came across something strange that made me loose some time. I have been trying to print the content of an ArrayList containing string elements, sometimes, an element might contain an empty string, which is fine and absolutely my intention.
So I have something like this:
List<String> l = new ArrayList<String>();
//adding strings in l, sometimes it's an empty string
for (int i=0; i < l.size(); i++) {
Log.w("element in l : ", l.get(i));
}
So here, when the loop is gonna hit the empty string, logcat is simply NOT going to print it out BUT (and here is the root of my confusion), if you have a message following the one that failed to display, suddenly the failed message is going to show up as if it contained the new logcat message. For example if you try logging an empty string like this
Log.w(TAG, <empty string here>);
Logcat is going to output nothing at first, then, when it has a NEW message to display this is what it prints out (in this case the new message is some warning about AudioTrack):
08-21 17:06:02.265 13047-13047/company.myapp W/TAG﹕ [ 08-21 17:06:05.411 766: 937 W/AudioTrack ]
AUDIO_OUTPUT_FLAG_FAST denied by client
I'm interested in knowing how this happens, maybe it can help someone else not getting super confused like I did. I suppose trying to log an empty string triggers some kind of buffer that sits there until it gets something to print, is this a bug?
That is an interesting question. I just tried this in LogRabbit and am able to see the same result.
I took a quick browse through the android source and see that Log.W(...) ends up in native code and getting handled in logd_write.c
This basically writes the data to /dev/log/main (or one of the other logs)
You can get those logs like this:
adb pull /dev/log/events .
adb pull /dev/log/main .
adb pull /dev/log/radio .
adb pull /dev/log/system .
You will need to press cntl-C otherwise the copy will happen forever.
Looking in the raw log in /dev/log/main I see the message does get logged:
<8b>F×U^_<8c>^Y^U^Emfl_MessageList^#Before Empty^#^R^#^#^#!z^#^#!z^#^#
<8b>F×U^_<8c>^Y^U^Emfl_MessageList^#^#^]^#^#^#!z^#^#!z^#^#
<8b>F×U^_ <8c>^Y^U^Emfl_MessageList^#After Empty^#7^#^#^#^#^E^#^#^Z^E^#^#
That gets decoded by struct found in logger.h So I think this is a problem in adb. pull the source code from here: (looks like quite a few of undocumented commands there)
This is the primary function
static int logcat(TransportType transport, const char* serial, int argc, const char** argv) {
char* log_tags = getenv("ANDROID_LOG_TAGS");
std::string quoted = escape_arg(log_tags == nullptr ? "" : log_tags);
std::string cmd = "shell:export ANDROID_LOG_TAGS=\"" + quoted + "\"; exec logcat";
if (!strcmp(argv[0], "longcat")) {
cmd += " -v long";
}
--argc;
++argv;
while (argc-- > 0) {
cmd += " " + escape_arg(*argv++);
}
return send_shell_command(transport, serial, cmd);
}
Looking in there I see that all logcat does is basically this:
adb shell
> exec logcat
So I think the root of the problem is in logcat itself. Logcat.cpp calls into log_read.c
Based on my quick read through things what I think is happening is the message is not terminated properly. The empty message does not show up until another message is appended and the first message overruns and shows the second message because it has the appropriate termination.

Titanium: Show and Create Contact Intent

I was trying to export contacts from my application to the native android contacts.
I found the following solution here on this site: Titanium: How to add Contact in Phone book in Android?.
And it kinda works. The intent gets started. Only problem is, that android does not recognize most of the Extras i put in. So almost every field is blank. It does not matter if I replace contactModel with a simple String, the result is the same.
So i was wondering if the keys are simply wrong, but there seems no proper documentation on appcelerator. Probably something has changed over the past years or I am just missing something. Does anybody know how to do it the right way.
Code Snippet:
if (OS_ANDROID) {
var intent = Ti.Android.createIntent({
action : 'com.android.contacts.action.SHOW_OR_CREATE_CONTACT',
data : 'mailto:' + contactModel.get('contact_first_name') + ' ' + contactModel.get('contact_last_name')
});
intent.putExtra('email', contactModel.get('contact_email'));
intent.putExtra('email_type', 'Work');
intent.putExtra('phone', contactModel.get('contact_mobile_number'));
intent.putExtra('phone_type', 'mobile');
intent.putExtra('name', contactModel.get('contact_first_name') + ' ' + contactModel.get('contact_last_name') );
intent.putExtra('address', addressModel.get('address_street') + ", " + addressModel.get('address_city'));
intent.putExtra('address_type', 'Work');
Ti.Android.currentActivity.startActivity(intent);
}
Thx in advance. :)
The first parameter of putExtra() also accepts one of the constants Ti.Android.... So instead of email you would probably have to use Ti.Android.EXTRA_EMAIL.
I think you can find quite a lot in the docs, e.g. here:
EXTRA constant properties in Ti docs
EXTRA constants in Android docs
Android Intents in Ti docs

Jelly Bean Issue - wifiManager.getConnectionInfo().getSSID() - extra ""

Hi all bug reporting for your information. link
Problem details:
The Code - wifiManager.getConnectionInfo().getSSID()
The above code to returns the current SSID, it is returning the current SSID with extra quotations around it.
For eg. the SSID internet is returned as "internet".
This is only seen on Jelly bean 4.2 using device Nexus 7.
This bug is causing errors in our app as we compare the current SSID with the SSID that we are trying to connect too.
The code wifiManager.getScanResults(); however still returns all SSID's without extra quotation marks.
this is not a bug and behavior is correct as per documentation at http://developer.android.com/reference/android/net/wifi/WifiInfo.html#getSSID()
The so-called bug apparently was in pre 4.2 devices, because they didn't return it with "" enclosure.
Aiden's method looks good to me in the current state of confusion left by Android. However, being theoritically correct would just require
if (ssid.startsWith("\"") && ssid.endsWith("\"")){
ssid = ssid.substring(1, ssid.length()-1);
}
This regular expression is quite neat:
String ssid = wi.getSSID().replaceAll("^\"(.*)\"$", "$1");
Just for the notes
Edit °1 (as per question in the comment):
The issue that OP describes is, that on some devices the SSID returned by getSSID() is enclosed in "" whereas it is not on other devices. E.g. on some devices the SSID is "MY_WIFI" and on others it is MY_WIFI - or spoken in Java code: "\"MY_WIFI\"" and "MY_WIFI".
In order to to unify both results I proposed to remove the " at start and end - only there, because " is a legal character inside the SSID. In the regular expression above
^ means from start
$ means at end
\" means " (escaped)
.* means any number of characters
(...) means a capturing group, that can be referred by $1
So the whole expression means: replace "<something>" by <something> where $1 = <something>.
If there is no " at end/start, the regular expression doesn't match and nothing is replaced.
See Java Pattern class for more details.
For the mean time this is how I am getting around it, although its not great it will fix the issue.
public String removeQuotationsInCurrentSSIDForJellyBean(String ssid){
int deviceVersion= Build.VERSION.SDK_INT;
if (deviceVersion >= 17){
if (ssid.startsWith("\"") && ssid.endsWith("\"")){
ssid = ssid.substring(1, ssid.length()-1);
}
}
return ssid;
}
Two very simple variants:
string = string.replaceAll("^\" | \"$", "");
and
string = string.substring(1, string.length() - 1);
Faced the same problem! Used this technique which is backwards compatible:
if (suppliedSSID.equals(connectionInfo.getSSID()) || ("\"" + suppliedSSID + "\"").equals(connectionInfo.getSSID()) { DO SOMETHING }

sendKeys - Send special characters

addressBar = (AutoCompleteTextView) mActivity.findViewById(package.R.id.addressBar);
TouchUtils.tapView(this, addressBar);
sendKeys("1"); //Works
sendKeys("G M A I L"); // Works - Result would be "gmail"
sendKeys("G M A I L . C O M"); // Doesn't work
sendKeys("{.}"); // Doesn't work
sendKeys("gmail") // Doesn't work
sendKeys("G M A I L {.} C O M") //Doesn't work
I am writing android test scripts using "InstrumentationTestCase2". I actually want to sendkeys - "gmail.com" but, unable to send special character "."(Dot)
For '.' (period or dot) you can try the int equivalent values of it.
Like,
sendKeys(56);
From Android-Docs
public static final int KEYCODE_PERIOD
Key code constant: '.' key.
Constant Value: 56 (0x00000038)
"The sequence of keys is a string containing the key names as specified in KeyEvent, without the KEYCODE_ prefix." (sendKeys documentation)
So you can use NUMPAD_DOT in the sendKeys string.
e.g.
sendKeys("G M A I L NUMPAD_DOT C O M");
For Further information see :
(http://developer.android.com/reference/android/test/InstrumentationTestCase.html#sendKeys(java.lang.String))
sendKeys(56); // for special character "." (Dot)
Have you tried the following:
getInstrumentation().sendStringSync("Do.You#Love.IT???");
works like magic and makes life a lot simpler!

Categories

Resources