German unicode letters don't show up in app - android

I have a problem with language encoding... what i try is to incorporate a random motivational string into my app which contains German unicode letters... as far as I know, Java uses Unicode-16, but the respective letters dont show up at all when I start the app. I'm using Android Studio and the app is tested on a real device.
public class Start extends ActionBarActivity {
//This is a string array containing quotes
String[] motivational = {"Unser größter Ruhm ist nicht, niemals zu fallen, sondern jedes Mal wieder aufzustehen.\nRalph Waldo Emerson"};
public int randInt() {
Random rand = new Random();
return rand.nextInt((motivational.length) + 1);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
//Takes a random quote from the list and sets it as a TextViews content
TextView motivator = (TextView) findViewById(R.id.motivator);
motivator.setText(motivational[randInt()]);
}
//rest of the class

Add your text to strings.xml and then use Android's getResources.getString() method to get the text
<resources>
<string name="motivational">Unser größter Ruhm ist nicht, niemals zu fallen, sondern jedes Mal wieder aufzustehen.\nRalph Waldo Emerson</string>
</resources>
Then in your java file, use
String motivational = getResources().getString(R.string.motivational);
TextView motivator = (TextView) findViewById(R.id.motivator);
motivator.setText(motivational);
Retrieving the value from strings.xml is done using
getResources().getString(R.string.motivational)
where R.string.motivational is the unique string identifier.
Isn't this the output you are looking for?

Related

How to format and style (Bold, TextSize) string resource in Android

Above is the image of what I want to achieve using String.xml
There are three things
'76' & '20' will be replaced dynamically using String.format
'20' should be bold
'20' should be bigger in size
I have tried all the solutions using Html.fromHtml class.
Following are the solutions which I have tried. I am able to make '20' bold but couldn't make the '20' bigger in size.
Following are the differet variations of String.xml which I have tried
<string name="points_data">Use %1$d points= <font size="30">₹ %2$d</font> in payment</string>
<string name="points_data">Use %1$d points= <font size="14"><b>₹ %2$d</b></font> in payment</string>
<string name="points_data">Use %1$d points= <font size="14"><b>₹ %2$d</b></font> in payment</string>
<string name="points_data"><![CDATA[Use %1$d points= <font size="60"><b>₹ %2$d</b></font> in payment]]></string>
<string name="points_data">Use %1$d points= <b><span style="fontSize='50'">₹ %2$d</span></b> in payment</string>
Following is the method I use for parsing above string
val formattedText = String.format(getString(R.string.points_data), 76, 20)
textViewPoints.text = HtmlCompat.fromHtml(formattedText, HtmlCompat.FROM_HTML_MODE_LEGACY)
I have came across following links while googling for solution but none of them is working for my case.
https://developer.android.com/guide/topics/resources/string-resource
Set TextView style (bold or italic)
Html.fromHtml deprecated in Android N
I have tried all the possible solutions which I could think of but none of them is working. I don't know what I am missing to implement. If anyone knows how to achieve this scenarion or knows about a way to achieve this please provide some guidance regarding that.
You don't need any html formatting, so you only need plain text in string resources, like this:
<string name="points_data">Use %1$d points= ₹%2$d in payment</string>
You can use a SpannableString, to format the 2nd parameter of your string resource.
Both "%1$d" and "%2$d" will be just placeholders, so don't use String.format() in this case:
val param1 = 20.toString()
val param2 = 70.toString()
var str = getString(R.string.points_data).replace("%1\$d", param1)
val index = str.indexOf("%2\$d")
val len = param2.length
str = str.replace("%2\$d", param2)
val sp = SpannableString(str)
sp.setSpan(StyleSpan(Typeface.BOLD), index, index + len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
sp.setSpan(RelativeSizeSpan(1.5f), index, index + len, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)
Now if you want to set the text of a TextView:
tv.text = sp
The size of the text can be altered by changing 1.5f, which is relative to the original size.
You can also use SpannableStringBuilder to achieve your required output
SAMPLE CODE
public class MainActivity extends AppCompatActivity {
TextView tvTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.tvTextView);
setSpan("76", "20");
}
public void setSpan(String priceOne, String priceTwo) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder("Use ");
spannableStringBuilder.append(priceOne);
SpannableString text = new SpannableString("$" + priceTwo);
text.setSpan(new RelativeSizeSpan(1.5f), 0, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(" Points =");
spannableStringBuilder.append(text);
spannableStringBuilder.append(" in Payment");
tvTextView.setText(spannableStringBuilder);
}
}
OUTPUT
UPDATE
as per your below comment
Yes. I could use this but my application also supports Hindi language. And for these localization scenario, I think, using SpannableStringBuilder would be some what difficult to manage
Than add your strings in res/values/string.xml like this
<resources>
<string name="app_name"> Demo App</string>
<string name="search">Search</string>
<string name="str_use">Use</string>
<string name="str_points">Points =</string>
<string name="str_payment">in Payment</string>
</resources>
Than use like this
public class MainActivity extends AppCompatActivity {
TextView tvTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvTextView = findViewById(R.id.tvTextView);
setSpan("76", "20");
}
public void setSpan(String priceOne, String priceTwo) {
SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(getString(R.string.str_use));
spannableStringBuilder.append(priceOne);
SpannableString text = new SpannableString("$" + priceTwo);
text.setSpan(new RelativeSizeSpan(1.5f), 0, text.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
spannableStringBuilder.append(getString(R.string.str_points));
spannableStringBuilder.append(text);
spannableStringBuilder.append(getString(R.string.str_payment));
tvTextView.setText(spannableStringBuilder);
}
}

