Restrict the change of the text in English when I change the locale and apply the Font of the entire application in android - android-fonts

I am trying to apply font for my entire application which is having support of multiple indian languages. i am applying the code given below for on or below lollipop.
public void setDefaultAppFont(String fontAssetName)
{
if (Build.VERSION.SDK_INT >= 21)
{
Map newMap = new HashMap();
final String typefaceFieldName = "sans-serif";
newMap.put(typefaceFieldName, Typeface.createFromAsset(appInstance.getAssets(), fontAssetName));
try
{
final Field staticField = Typeface.class.getDeclaredField("sSystemFontMap");
staticField.setAccessible(true);
staticField.set(null, newMap);
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
else
{
Typeface typeface = Typeface.createFromAsset(appInstance.getAssets(), fontAssetName);
try
{
Field staticField = Typeface.class.getDeclaredField("DEFAULT");
staticField.setAccessible(true);
staticField.set(null, typeface);
staticField = Typeface.class.getDeclaredField("DEFAULT_BOLD");
staticField.setAccessible(true);
staticField.set(null, typeface);
staticField = Typeface.class.getDeclaredField("SANS_SERIF");
staticField.setAccessible(true);
staticField.set(null, typeface);
staticField = Typeface.class.getDeclaredField("SERIF");
staticField.setAccessible(true);
staticField.set(null, typeface);
staticField = Typeface.class.getDeclaredField("MONOSPACE");
staticField.setAccessible(true);
staticField.set(null, typeface);
}
catch (NoSuchFieldException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
Above code allows us to change default english font on or below lollipop devices, but then it is unable to render default english letters coming from strings file and starts converting these english letters into non-english language letters automatically when non-english language is selected by user.
For Example :
I am using a spinner in my application that is having ten language options like, English(Written in english alphabets), Kannada(Written is kannada alphabets), Marathi(Written in marathi alphabets), Gujarati(Written in gujarati alphabets) etc. if user selects a perticular option from that spinner, the whole app language and font changes. It also changes the English(Written in english alphabets) in spinner that should not allowed to be changed in other languages even if user selects any language option.

Related

Match and extract special word in Dart

I tried to manipulate a text to match and extract special or some words in Dart. For example:
I want to check matching of words ends with a given word
String oldText = "website or show me to";
String newText = "show me to tell";
if (oldText.trim().endsWith(newText.trim())) {
final extractText = oldText.trim().substring(newText.length);
print(extractText);
} else {
print("Not matched");
}
I want to extract only word - "tell" so how can I do it? Need to use Regular expression?
Take a look here. I've implemented a regex which will check that tell is followed by end of line $. The regex is probably easier than any other method you might try, plus it's easy to change if conditions change.
void main() {
String oldText = "website or show me to";
String newText = "show me to tell";
RegExp parser = RegExp(r"tell$");
if (parser.hasMatch(oldText)) {
print(parser.stringMatch(oldText).toString());
} else {
print("Not matched");
}
if (parser.hasMatch(newText)) {
print(parser.stringMatch(newText).toString());
} else {
print("Not matched");
}
}
And here is an example where I have removed the check to a function and also set it up so that you can dynamically generate the regex:
void main() {
String oldText = "website or show me to";
String newText = "show me to tell";
String test = "tell";
RegExp parser = RegExp(test+r"$");
print(checkMatch(oldText, parser));
print(checkMatch(newText, parser));
}
checkMatch(text, parser) {
if (parser.hasMatch(text)) {
return(parser.stringMatch(text).toString());
} else {
return("Not matched");
}
}

How to display data (which has just been inserted in database) in a TextView?

The attached photo is a representation of my layout.I need to enter the first and last name in the EditTexts. And by pressing the Insert Button, the info is saved to the database. (This part I managed to do) However, on clicking the Show button, the entered input is to be displayed in the TextView which consists of the firstname & lastname. Attached photo
to upload your data into remote database you can use this code
//enregistrement des donnees dans la base de donnees
WebClient client = new WebClient();
Uri uri = new Uri("http://test.com/login.php");
NameValueCollection parameters = new NameValueCollection();
parameters.Add("Email", email);
parameters.Add("Password", password);
client.UploadValuesCompleted += Client_UploadValuesCompleted;
client.UploadValuesAsync(uri, parameters);
it will generate this method
private void Client_UploadValuesCompleted(object sender, UploadValuesCompletedEventArgs e)
{
if (Encoding.UTF8.GetString(e.Result) == "success!!!")
{
Toast.MakeText(this, "success!!!", ToastLength.Long).Show();
}
else if (Encoding.UTF8.GetString(e.Result) == "failed!!!")
{
Toast.MakeText(this, "failed!!!", ToastLength.Long).Show();
}
}
and to retrieve your data you can use code
articles = new JavaList<ModelArticle>();
mWebClient = new WebClient();
mUrl = new Uri(urlAddress);
mWebClient.DownloadDataAsync("your url");
mWebClient.DownloadDataCompleted += MWebClient_DownloadDataCompleted;
it will generate this method
private void MWebClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
RunOnUiThread(() =>
{
try
{
string json = Encoding.UTF8.GetString(e.Result);
articles = JsonConvert.DeserializeObject<JavaList<ModelArticle>>(json);
}
catch (Exception exception)
{
Toast.MakeText(this, " Vueillez verifier votre connexion a internet puis reessayer ", ToastLength.Short).Show();
}
});
}
now your result is in the javalist articles don't forget to create a model of your json result

I am not able to parse IOS driver page source

I got Page source using
String pageSource = driver.getPageSource();
Now i need to save this xml file to local in cache. So i need to get element attributes like x and y attribute value rather than every time get using element.getAttribute("x");. But I am not able to parse pageSource xml file to some special character. I cannot remove this character because at if i need element value/text it shows different text if i will remove special character. Appium is use same way to do this.
I was also facing same issue and i got resolution using below code which i have written and it works fine
public static void removeEscapeCharacter(File xmlFile) {
String pattern = "(\\\"([^=])*\\\")";
String contentBuilder = null;
try {
contentBuilder = Files.toString(xmlFile, Charsets.UTF_8);
} catch (IOException e1) {
e1.printStackTrace();
}
if (contentBuilder == null)
return;
Pattern pattern2 = Pattern.compile(pattern);
Matcher matcher = pattern2.matcher(contentBuilder);
StrBuilder sb = new StrBuilder(contentBuilder);
while (matcher.find()) {
String str = matcher.group(1).substring(1, matcher.group(1).length() - 1);
try {
sb = sb.replaceFirst(StrMatcher.stringMatcher(str),
StringEscapeUtils.escapeXml(str));
} catch (Exception e) {
e.printStackTrace();
}
}
try {
Writer output = null;
output = new BufferedWriter(new FileWriter(xmlFile, false));
output.write(sb.toString());
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if you will get that kind of problem then catch it with remove special character and parse again.
try {
doc = db.parse(fileContent);
} catch (Exception e) {
removeEscapeCharacter(file);
doc = db.parse(file);
}
It might works for you.
I can able to do same using SAXParser and add handler to do for this.
Refer SAX Parser

twitter page not in english error

I am using the code -
BrowserContentManager browserMngr = new BrowserContentManager(0);
RenderingOptions rendOptions = browserMngr.getRenderingSession().getRenderingOptions();
rendOptions.setProperty(RenderingOptions.CORE_OPTIONS_GUID,RenderingOptions.SHOW_IMAGES_IN_HTML,false);
add(browserMngr);
BrowserContentManagerOAuthDialogWrapper pageWrapper =new BrowserContentManagerOAuthDialogWrapper(browserMngr);
pageWrapper.setConsumerKey("my key");
pageWrapper.setConsumerSecret("my secret");
pageWrapper.setCallbackUrl("https://twitter.com");
try {
pageWrapper.login();
}
catch (Exception e) {
System.out.println("error: "+e.getMessage());
}
This is for Twitter login.The language of the Browser Screen is not in English. So how to change it to English ?.

Issue in Invoking camera and saving images in SD card

In my task I have to invoke camera in a button click and take picture and have to save it and display the image in the same screen. I have tried it and succeed in emulator. but its not working in real device. getting some errors. tried a lot. but cant able to find out the issue. more over, Its working perfectly in 9700 emulator and showing some error in 9500.
public class CameraScreen extends MainScreen implements FieldChangeListener
{
/** The camera's video controller */
private VideoControl _videoControl;
private Field _videoField;
private EncodingProperties[] _encodings;
private int _indexOfEncoding = 0;
private static String FILE_NAME = System.getProperty("fileconn.dir.photos")+"IMAGE"; //"file:///SDCard/" + "myphotos/" + "IMAGE";//
private static String EXTENSION = ".bmp";
private static int _counter;
int flag = 0;
BitmapField imageField = new BitmapField();
HorizontalFieldManager menuBar = new HorizontalFieldManager(Field.USE_ALL_WIDTH);
VerticalFieldManager main_vfm = new VerticalFieldManager();
VerticalFieldManager camera_vfm = new VerticalFieldManager();
VerticalFieldManager image_vfm = new VerticalFieldManager();
ButtonField bt = new ButtonField("Click",ButtonField.CONSUME_CLICK);
ButtonField front_bt = new ButtonField("Front",ButtonField.CONSUME_CLICK);
ButtonField back_bt = new ButtonField("Back",ButtonField.CONSUME_CLICK);
ButtonField side1_bt = new ButtonField("Side 1",ButtonField.CONSUME_CLICK);
ButtonField side2_bt = new ButtonField("Side 2",ButtonField.CONSUME_CLICK);
public CameraScreen()
{
setTitle("First Screen");
bt.setChangeListener(this);
front_bt.setChangeListener(this);
back_bt.setChangeListener(this);
side1_bt.setChangeListener(this);
side2_bt.setChangeListener(this);
image_vfm.add(menuBar);
menuBar.add(front_bt);
menuBar.add(back_bt);
menuBar.add(side1_bt);
menuBar.add(side2_bt);
image_vfm.add(bt);
try {
Bitmap image = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
imageField.setBitmap(image);
image_vfm.add(imageField);
} catch(Exception e) {
System.out.println(e.toString());
}
main_vfm.add(image_vfm);
add(main_vfm);
front_bt.setFocus();
// Initialize the camera object and video field
initializeCamera();
// Initialize the list of possible encodings
initializeEncodingList();
// If the field was constructed successfully, create the UI
if(_videoField != null)
{
createUI();
}
// If not, display an error message to the user
else
{
camera_vfm.add( new RichTextField( "Error connecting to camera." ) );
}
}
/**
* Takes a picture with the selected encoding settings
*/
public void takePicture()
{
try
{
// A null encoding indicates that the camera should
// use the default snapshot encoding.
String encoding = null;
if( _encodings != null )
{
// Use the user-selected encoding
encoding = _encodings[_indexOfEncoding].getFullEncoding();
}
// Retrieve the raw image from the VideoControl and
// create a screen to display the image to the user.
createImageScreen( _videoControl.getSnapshot( encoding ) );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Prevent the save dialog from being displayed
* #see net.rim.device.api.ui.container.MainScreen#onSavePrompt()
*/
protected boolean onSavePrompt()
{
return true;
}
/**
* Initializes the Player, VideoControl and VideoField
*/
private void initializeCamera()
{
try
{
// Create a player for the Blackberry's camera
Player player = Manager.createPlayer( "capture://video" );
// Set the player to the REALIZED state (see Player javadoc)
player.realize();
// Grab the video control and set it to the current display
_videoControl = (VideoControl)player.getControl( "VideoControl" );
if (_videoControl != null)
{
// Create the video field as a GUI primitive (as opposed to a
// direct video, which can only be used on platforms with
// LCDUI support.)
_videoField = (Field) _videoControl.initDisplayMode (VideoControl.USE_GUI_PRIMITIVE, "net.rim.device.api.ui.Field");
_videoControl.setDisplayFullScreen(true);
//_videoControl.setDisplaySize(50, 50);
_videoControl.setVisible(true);
}
// Set the player to the STARTED state (see Player javadoc)
player.start();
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
}
}
/**
* Initialize the list of encodings
*/
private void initializeEncodingList()
{
try
{
// Retrieve the list of valid encodings
String encodingString = System.getProperty("video.snapshot.encodings");
// Extract the properties as an array of word
String[] properties = StringUtilities.stringToKeywords(encodingString);
// The list of encodings
Vector encodingList = new Vector();
//Strings representing the four properties of an encoding as
//returned by System.getProperty().
String encoding = "encoding";
String width = "width";
String height = "height";
String quality = "quality";
EncodingProperties temp = null;
for(int i = 0; i < properties.length ; ++i)
{
if( properties[i].equals(encoding))
{
if(temp != null && temp.isComplete())
{
// Add a new encoding to the list if it has been
// properly set.
encodingList.addElement( temp );
}
temp = new EncodingProperties();
// Set the new encoding's format
++i;
temp.setFormat(properties[i]);
}
else if( properties[i].equals(width))
{
// Set the new encoding's width
++i;
temp.setWidth(properties[i]);
}
else if( properties[i].equals(height))
{
// Set the new encoding's height
++i;
temp.setHeight(properties[i]);
}
else if( properties[i].equals(quality))
{
// Set the new encoding's quality
++i;
temp.setQuality(properties[i]);
}
}
// If there is a leftover complete encoding, add it.
if(temp != null && temp.isComplete())
{
encodingList.addElement( temp );
}
// Convert the Vector to an array for later use
_encodings = new EncodingProperties[ encodingList.size() ];
encodingList.copyInto((Object[])_encodings);
}
catch (Exception e)
{
// Something is wrong, indicate that there are no encoding options
_encodings = null;
home.errorDialog(e.toString());
}
}
/**
* Adds the VideoField to the screen
*/
private void createUI()
{
// Add the video field to the screen
camera_vfm.add(_videoField);
}
/**
* Create a screen used to display a snapshot
* #param raw A byte array representing an image
*/
private void createImageScreen( byte[] raw )
{
main_vfm.replace(camera_vfm, image_vfm);
fieldChanged(raw);
Bitmap image1 = Bitmap.createBitmapFromBytes( readFile(),0, -1, 5 );
try{
if(flag == 1){
}
else{
image_vfm.delete(imageField);
}
imageField.setBitmap(image1);
image_vfm.add(imageField);
}
catch(Exception e){System.out.println(e.toString());}
}
private byte[] readFile() {
byte[] result = null;
FileConnection fconn = null;
try {
fconn = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
} catch (IOException e) {
System.out.print("Error opening file");
}
if (!fconn.exists()) {
//Dialog.inform("file not exist");
} else {
InputStream in = null;
ByteVector bytes = new ByteVector();
try {
in = fconn.openInputStream();
} catch (IOException e) {
System.out.print("Error opening input stream");
}
try {
int c = in.read();
while (-1 != c) {
bytes.addElement((byte) c);
c = in.read();
}
result = bytes.getArray();
} catch (IOException e) {
System.out.print("Error reading input stream");
}
try {
fconn.close();
} catch (IOException e) {
System.out.print("Error closing file");
}
}
return result;
}
public void fieldChanged( final byte[] _raw )
{
try
{
flag ++;
// Create the connection to a file that may or
// may not exist.
FileConnection file = (FileConnection)Connector.open(FILE_NAME + "_front" + EXTENSION);
// If the file exists, increment the counter until we find
// one that hasn't been created yet.
if (file.exists()) {
file.delete();
file.close();
file = (FileConnection) Connector.open(FILE_NAME + "_front" + EXTENSION);
}
//FileConnection file_temp = (FileConnection)Connector.open(FILE_NAME + "tempimg" + EXTENSION);
//file_temp.delete();
// We know the file doesn't exist yet, so create it
file.create();
// Write the image to the file
OutputStream out = file.openOutputStream();
out.write(_raw);
// Close the connections
//out.close();
file.close();
//Dialog.inform( "Saved to " + FILE_NAME + "_front" + EXTENSION );
}
catch(Exception e)
{
home.errorDialog("ERROR " + e.getClass() + ": " + e.getMessage());
Dialog.inform( "File not saved this time");
}
}
/**
* Sets the index of the encoding in the 'encodingList' Vector
* #param index The index of the encoding in the 'encodingList' Vector
*/
public void setIndexOfEncoding(int index)
{
_indexOfEncoding = index;
}
/**
* #see net.rim.device.api.ui.Screen#invokeAction(int)
*/
protected boolean invokeAction(int action)
{
boolean handled = super.invokeAction(action);
if(!handled)
{
switch(action)
{
case ACTION_INVOKE: // Trackball click
{
takePicture();
return true;
}
}
}
return handled;
}
public void fieldChanged(Field field, int context) {
// TODO Auto-generated method stub
srn2 screen2 = new srn2();
srn3 screen3 = new srn3();
srn4 screen4 = new srn4();
if(field==bt)
{
main_vfm.replace(image_vfm, camera_vfm);
}
if(field==back_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen2);
}
if(field==side1_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen3);
}
if(field==side2_bt)
{
UiApplication.getUiApplication().popScreen(UiApplication.getUiApplication().getActiveScreen());
UiApplication.getUiApplication().pushScreen(screen4);
}
}
}
Note: This Error displaying first "javax.microedition.media.MediaException: There is already another active Player. Call Player.close() on the existing Player to free up the resources." and camera gets open and when i try to take picture this error displays "Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
After _videoControl.getSnapshot( encoding ) has been called you need to close player (i.e. to call player.close(). And that's exactly what the exception tells about.
However this method of taking images is highly unreliable - you'll not be able to use it for every BB device model. I don't know why RIM put it in SDK samples. By doing that RIM pushes developers to a wrong way. As alishaik786 mentiones a proper method of taking images on BB is using Invoke.invokeApplication(Invoke.APP_TYPE_CAMERA, new CameraArguments()) with a FileSystemJournalListener implementation. Just search on StackOverflow on these for the implementation details. I vaguely recall the implementation is painful (like many other parts on BB), but once done it will work on any device.
you got two error
1."javax.microedition.media.MediaException: There is already another active Player. Call Player.close()
this exception thrown if you try to open camera (player) while another instance of camera is already opened. In your code, you need to define the player object as a class level and must close the player after taking the snapshot (also need to close the player if you push from one screen to another).
2."Error Class Java.lang.ArrayIndexOutOfBoundsException: Index 0>=0"
This error may occur when you access encoding array while encoding array size is zero.
You can ensure this issue by using _videoControl.getSnapshot( null), which take the snapshot in default encoding.
So first insure these issue and reply me.

Resources