Placing String from strings.xml in the Toast Message - java

I'm currently finishing my game app for android, but I have encountered one problem that keeps crashing my app.
I was trying to place the text from strings.xml inside the toast message and my code looks like this:
// THIS IS THE PART THAT DOES NOT WORK:
int stringrank = getResources().getIdentifier("rank"+points, "string", this.getPackageName());
rank = getString(stringrank);
// I want to get different rank String depending on the collected points,
// so it would be rank1, rank2, rank3 and so on - thats why "rank"+points.
// It worked for me in the different parts of the code, but when I want to
// use it in the Toast Message it does not.
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.done_toast, (ViewGroup) findViewById(R.id.done_toast));
TextView text = (TextView) layout.findViewById(R.id.text);
// APP CRASHES when I use "rank" String here, if I place other text it works just fine.
text.setText(rank);
final Toast donetoast = new Toast(getApplicationContext());
donetoast.setGravity(Gravity.BOTTOM|Gravity.CENTER_HORIZONTAL, 0, 35);
donetoast.setDuration(Toast.LENGTH_SHORT);
donetoast.setView(layout);
// Rest of the Toast Message code is below, not important.
(...)
When I place the normal text in the Toast Message (does not matter whether in Java or in the done_toast.xml) it works perfectly, but if I want to call the String from strings.xml the app crashes.
Thank you for your help in advance!

You can't create a Toast object like that. It must be done using Toast.makeText().
Try this
final Toast donetoast=Toast.makeText(getApplicationContext());
donetoast.setDuration(Toast.LENGTH_SHORT);
donetoast.setView(layout);

Related

Android ACTION_SEND with special unicode characters