Parameter in strings.xml does't work

I don't understand this anymore.
I try to write a TextView
android:text="#string/dbVer"
define in strings.xml
<string name="dbVer">db %1$s</string>
and in Activity
int dbTag = Integer.parseInt(yearDay.format(new Date(new File(databasePath + "/ean_database.db").lastModified())));
String dbVer = String.format(getString(R.string.dbVer), dbTag );
The TextView is still showing: db %1$s
The nearest answer I found: Are parameters in strings.xml possible? is similar but in fact something is wrong for me.
It looks like you are getting the result "db %1$s" because you are creating a string and assigning that as its value in the strings.xml file between these ><. What are you trying to have it show instead?
android:text="#string/dbVer"
This refers to your format string and displays the raw format string you're seeing.
int dbTag = Integer.parseInt(yearDay.format(new Date(new File(databasePath + "/ean_database.db").lastModified())));
String dbVer = String.format(getString(R.string.dbVer), dbTag );
This creates a new string dbVer using the format string from resources.
What is missing is that you need to set this new string as your TextView's text:
TextView tv = (TextView)findViewById(R.id.your_textview_id); // assuming an activity
tv.setText(dbVer);

Localization of code generated natural language strings

I'm writing an app in which I want to display a string, describing an object in my model, to the user. I've started thinking about localization and I'm a bit stumped as to the best approach to deal with the difference in grammar between languages.
Imagine if in my model I have a verb an object and a quantity (pseudocode):
int _quantity = 6;
String _object = "#string/object";
String _verb = "#string/verb";
This should render in English as _verb + _quantity + _object (i.e. "eat 6 eggs", whereas in German it should render as _quantity + _object + _verb (i.e. "6 eggs eat" (but, obviously, using German word tokens rather than English :) ))
Is there a standard approach to this type of problem in Android?
Thanks.
OK, I've come up with a solution which, based on what I know, is the best I can find. If anyone has a better solution, please post!
1) In strings.xml, define any bits of text needed (for me, these equated to the localised names for enumeration members and for the string used to build natural language strings (more on this in a bit))
Example:
<resources>
...
<string name="verb_ate">ate</string>
<string name="verb_threw">threw</string>
...
<string name="modelobject_naturallanguagedescription">I {0} {1} {2}</string>
...
</resources>
2) In any enumerations, decorate them with the resource ids of the strings they are to use for display
Example:
public enum VerbType
Ate(R.string.verb_ate),
Threw(R.string.verb_threw);
private final int _stringID;
private VerbType(int stringID) {
_stringID = stringID;
}
public int getStringID() {
return _stringID;
}
}
3) Make a helper function which will take the model object and the context and will piece together the required natural language string (using java.text.MessageFormat), plus a helper function for each enumeration:
Example (assume that ModelObject has _verb, _quantity, _object and relevant getters):
public static String getVerb(VerbType v, Context c) {
return c.getResources().getString(v.getStringID());
}
public static String getNaturalLanguageString(ModelObject o, Context c) {
MessageFormat mf = new MessageFormat(c.getResources().getString(R.string.modelobject_naturallanguagedescription);
return mf.format(new Object[] {getVerb(o.getVerb(),c), o.getQuantity(), o.getObject()});
}
So, having done all of this, it's easy enough to define another strings file for a different language (German for example (I don't know German, so the language won't be correct)):
<resources>
...
<string name="verb_ate">gegessen</string>
<string name="verb_threw">gethrown</string>
...
<string name="modelobject_naturallanguagedescription">Ich haben {1} {2} {0}</string>
...
</resources>
So, in an english locale getNaturalLanguageString might return:
I ate 6 eggs
whereas in a German locale it might return:
Ich haben 6 eggs gegessen

eclipse android setText to random String

Hello I have 2000 Questions each with 3 possible answers in my Strings.xml. I want that a random question is displayed in the textview with is answers.
<string name="Frage1">Was versteht man unter defensivem Fahren?</string>
<string name="ersteAntwort1">Nicht auf dem eigenen Recht bestehen</string>
<string name="zweiteAntwort1">Mit Fehlern anderer rechnen</string>
<string name="dritteAntwort1">Vorsorglich an jeder Kreuzung anhalten</string>
<string name="Frage2">Was kann zu Auffahrunfällen führen?</string>
<string name="ersteAntwort2">Unerwartet starkes Bremsen</string>
<string name="zweiteAntwort2">Unaufmerksamkeit</string>
<string name="dritteAntwort2">Zu dichtes Auffahren</string>
<string name="Frage3">Sie fahren innerorts hinter einem Fahrzeug mit ortsfremdem Kennzeichen. Was könnte geschehen?</string>
<string name="ersteAntwort3">- bremst unerwartet</string>
<string name="zweiteAntwort3">- betätigt den Blinker vor dem Abbiegen zu spät</string>
<string name="dritteAntwort3">- hält unerwartet an, um nach dem Weg zu fragen</string>
The names of the Strings are always the same only the number of the question changes so i want to add a random number to the first part of the string name
public void neueFrage (View view) {
Button buttonTipp = (Button)findViewById(R.id.button1);
final TextView tw = (TextView)findViewById(R.id.textView1);
final CheckBox Chk1 = (CheckBox)findViewById(R.id.checkBox1);
final CheckBox Chk2 = (CheckBox)findViewById(R.id.checkBox2);
final CheckBox Chk3 = (CheckBox)findViewById(R.id.checkBox3);
buttonTipp.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
int random = (int) (Math.random() *3 );
String zahl = String.valueOf(random);
String question = "Frage"+zahl;
String firstAnswer ="ersteAntwort"+zahl;
String secondAnswer = "zweiteAntwort"+zahl;
String thirdAnswer = "dritteAntwort"+zahl;
tw.setText(R.string.question);
Chk1.setText(R.string.firstAnswer);
Chk1.setText(R.string.secondAnswer);
Chk1.setText(R.string.thirdAnswer);
}});
}
First of all, if you can, write the data in an appropriate format. XML would be a good choice, you could create your own XML format and read it. An example XML format could be as follows, Android does include some excellent parsers as well.
<questions_list>
<question name="Question 1?">
<answer name="Answer 1"/>
<answer name="Answer 2">
<correct/>
</answer>
<answer name="Answer 3"/>
</question>
</question_list>
If that doesn't work, maybe a String Array could work, like this:
<string-array name="question1">
<item>Question 1</item>
<item>Answer 1</item>
...
</string-array>
A third option would be to put the data into a SQLite database, probably with 5 columns, question, 3 answers, and the correct answer. There's a lot out there on how to do this, the easiest way is to use a language like Python to populate the database, then use something like SQLiteAssetHelper to put the database in to your program.
I think re-formatting will save you considerable work. XML, a database, or something else, but I'm sure a better format would help you considerably.
As it stands, you would have to reference not only the questions directly in the code, but also the answers. The tool simply isn't meant to be used the way you're using it.

