This problem happened with my phone (Samsung Galaxy Note 4)
I am using jQuery, I am trying to code such that if a person fill (keyup jquery) value on input, text will spilt into 4 digit number
example : 123412341234 will become 1234-1234-1234
but when i test my code
example : 123412341234
it become
1234-1123-4121-2341-2312-3412-3412-3412-3411-2341-2341-2123-4123-4123-1234-1234-1234
below is my code :
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");
var account_bank_number_new = autoSplit(5, account_bank_number_filter, '-');
$('.debug-mode').html(account_bank_number_new);
}
function autoSplit(number, string, splitChar) {
var stringLength = string.length;
var countNumber = 1;
var newString = '';
for (var i = 0; i <stringLength ; i++) {
if (countNumber == number && string.charAt(i) != splitChar) {
newString = newString+splitChar+string.charAt(i);
countNumber = 2;
continue;
}
newString = newString + string.charAt(i);
countNumber++;
};
return newString;
}
What am I doing wrong?
Hi no sure if you need this but you can do a simple :
var str = "123412341234";
str.replace(/(.{4})/g,"$1-").slice(0,-1);
$(document).ready(function(){
//uncomment if you want do it onload page
//$( "#account_bank_number" ).keyup();
});
//test on click to the input
$( "#account_bank_number" ).click(function() {
$( "#account_bank_number" ).keyup(); //this is a trigger
});
$('#account_bank_number').keyup(function(e){
e.preventDefault();
var account_bank_number = $(this).val();
var account_bank_number_filter = account_bank_number.replace(/-/g, "");//no sure you need it ...
var account_bank_number_new = account_bank_number_filter.replace(/(.{4})/g,"$1-").slice(0,-1);
$('.debug-mode').html(account_bank_number_new);
//adding the value to the input comment if you dont need
this.value = account_bank_number_new;
});
.debug-mode{background-color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input id="account_bank_number" type="text" value="1234123412341234"/>
<div class="debug-mode"></div>
Simple regex "." is the string. "{4}" is the number to cut the string every 4 characters. "$1-" is the pattern. "$1" is the new string cutting and the "-" at this end is the character being added and the slice is for deleting the last characters added by your replace function. Regards
Related
My google chart is not aligned in the center of my android emulator screen. When activity loads up, I get this:
How can I put the chart in the center of the screen? I tried some css, and xml solutions found on stack but they brought no result.
Here is the code I used:
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'ITEM');
data.addColumn('number', 'VALUE');
data.addRows([
[Android.getName(0), Android.getPoint(0)],
[Android.getName(1), Android.getPoint(1)],
[Android.getName(2), Android.getPoint(2)],
[Android.getName(3), Android.getPoint(3)],
[Android.getName(4), Android.getPoint(4)]
]);
// Set chart options
var options = {'title':'You Have a GREAT Music Taste',
pieHole: 0.4,
width: '100%',
height: '750'
};
// Instantiate and draw our chart, passing in some options.
var chart = new
google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, options);
google.visualization.events.addListener(chart, 'select', selectHandler);
function selectHandler() {
var selection = chart.getSelection();
var message = '';
for (var i = 0; i < selection.length; i++) {
var item = selection[i];
if (item.row != null && item.column != null) {
var str = data.getFormattedValue(item.row, item.column);
message += '{row:' + item.row + ',column:' + item.column + '} = '
+ str + '\n';
} else if (item.row != null) {
var str = data.getFormattedValue(item.row, 0);
message += '{row:' + item.row + ', column:none}; value (col 0) = '
+ str + '\n';
} else if (item.column != null) {
var str = data.getFormattedValue(0, item.column);
message += '{row:none, column:' + item.column + '}; value (row 0)
= ' + str + '\n';
}
}
if (message == '') {
message = 'nothing';
}
Android.sendData('You selected ' + message);
}
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div" style="width:500; height:500"></div>
</body>
</html>
i need to change the text="font roboto regular" to Font Roboto Regular in xml itself, how to do?
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:textSize="18sp"
android:textColor="#android:color/black"
android:fontFamily="roboto-regular"
android:text="font roboto regular"
android:inputType="textCapWords"
android:capitalize="words"/>
If someone looking for kotlin way of doing this, then code becomes very simple and beautiful.
yourTextView.text = yourText.split(' ').joinToString(" ") { it.capitalize() }
You can use this code.
String str = "font roboto regular";
String[] strArray = str.split(" ");
StringBuilder builder = new StringBuilder();
for (String s : strArray) {
String cap = s.substring(0, 1).toUpperCase() + s.substring(1);
builder.append(cap + " ");
}
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText(builder.toString());
Try this...
Method that convert first letter of each word in a string into an uppercase letter.
private String capitalize(String capString){
StringBuffer capBuffer = new StringBuffer();
Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
while (capMatcher.find()){
capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
}
return capMatcher.appendTail(capBuffer).toString();
}
Usage:
String chars = capitalize("hello dream world");
//textView.setText(chars);
System.out.println("Output: "+chars);
Result:
Output: Hello Dream World
KOTLIN
val strArrayOBJ = "Your String".split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()
val builder = StringBuilder()
for (s in strArrayOBJ) {
val cap = s.substring(0, 1).toUpperCase() + s.substring(1)
builder.append("$cap ")
}
txt_OBJ.text=builder.toString()
Modification on the accepted answer to clean out any existing capital letters and prevent the trailing space that the accepted answer leaves behind.
public static String capitalize(#NonNull String input) {
String[] words = input.toLowerCase().split(" ");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < words.length; i++) {
String word = words[i];
if (i > 0 && word.length() > 0) {
builder.append(" ");
}
String cap = word.substring(0, 1).toUpperCase() + word.substring(1);
builder.append(cap);
}
return builder.toString();
}
you can use this method to do it programmatically
public String wordFirstCap(String str)
{
String[] words = str.trim().split(" ");
StringBuilder ret = new StringBuilder();
for(int i = 0; i < words.length; i++)
{
if(words[i].trim().length() > 0)
{
Log.e("words[i].trim",""+words[i].trim().charAt(0));
ret.append(Character.toUpperCase(words[i].trim().charAt(0)));
ret.append(words[i].trim().substring(1));
if(i < words.length - 1) {
ret.append(' ');
}
}
}
return ret.toString();
}
refer this if you want to do it in xml.
You can use
private String capitalize(final String line) {
return Character.toUpperCase(line.charAt(0)) + line.substring(1);
}
refer this How to capitalize the first character of each word in a string
android:capitalize is deprecated.
Follow these steps: https://stackoverflow.com/a/31699306/4409113
Tap icon of ‘Settings’ on the Home screen of your Android Lollipop
Device
At the ‘Settings’ screen, scroll down to the PERSONAL section and
tap the ‘Language & input’ section.
At the ‘Language & input’ section, select your keyboard(which is
marked as current keyboard).
Now tap the ‘Preferences’.
Tap to check the ‘Auto – Capitalization’ to enable it.
And then it should work.
If it didn't, i'd rather to do that in Java.
https://stackoverflow.com/a/1149869/2725203
Have a look at ACL WordUtils.
WordUtils.capitalize("your string") == "Your String"
Another approach is to use StringTokenizer class. The below method works for any number of words in a sentence or in the EditText view. I used this to capitalize the full names field in an app.
public String capWordFirstLetter(String fullname)
{
String fname = "";
String s2;
StringTokenizer tokenizer = new StringTokenizer(fullname);
while (tokenizer.hasMoreTokens())
{
s2 = tokenizer.nextToken().toLowerCase();
if (fname.length() == 0)
fname += s2.substring(0, 1).toUpperCase() + s2.substring(1);
else
fname += " "+s2.substring(0, 1).toUpperCase() + s2.substring(1);
}
return fname;
}
in kotlin, string extension
fun String?.capitalizeText() = (this?.toLowerCase(Locale.getDefault())?.split(" ")?.joinToString(" ") { if (it.length <= 1) it else it.capitalize(Locale.getDefault()) }?.trimEnd())?.trim()
Kotlin extension function for capitalising each word
val String?.capitalizeEachWord
get() = (this?.lowercase(Locale.getDefault())?.split(" ")?.joinToString(" ") {
if (it.length <= 1) it else it.replaceFirstChar { firstChar ->
if (firstChar.isLowerCase()) firstChar.titlecase(
Locale.getDefault()
) else firstChar.toString()
}
}?.trimEnd())?.trim()
As the best way for achieving this used to be the capitalize() fun, but now it got depricated in kotlin. So we have an alternate for this. I've the use case where I'm getting a key from api that'll be customized at front end & will be shown apparently. The value is coming as "RECOMMENDED_OFFERS" which should be updated to be shown as "Recommended Offers".
I've created an extension function :
fun String.updateCapitalizedTextByRemovingUnderscore(specialChar: String): String
that takes a string which need to be replaced with white space (" ") & then customise the words as their 1st character would be in caps. So, the function body looks like :
fun String.updateCapitalizedTextByRemovingUnderscore(
specialChar: String = "") : String {
var tabName = this
// removing the special character coming in parameter & if
exist
if (spclChar.isNotEmpty() && this.contains(specialChar)) {
tabName = this.replace(spclChar, " ")
}
return tabName.lowercase().split(' ').joinToString(" ") {
it.replaceFirstChar { if (it.isLowerCase())
it.titlecase(Locale.getDefault()) else it.toString() } }
}
How to call the extension function :
textView.text =
"RECOMMENDED_OFFERS".updateCapitalizedTextByRemovingUnderscore("_")
OR
textView.text = <api_key>.updateCapitalizedTextByRemovingUnderscore("_")
The desired output will be :
Recommended Offers
Hope this will help.Happy coding :) Cheers!!
capitalize each word
public static String toTitleCase(String string) {
// Check if String is null
if (string == null) {
return null;
}
boolean whiteSpace = true;
StringBuilder builder = new StringBuilder(string); // String builder to store string
final int builderLength = builder.length();
// Loop through builder
for (int i = 0; i < builderLength; ++i) {
char c = builder.charAt(i); // Get character at builders position
if (whiteSpace) {
// Check if character is not white space
if (!Character.isWhitespace(c)) {
// Convert to title case and leave whitespace mode.
builder.setCharAt(i, Character.toTitleCase(c));
whiteSpace = false;
}
} else if (Character.isWhitespace(c)) {
whiteSpace = true; // Set character is white space
} else {
builder.setCharAt(i, Character.toLowerCase(c)); // Set character to lowercase
}
}
return builder.toString(); // Return builders text
}
use String to txt.setText(toTitleCase(stringVal))
don't use android:fontFamily to roboto-regular. hyphen not accept. please rename to roboto_regular.
To capitalize each word in a sentence use the below attribute in xml of that paticular textView.
android:inputType="textCapWords"
In Phonegap I try to fetch the contact list from phone.I need just name and phone number , its taking around 40 seconds to fetch all the result.I add the plugin in config.xml .In my phone I have around only 400 contacts. But when I alert the length of contact in index.html it says that 1351 list.I don't know where I am wrong.I think some optimization is needed while fetching name and number from phone.
advance Thanks...:)
Config.xml
<feature name="Contacts">
<param name="android-package" value="org.apache.cordova.contacts.ContactManager" />
</feature>
index.html
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
filter = ["displayName", "phoneNumbers"];
navigator.contacts.find(filter, onSuccess, onError, options);
}
var cSort = function(a, b) {
aName = a.displayName ;
bName = b.displayName ;
return aName < bName ? -1 : (aName == bName ? 0 : 1);
};
function onSuccess(contacts) {
contacts = contacts.sort(cSort);
alert("length " + contacts.length );
var i =0;
for (var i = 0; i < contacts.length; i++)
{
console.log("Display Name = " + contacts[i].displayName);
if(contacts[i].displayName != null)
{
if( contacts[i].phoneNumbers == null )
continue;
else if(contacts[i].phoneNumbers.length)
{
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
$('#contact_list').append('<li> Name:'+contacts[i].displayName+'</li>');
$('#contact_list').append('<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>');
}
$('#contact_list').listview('refresh');
}
}
}
}
function onError(contactError) {
alert('onError!');
}
</script>
Change your code from:
{
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
$('#contact_list').append('<li> Name:'+contacts[i].displayName+'</li>');
$('#contact_list').append('<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>');
}
$('#contact_list').listview('refresh');
}
To:
{
var finalList = '';
listEntryPoint = $('#contact_list');
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
finalList += '<li> Name:'+contacts[i].displayName+'</li>' + '<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>';
}
listEntryPoint.append(finalList);
listEntryPoint.listview('refresh');
}
#BINIL S, you have a very expensive Jquery call:
$('#contact_list').append(...);
Change to:
listEntryPoint = $('#contact_list');
move that outside of the loop and assign it to a variable, that should help. You can also NOT insert the new entries one at at time. You CAN make the one large list before you insert into HTML. Like this,
finalList += '<li> Name:'+contacts[i].displayName+'</li>' + '<li> Number:'+contacts[i].phoneNumbers[j].value+'</li><br><br>';
After loop is done,
listEntryPoint.append(finalList);
That should help - Jesse
I am trying to achieve this horizontal swipers inside listview(vertical scroll) in Jquery Mobile, below i attached an example of what i meant but that is in Android. I am wondering how would i achieve this in Jquery Mobile. It is the functionality in Airbnb app - a listview that you can scroll vertically, but at the same time each list has multiple images that you can scroll horizontally.
swiping items on listview, with small vertical margin
I had an attempt to achieve it by loading the list in an ajax, and then nest the images inside another for loop and putting that into swipers. But the problem is the swiper isnt showing up, and also the layout is all messed up.
<script>
$( "#form" ).submit('pageinit',function( event ) {
$("#newContent2").empty();
var values = $(this).serialize();
console.log(values);
$.ajax({
type: "POST",
url: "http://test.com/search.php",
data: values,
dataType:'json',
success: function(data){
console.log(data);
var $el = $('#list');
var listView = new infinity.ListView($el);
for (var i=0; i<50; i++) {
var listing = data[i].listing;
var Location = data[i].Location;
var date = data[i].date;
var images = data[i].pics.split(',');
console.log(image);
for(var j = 0; j<images.length; j++){
var image3= "http://test.com/"+images;
console.log(image3);
var image2=" <div class='swiper-slide'><img class='lazy' src='"+ image3 + "' width='100%' id='viewer'/></div>"
}
var myOtherUrl = "list.html?Listingid=" + encodeURIComponent(listingid)+"?Location="+ encodeURIComponent(Location)+ encodeURIComponent(nobed+"?date="+ encodeURIComponent(date));
$.mobile.pageContainer.pagecontainer( "change", "#pageX", { foo: data[i].listingid, location:data[i].Location } );
var $newContent = "<li id='indi'><a href='" + myOtherUrl + "'>'"+ image2+ "'</a></li>"
+"<div id=two class=col-md-1 style=height:38%> <h9 class=name data-address href='"+ myOtherUrl + "'><a id="+"my-button"+">BucketListly</a>"+ "<h9 > "+data[i].Location+ "</h9>";
$("#newContent2").append($newContent);
var listItems = listView.find('.my-items');
for(var index = 0, length = listItems.length; index < length; index++) {
listItems[index].remove();
}
var swiper = new Swiper('.swiper-container', {
loop:false,
autoResize: true,
calculateHeight:true,
onSlideChangeStart: function(){
$('.swiper-pagination-switch').removeClass('active')
$('.swiper-pagination-switch').eq(swiper.activeSlide).addClass('active')
}
});
//navigation
$('.swiper-pagination-switch').click(function(){
swiper.swipeTo($(this).index());
$('.swiper-pagination-switch').removeClass('active');
$(this).addClass('active')
})
}
}
});
return false;
});
</script>
i am developing an app like "whatsapp" for which i want display contacts on my content (between header and footer) from my android phone so what can i do that task?
i tried this but it doesnt work.
function displayContact1() {
alert('Clicked');
var options = new ContactFindOptions();
options.filter="";
options.multiple=true;
var filter = [ "displayName", "phoneNumbers", "photos" ];
navigator.contacts.find(filter, displayContact, onContactError, options);
var myContacts = new Object();
// Default image path for the profile image
var defaultImagePath = $("#defaultImagePath").attr('src');
for (var i=0; i<contacts.length; i++)
{
if( contacts[i].phoneNumbers == null )
continue;
// Checks for the image
var img = contacts[i].photos != null ? contacts[i].photos[0].value : defaultImagePath;
if(contacts[i].phoneNumbers.length)
for (var j=0; j<contacts[i].phoneNumbers.length; j++)
{
var pNumber = contacts[i].phoneNumbers[j].value;
var name = contacts[i].displayName != null ? contacts[i].displayName: "No name";
// To sort the names based on the starting letter
// Stores the names in that array
var index = name.substring(0,1).toUpperCase();
if (typeof myContacts[index] == 'undefined')
{
myContacts[index] = new Array();
}
// cuts the large names
if( name.length > 35 )
{
name = name.substr(0,35)+"...";
}
// Push every details into an array.
myContacts[index].push({"name":name, "pNumber": pNumber, "img": img} );
}
}
var arrayKeys = new Array();
for (var key in myContacts )
{
arrayKeys.push( key );
}
// Sorts the array based on the key A, B , C etc
arrayKeys = arrayKeys.sort();
for( i = 0 ; i < arrayKeys.length ; i++ )
{
var records = myContacts[ arrayKeys[i] ];
$("#contacts").append ("<li class='letter-head'>"+ arrayKeys[i]+"</li>");
// Sort each names
records = records.sort( sortNames );
for( var r_key in records )
{
$("#contacts").append ( "<li><img src='"+ records[r_key].img+"' /> <span class='contact-name'>"+records[r_key].name + "</span><span class='contact-number'>" + records[r_key].pNumber + "</span></li>");
}
}
hide_loader();
$('.addressBook').effect("slide", {direction: "right"}, 500);
}
function sortNames(a, b )
{
return a.name.toLowerCase() > b.name.toLowerCase() ? 1 : -1;
}
Please look up the Android Developer Site before asking next time.
Google can help here too.
There's a "Contact Managet" Sample from Google or THIS one.
Here's how you read the contact data: LINK
Here's how you create a custom listview: LINK
Here's a tutorial for a whole contacts list: LINK