I am trying to send text using an intent. I thought it was straight-forward:
public Intent getIntent() {
final Intent intent = new Intent();
intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getText());
return intent;
}
private String getText(){
// the emoji can be one of many. I removed all that for brevity
final int unicode = 0x1F3C5;
final String emoji = String.valueOf(Character.toChars(unicode));
// final String emoji = "\n1F3C5"; //didn't work either
// I also tried using HTML here but I think I have some wires crossed, so I am not ruling that out yet
return textPartOne + " " + emoji + " " + textPartTwo;
}
As you can see, the EXTRA_TEXT has a special character in it (an emoji). When the text sends from device A the emoji appears like I expect in the message. But on device B (the receiver) the text shows some madness (usually in two different messages):
#.£¡ù¿ ¡ ¡ | | < | | | \ < | [ ¡ { ¡ [ ¡
#H£(ù#æ#a#¤¥¡
¡9#ü#Hù#Θ#=#ø¥p
¡6#Ö#Δì¿ ¡ |
It doesn't matter if I send the message from device A to device B or B to A. I get the same results either way, so I believe it isn't an issue with the emoji not being supported.
Now, if I remove all but the emoji code:
Xäx&
If I remove the emoji code altogether it works like a charm.
But the client has gotta have those emojis...
😤
Some other things that may be of note:
I am using this to manage what intents I am presenting to the user. They could pick MMS, email, Twitter, Facebook or whatever really. I need to support all of these
I am getting the special characters from Emojipedia
I am not displaying the emojis anywhere in the app. They will be shown in Text message, Email, or Facebook/Twitter feed.
There is already an iOS variant of this app who is successfully doing this.
I have tried nearly a dozen different ways with no avail.
Is there anyone that may have some insight on how to properly send special characters?
Edit:
As you can see, I am sending the emoji I desire. But the result is far from what I expect. This is a screenshot of an emulator sending a text to itself.
Here are some of the ways I have tried
String attempt1 = "--";
try {
attempt1 = Html.fromHtml(new String("&#x1F3C5".getBytes("UTF-8"))).toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
final int codePoint = 0x26F7;
final String attempt2 = new String(new int[]{codePoint}, 0, 1);
final String attempt3 = new String(Character.toChars(codePoint));
final String attempt4 = "\u26F7";
All result in:
&n
If I add text to these:
final String attempt4 = "COME ON: \u26F7";
I get this:
#Σ£(ù#æ#s##£ Å¡7#X£¿ù¿
Which makes total sense he said sarcastically
You can use intents, which are messages sent between activities. In a intent you can put all sort of data, String, int, etc.
In your case, in activity2, before going to activity1, you will store a String message this way :
Intent intent = new Intent(activity2.this, activity1.class);
intent.putExtra("message", getText());
startActivity(intent);
In activity1, in onCreate(), you can get the String message by retrieving a Bundle (which contains all the messages sent by the calling activity) and call getString() on it :
Bundle bundle = getIntent().getExtras();
String message = bundle.getString("message");
Then you can set the text in the TextView:
TextView txtView = (TextView) findViewById(R.id.your_resource_textview);
txtView.setText(message);
Hope this helps !

How to interpret this log message?

I was trying to add a text view to a LinearLayout programmatically using the following:
Resources r = getResources ();
TextView text = new TextView (this);
text.setText (R.string.no_passwords);
Log.d ("My App", r.getString (R.string.no_passwords));
text.setTextSize (r.getDimension (R.dimen.prompt_size));
Log.d ("My App", "Text size: " + r.getDimension (R.dimen.prompt_size));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams (ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
parent.setGravity (Gravity.CENTER);
text.setLayoutParams (params);
parent.addView (text);
Explanation:
parent is the LinearLayout with the id parent_layout (You will see this in the code below). I am logging with the tag "My App" because I am using a custom filter to log stuff.
But the view is not added. I looked at the log message and see something relly weird:
10-17 09:33:26.764 11877-11877/com.passwordgen D/My App﹕ [ 10-17 09:33:26.764 11877:11877 D/My App ]
Text size: 43.132
R.string.no_password should be "You have not saved any passwords yet" and R.dimen.prompt_size should be 9pt.
Quuestions:
Why the first log message isn't showing the right text but [ 10-17 09:33:26.764 11877:11877 D/My App ]? And why the second message is not prefixed by the tag "My App"?
You will need to call invalidate() to make the view be redrawn. Also it is recommended you do this via an xml file vs. in code.

Android Linkify - Clickable telephone numbers

So I am trying to add the functionality that when you click on a phone number it would take you to the Dialer app with the pre-populated number. I have the code below:
mContactDetailsText.setText(phonetextBuilder.toString());
Pattern pattern = Pattern.compile("[0-9]+\\s+[0-9]+");
Linkify.addLinks(mContactDetailsText, pattern, "tel:");
and the Text is currently "T. 0123 4567890"
The current outcome is just having the above string without it being clickable. I have even tried added the following line, but to no luck:
mContactDetailsText.setAutoLinkMask(0);
Anyone got any ideas or can see what I am doing wrong?
Thanks
The autolink mask needs to include a search for phone numbers:
mContactDetailsText.setAutoLinkMask(Linkify.PHONE_NUMBERS);
Then you'll need to set the links to be clickable:
mContactDetailsText.setLinksClickable(true);
You might also need movement method set like so:
mContactDetailsText.setMovementMethod(LinkMovementMethod.getInstance())
You should be able to accomplish what you want with the other answers,
but this will definitely work and will give you more control over the display of the text and what will happen when you click the number.
String text = "T. ";
StringBuilder stringBuilder = new StringBuilder(text);
int phoneSpanStart = stringBuilder.length();
String phoneNumber = "0123 4567890"
stringBuilder.append(phoneNumber);
int phoneSpanEnd = stringBuilder.length();
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View textView) {
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:" + phoneNumber.replace(" ", "")));
startActivity(intent);
}
public void updateDrawState(TextPaint ds) {// override updateDrawState
ds.setUnderlineText(false); // set to false to remove underline
ds.setColor(Color.BLUE);
}
};
SpannableString spannableString = new SpannableString(stringBuilder);
spannableString.setSpan(clickableSpan, phoneSpanStart, phoneSpanEnd,Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
myTextView.setText(spannableString);
myTextView.setMovementMethod(LinkMovementMethod.getInstance());
You need to set an onClickListener() on your TextViews. Then they will respond to clicks.

Add domain to a relative link

I'm fetching some data containing HTML from my server to use in my app, and the html has some links like Go here.
I'm applying the html to a TextView like
text.setText(Html.fromHtml(htmlString));
text.setMovementMethod(LinkMovementMethod.getInstance());
The link works, but causes my app to crash with
No Activity found to handle Intent { act=android.intent.action.VIEW dat=/go/here...`
I'm guessing the crash is because it's a relative link and doesn't have the domain in. Is there any methods, maybe Regex, to search for all <a/> tags and add the domain before it?
I would be tempted to go the simplest way:
final String faultyHtml = "Link: click here etc etc";
final String domain = "http://www.google.fr";
final String fixedHtml = faultyHtml.replace("href=\"/", "href=\"" + domain + "/");
text.setText(Html.fromHtml(fixedHtml));
text.setMovementMethod(LinkMovementMethod.getInstance());
(all occurrences would be added the same domain though)
int index = htmlString.indexOf("<a>");
String part1 = htmlString.subString(0,index+2);
String part2 = htmlString.subString(index+3);
String newHtmlString = part1+"http://"+part2;
You can try like this codes.
TextView tv = (TextView) findViewById(R.id.textView1);
String text = "This is just a test. Click this link here Google to visit google.";
tv.setMovementMethod(LinkMovementMethod.getInstance());
tv.setText(Html.fromHtml(text));
reference How to make links in textview clickable in android?

Android: Open alertdialog from part of string?

I have a CheckBox with a string that says "I have read and understood the terms and conditions". Now I want to make the words "terms and conditions" to a link which opens a alertdialog where the terms and conditions can be read. Nothing special.
I'm thinking something in the line of:
<string name="cont_agree">I have read and understood the <a ref="open alertdialog">terms and conditions.</a></string>
Is it possible, and what should I use where it now says "open alertdialog"?
If it can't be done this way, how should I do?
Addition:
To open a url you would use this code:
<string name="cont_agree"><a ref="http://www.stackoverflow.com">Stackoverflow</a></string>
But how do you open a alertdialog, or say another screen, from a string? I have seen apps who does this so it is possible, of course, but how?
EDIT:
This is the code I use for the SpannableStringBuilder:
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(getString(R.string.before));
//Now create a ClickableSpan
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
d.show(); //Here dialog will be displayed
}
};
//Now append the TOS string
text.append(getString(R.string.popup));
//Declare that the "TOS" string is a clickableSpan
text.setSpan(clickableSpan, getString(R.string.before).length(),getString(R.string.before).length()+getString(R.string.popup).length(), 0); //Check on API setSpan method
((CheckBox)findViewById(yourview)).setMovementMethod(LinkMovementMethod.getInstance());
((CheckBox)findViewById(yourview)).setText(text, BufferType.SPANNABLE);
I still get some markers at the first "text.append" line.
Multiple markers at this line:
Return type for the method is missing
Syntax error on token ")", { expected after this token
R.string.before cannot be resolved to a type
Syntax error on token ")", invalid VariableDeclaratorId
Syntax error on token "append", Identifier expected after this token
First setup your dialog
Dialog d = new Dialog(context);
d.setTitle... etcetc
In your values.xml create 2 string
<string name="before">I have read and understood the</string>
<string name="popup">TOS</string</string>
Now you can use SpannableStringBuilder
SpannableStringBuilder text = new SpannableStringBuilder();
text.append(getString(R.string.before));
//Now create a ClickableSpan
ClickableSpan clickableSpan = new ClickableSpan() {
#Override
public void onClick(View view) {
d.show(); //Here dialog will be displayed
}
};
//Now append the TOS string
text.append(getString(R.string.popup));
//Declare that the "TOS" string is a clickableSpan
text.setSpan(clickableSpan, getString(R.string.before).length(), getString(R.string.before).length()+getString(R.string.popup).length(), 0); //Check on API setSpan method
((CheckBox)findViewById(yourview)).setMovementMethod(LinkMovementMethod.getInstance());
((CheckBox)findViewById(yourview)).setText(text, BufferType.SPANNABLE); //AAAAND WE'RE DONE!

Categories

Resources