I want to get a long or double value from JSON by adapter list and set them to EditText in Android. how can I do this work?
If you are using the JSONObject class you can use
try {
long l = object.getLong(key); // throws exception if there's no long at that key
}
catch(JSONException json) {}
or
long l = object.optLong(key); // instead of throwing exception returns 0
Then do
editText.setText("" + l);
Related
I wrote this code to convert dynamic list to Word list but linter says:
Omit type annotations for local variables. on 2nd line.
However if I omit type annotations, I get an error A value of type 'List<dynamic>' can't be returned from method 'convert' because it has a return type of 'List<Word>'.
It there any smarter way to convert?
static List<Word> convert(List<dynamic> words) {
final List<Word> wordsList = [];
words.forEach((v) {
final map = Map<String, dynamic>.from(v as Map<dynamic, dynamic>);
wordsList.add(Word.fromMap(map));
});
return wordsList;
}
Word.fromMap is:
Word.fromMap(Map<String, dynamic> map)
: text = map['text'] as String,
count = map['count'] as int;
To avoid the warning, and put the type on the right-hand side as the lint wants, just write:
final wordsList = <Word>[];
I assume words is JSON data, so the maps are already Map<String, dynamic>. Then you can also do everything in one line:
static List<Word> convert(List<dynamic> words) =>
[for (var v in words) Word.fromMap(v)];
Use the cast() method like this:
class Word {
final String text;
final int count;
static List<Word> convert(List<dynamic> words) {
final List<Word> wordsList = [];
words.cast<Map<dynamic, dynamic>>().forEach((v) { // <-- look here
final map = Map<String, dynamic>.from(v);
wordsList.add(Word.fromMap(map));
});
return wordsList;
}
Word.fromMap(Map<String, dynamic> map)
: text = map['text'] as String,
count = map['count'] as int;
}
It will ensure the casting are done on each element. Make sure the type are correct since it will else result in a type-cast error.
How do I get the last n-characters in a string?
I've tried using:
var string = 'Dart is fun';
var newString = string.substring(-5);
But that does not seem to be correct
var newString = string.substring(string.length - 5);
Create an extension:
extension E on String {
String lastChars(int n) => substring(length - n);
}
Usage:
var source = 'Hello World';
var output = source.lastChars(5); // 'World'
While #Alexandre Ardhuin is correct, it is important to note that if the string has fewer than n characters, an exception will be raised:
Uncaught Error: RangeError: Value not in range: -5
It would behoove you to check the length before running it that way
String newString(String oldString, int n) {
if (oldString.length >= n) {
return oldString.substring(oldString.length - n)
} else {
// return whatever you want
}
}
While you're at it, you might also consider ensuring that the given string is not null.
oldString ??= '';
If you like one-liners, another options would be:
String newString = oldString.padLeft(n).substring(max(oldString.length - n, 0)).trim()
If you expect it to always return a string with length of n, you could pad it with whatever default value you want (.padLeft(n, '0')), or just leave off the trim().
At least, as of Dart SDK 2.8.1, that is the case. I know they are working on improving null safety and this might change in the future.
var newString = string.substring((string.length - 5).clamp(0, string.length));
note: I am using clamp in order to avoid Value Range Error. By that you are also immune to negative n-characters if that is somehow calculated.
In fact I wonder that dart does not have such clamp implemented within the substring method.
If you want to be null aware, just use:
var newString = string?.substring((string.length - 5).clamp(0, string.length));
I wrote my own solution to get any no of last n digits from a string of unknown length, for example the 5th to the last digit from an n digit string,
String bin='408 408 408 408 408 1888';// this is the your string
// this function is to remove space from the string and then reverse the
string, then convert it to a list
List reversed=bin.replaceAll(" ","").split('').reversed.toList();
//and then get the 0 to 4th digit meaning if you want to get say 6th to last digit, just pass 0,6 here and so on. This second reverse function, return the string to its initial arrangement
var list = reversed.sublist(0,4).reversed.toList();
var concatenate = StringBuffer();
// this function is to convert the list back to string
list.forEach((item){
concatenate.write(item);
});
print(concatenate);// concatenate is the string you need
I'm writing a function to replace substrings (what laguange doesn't have this, grr), and I am getting some strange characters in my ouput. I cannot figure out why.
string replaceSubstring(string input, string targetSubstring, string substitute, bool matchCase)
{
string result = input
Buffer b = create
b = input
int targetStartPos
int targetLength
while (findPlainText(result, targetSubstring, targetStartPos, targetLength, matchCase))
{
string prefixStr = b[0:targetStartPos - 1]
string suffixStr = b[targetStartPos + targetLength:]
b = prefixStr substitute suffixStr
result = tempStringOf(b)
}
delete b
return result
}
When running print replaceSubstring("Jake Lewis", "ake", "ack", false), I get an output of �*��*�is. This would appear to be some sort of encoding issue, but I am unclear on how this is happening, or how to fix it.
Try using stringOf() instead of tempStringOf(). Your processing is fine, but the result becomes invalid after deleting b.
I made a table and the corresponding SQLContainer. The table have a column with phone numbers. In db table type of the corresponding column is a int. I wish formatting values of Vaadin table, in such way that view phone numbers become without comas or dots like separator of thousand(8,888 -> 8888).
I have already made similar thing to the Table which data source is a JPAContainer on this way:
Table imenikTable = new Table("Imenik", imenikData){
/**
*
*/
private static final long serialVersionUID = 8213291207581835298L;
#Override
protected String formatPropertyValue(Object rowId,
Object colId, #SuppressWarnings("rawtypes") Property property) {
Object v = property.getValue();
if (v instanceof Integer) {
DecimalFormat df = (DecimalFormat) DecimalFormat.getInstance(getLocale());
df.applyLocalizedPattern("##00");
return df.format(v);
}
return super.formatPropertyValue(rowId, colId, property);
}
};
And everything works well. But when i made similar construction with SQLContiner instead of JPAContainer formatting is simply ignored. Affter that i try to change the way like this:
StringToIntegerConverter plainIntegerConverter = new StringToIntegerConverter(){
private static final long serialVersionUID = -7517984934588222147L;
protected NumberFormat getFormat(Locale locale){
NumberFormat format = super.getFormat(locale);
format.setGroupingUsed(false);
return format;
}
};
contaktListTable.setConverter("telbr", plainIntegerConverter);
But still my environment ignores me, even no error messages! What can be problem?
I think
Object v = property.getValue();
is not returning an Integer value when you use the SQLContainer and that's why you are not seeing any exceptions, the conditional block is not being executed.
Can you check that with a break point?
How to get the length of a string array like
str 30 name[];//dynamic array
I used the following for getting the length,but it showing the error as "the variable is not of the type CLASS."
int len=name.get_length();
It sounds like you might be happier using the Array collection class.
http://msdn.microsoft.com/en-us/library/array.aspx
static void TestArray(Args _args)
{
Array strArray = new Array(Types::String);
;
strArray.value(1, 'abc');
strArray.value(2, 'def');
info(strfmt("%1", strArray.lastIndex()));
}
You need the dimOf function. Take a look to the reference:
http://msdn.microsoft.com/en-us/library/aa597117.aspx
Sorry, there is no build-in function to return the string array size. Since you are in full control what you put in the array, there need not be any!
The built-in function dimof returns the allocated size of the array, which is only of practical value for a fixed size array like str 30 name[20], where dimof(name) returns 20.
A clean way to remain in control, is to use a setter function:
static void TestArray(Args _args)
{
str 30 name[];
int n = 0;
int i;
void nameSet(int _i, str 30 _name)
{
n = max(n,_i);
name[_i] = _name;
}
;
nameSet(2,'abc');
nameSet(4,'def');
for (i = 1; i <= n; i++)
info(name[i]);
}
There is no upper bound index limit, so accessing name[7] is perfectly valid and in this case returns a blank value. This may be used to your advantage, if you always use all holes and never stores a blank:
static void TestArray(Args _args)
{
str 30 name[];
int i;
name[1] = 'abc';
name[2] = 'def';
for (i = 1; name[i]; i++)
info(name[i]);
}
Beware that accessing a higher index (in this case higher than 2) may in fact increase the allocated size of the array.