I've made a class which holds some string and integers, in that class I made a function to convert the data in the class in to a readable string;
public String GetConditions() {
String BigString = null;
String eol = System.getProperty("line.separator");
try {
BigString += "Depth: " + ci(Depth) + eol;
and so on...
Because I have to convert many integers, I made an extra function to convert a integer to a string;
public String ci(Integer i) {
// convert integer to string
if (i != null) {
String a = new Integer(i).toString();
return a;
} else {
return "n/a";
}
}
This throws a NullPointerException exception on return a. I'm quite new to Java, this is probally a noob question... Sorry about, thanks in advance!
There is a much simpler way to convert an Integer to a String: use String#valueOf(int).
public String ci(Integer i)
{
return i == null ? "n/a" : String.valueOf(i);
}
Try converting the Integer you pass in your method to string, instead of instantiating a new one.
You can do it straight forward like:
String a = i.toString();
or
String a = Integer.toString(i.intValue());
Thanks guys, but I found the problem, I've tried to add something to a string which was 'null' , this line:
String BigString = null;
Related
I am stuck with the ObjectBox Like Query. I have done as below when I search for something.
QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
builder.contains(MItemDetail_.productName, search);
itemList = builder.build().find();
For example, My data is:
paracetamol
paracetamol potest
paracetamol_new
Problem:
Now as you know the contains works simply as that returns a list of items that contain a given search string.
What I Want:
If I search para new, I want the result paracetamol_new
If I search para p, I want the result paracetamol potest
If I search para e e, I want the result paracetamol potest and paracetamol_new
Is there any function or utility available in ObjectBox that can help me to achieve this?
Do let me know If you have any questions.
Edited:
The given links in a comment, My question is different. I know all the methods contains(), startsWith, and endsWith but my problem not getting solved using that.
With Reference to this answer I have done some changes as given and I got a perfect solution as I wanted.
QueryBuilder<MItemDetail> builder = mItemDetailListBox.query();
// builder.contains(MItemDetail_.productName, search);
builder.filter(new QueryFilter<MItemDetail>() {
#Override
public boolean keep(#NonNull MItemDetail entity) {
return like(entity.getProductName(), "%"+ search + "%");
}
}).order(MItemDetail_.productName);
businessModels = builder.build().find();
In the following methods, I have added one more replace statement .replace(" ",".*?")
private static boolean like(final String str, final String expr) {
String safeString = (str == null) ? "" : str;
String regex = quoteMeta(expr);
regex = regex.replace("_", ".").replace(" ",".*?").replace("%", ".*?");
Pattern p = Pattern.compile(regex,
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
return p.matcher(safeString).matches();
}
private static String quoteMeta(String s) {
if (s == null) {
throw new IllegalArgumentException("String cannot be null");
}
int len = s.length();
if (len == 0) {
return "";
}
StringBuilder sb = new StringBuilder(len * 2);
for (int i = 0; i < len; i++) {
char c = s.charAt(i);
if ("[](){}.*+?$^|#\\".indexOf(c) != -1) {
sb.append("\\");
}
sb.append(c);
}
return sb.toString();
}
Thank you.
I want to remove String null and want to show like this Item 1, Item2, Item 3 Here is output... nullItem 1Item 2Item 3
String result;
for (Cuisine c : boxAdapter.getBox()) {
if (c.checkbox) {
result += c.name;
}
}
// result = result.substring(0,4);
Initialize your String like this:
String result = "";
instead of just:
String result;
You can do it like this, put a null check.
String result;
for (Cuisine c : boxAdapter.getBox()) {
if (c.checkbox) {
if(c.name != null)
result += c.name;
}
}
OR
You can just initialize your String with empty string like:-
String result = "";
You're appending the three box names to an initially null String (result) , solve this problem by making your String an empty string at the beginning :
String result = "";
Find the solution
String result;
for (Cuisine c : boxAdapter.getBox()) {
if ((c.name!=null)&&(c.checkbox)) {
result += c.name;
}
}
//
Use regular expression to replace non-printable characters.
String string=line.replaceAll("[^\\p{Print}]","");
I'm using Codenameone to develop application in mobile. I want to create a method to show an error message on Screen. But I got an error:
This is my code
public class Common {
public static boolean checkNullOrEmpty(String value){
return !(value != null && !value.equals(""));
}
public static void showMessage(String title,String msgID, Object... params){
String result = String.format(msgID, params);
Dialog.show(title, result, "OK", "Cancel");
}
}
And this is the way I call that method:
Common.showMessage("Error", "Item %s ; Item %s","01","02");
This is error message:
error: cannot find symbol
String result = String.format(msgID, params);
symbol: method format(String,Object[])
location: class String
Can anybody help me? Thanks a lot.
String.format isn't supported by the Codename One subset of the Java API. You should be able to use something like StringUtil.replaceAll etc. to replace entries e.g. for this:
Common.showMessage("Error", "Item {0} ; Item {1}","01","02");
You should be able to do something like this:
String result = msgID;
for(int iter = 0 ; iter < params.length ; iter++) {
result = StringUtil.replaceAll(result, "{" + iter + "}", params[iter]);
}
I'm looking for a way to convert the first letter of a string to a lower case letter. The code I'm using pulls a random String from an array, displays the string in a text view, and then uses it to display an image. All of the strings in the array have their first letter capitalized but image files stored in the app cannot have capital letters, of course.
String source = "drawable/"
//monb is randomly selected from an array, not hardcoded as it is here
String monb = "Picture";
//I need code here that will take monb and convert it from "Picture" to "picture"
String uri = source + monb;
int imageResource = getResources().getIdentifier(uri, null, getPackageName());
ImageView imageView = (ImageView) findViewById(R.id.monpic);
Drawable image = getResources().getDrawable(imageResource);
imageView.setImageDrawable(image);
Thanks!
if (monb.length() <= 1) {
monb = monb.toLowerCase();
} else {
monb = monb.substring(0, 1).toLowerCase() + monb.substring(1);
}
public static String uncapitalize(String s) {
if (s!=null && s.length() > 0) {
return s.substring(0, 1).toLowerCase() + s.substring(1);
}
else
return s;
}
Google Guava is a java library with lot of utilities and reusable components. This requires the library guava-10.0.jar to be in classpath. The following example shows using various CaseFormat conversions.
import com.google.common.base.CaseFormat;
public class CaseFormatTest {
/**
* #param args
*/
public static void main(String[] args) {
String str = CaseFormat.LOWER_CAMEL.to(CaseFormat.UPPER_UNDERSCORE, "studentName");
System.out.println(str); //STUDENT_NAME
str = CaseFormat.UPPER_UNDERSCORE.to(CaseFormat.LOWER_CAMEL, "STUDENT_NAME");
System.out.println(str); //studentName
str = CaseFormat.LOWER_HYPHEN.to(CaseFormat.UPPER_CAMEL, "student-name");
System.out.println(str); //StudentName
str = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_HYPHEN, "StudentName");
System.out.println(str); //student-name
}
}
Output Like:
STUDENT_NAME
studentName
StudentName
student-name
Can anybody please tell what toString in Android is for and how it can be used?
As example would be highly appreciated.
toString is not specific to android. Its a method in java's Object class, which is the superclass of every java object. 'toString' is meant for returning textual representation of an object. This is generally overridden by java classes to create a human readable string to represent that object.
Apart from many other uses, it is widely used for logging purpose so as to print the object in a readable format. Appending an object with string automatically calls the toString() of that object e.g. "abc" + myObject will invoke 'toString' of myObject and append the returned value to "abc"
A good example of toString implementation would look like -
#Override
public String toString() {
return new StringBuilder()
.append("{Address:")
.append(" street=").append(street)
.append(", pincode=").append(pincode)
.append("}").toString();
}
Its the same as in normal Java...
I use it for debugging like this:
class MyClass {
var myVar;
var myOtherVar;
public String toString() {
return "myVar: " + myVar + " | myOtherVar: " + myOtherVar;
}
}
with Log.d("TAG", myClassObject.toString()); I can log what my object contains...
thats just one of countless possibilities.
class Account {
public final String name;
public final String email;
public Account(String name, String email) {
this.name = name;
this.email = email;
}
#Override
public String toString() {
return new Gson().toJson(this);
}
}
It's not like Java. Override example:
#Override
public String toString()
{
return new StringBuffer()
.append("[Museum]-")
.append(name)
.append(" Lat:")
.append(lat)
.append(" Lon: ")
.append(lon).toString();
}
And then usage of the method is
Log.i(LOG_TAG, museum.toString()); // Instead of just "museum"