How do I write a random quote generator in Java for Android?

I am very new to Java for Android, and am basically just a noob trying to make a few basic apps for a HTC phone. So far, mainly by copying code, I've written apps that will write "Hello, World", print a random number and display a picture, and these have worked nicely on my phone.
I would now like to combine what I've done and write an app that will generate a random quote from a specified list and print it on the screen. A refresh button would be nice, too.
I looked at these links first as a starting point:
Forrst
Stack Overflow
However, I think I'm going in circles now by trying to combine the two. I started off by making an array of the quotes, generating a random number and assigning it to the quote, then trying to get the tv.setText method to write it.
Any help gratefully received! Thank you!
This is what I have so far:
package com.Me;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.util.Random;
public class QuoteActivity extends Activity {
int numQuotes = 10;
String[] quotes = new String[numQuotes] {"John", "Mary", "Bob"};
String randomQuote = quotes[Math.floor(Math.random() * numQuotes)];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Make a new text view passing Activity object
TextView tv = new TextView(this);
//Set a text into view
tv.setText(randomQuote);
//set the view into activity view container
setContentView(tv);
}
}
Ok, some basic stuff first: you're not assigning numbers to the quotes, you're using the random number to index the quotes array. With that said, something like this would do the trick:
String[] quotes = new String[] {"q1", "q2", "q3"};
String randomQuote = quotes[(int) (Math.random() * quotes.length)];
Please note that you cannot both set the size of an array and initialize it at the same time. I.e. either you do like above, or you do something like:
int numQuotes = 3;
String[] quotes = new String[numQuotes];
quotes[0] = "q1";
quotes[1] = "q2";
quotes[2] = "q3";
I see a couple of errors in your code:
You init an array either by
String[] quotes = new String[]{"1", "2", "3"};
or
String[] quotes = new String[3];
quotes[0] = "1";
quotes[1] = "2";
quotes[2] = "3";
The Math.floor() and Math.random() return double, and you should access array elements with ints. You should cast to int. You don't actually need floor() because random() returns positive value.
You will get an exception if you try to access an array element that is not there. If you have array with 3 elements and math.random()*10 gives you 4 - you will crash.
I suggest:
int randomElemenetIndex = (int) (Math.random() * 10) % 3; //This way you will have 0, 1 or 2
...
tv.setText(quotes[randomElementIndex]);

Categories

Resources