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]);
}
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 was looking for an example and alive code to transfer just a list of objects into Json string and vice versa.
It is not a secret, that Androids are often used as a communication devices between (in my case) PC with .NET and the Android device itself.
The very common operation is to send SMS messages to a group of subscribers, that's usually exists as a List of objects.. say..
class Man {
public string Number {get;set;}
public string Message {get;set;}
}
So, the List<Man> Men = new List<Man>();
is quite intuitive as the basic structure.
I can convert both ways in C#.NET
using System;
using Newtonsoft.Json;
using System.Collections.Generic;
public class Program
{
public static void Main() {
List<Man> Men = new List<Man>();
// numbers are just random
Man m1 = new Man();
m1.Number = "+6149168158";
m1.Message = "Hello Bob from 1";
m1.UniqueCode = "0123";
m1.State = 0;
Man m2 = new Man();
m2.Number = "+6146146182";
m2.Message = "Hello Bob from 2";
m2.UniqueCode = "0125";
m2.State = 0;
Men.AddRange(new Man[] { m1, m2 });
string result = JsonConvert.SerializeObject(Men);
Console.WriteLine(result);
List<Man> men = JsonConvert.DeserializeObject<List<ManĀ»(result);
foreach(Man m in men) Console.WriteLine(m.Message);
}
}
public class Man
{
public string Number{get;set;}
public string Message {get;set;}
public string UniqueCode {get;set;}
public int State {get;set;}
}
It works.. but the Android side.. just like a dark matter.. I am sure it exists, but I can't touch it..
So, please, whoever knows it, please, publish the Android part here, so the others would get nice and clear example for such a standard requirement.
(No Gson, Mason or some others.. only Android and only JSON..
Thank you..
It looks like you might not want to use the tools available( Gson, Mason or some others..)
You must manually implement your mapper class for every object:
Native tools for android are JSONArray,JSONObject;
In the following code I have provided an example of decoding
Ok, this is the Deserializator
public List<Man> DecodeFactor(String json) throws JSONException {
List<Man> list = null;
try
{
JSONArray headarrays=new JSONArray(json);
if(headarrays.length()>0)
{
list=new ArrayList<Man>();
for (int i = 0; i <headarrays.length() ; i++)
{
Man man=new Man();
JSONObject o = headarrays.getJSONObject(i);
man.Message = o.getString("Message");
man.Number = o.getString("Number");
man.UniqueCode = o.getString("UniqueCode");
man.State = o.getInt("State");
list.add(man);
}
}
}catch (Exception ee) { ee.printStackTrace(); }
return list;
}
Trying to convert a Arraylist of strings into one big comma separated string.
However when I use the
String joined = TextUtils.join(", ", participants);
Debugger shows me size of 4 for participants however the joined value as "" therefore empty
private ArrayList<String> participants;
Not sure what is going wrong?
UPDATE:
List<String> list = new ArrayList<>();
list.add("Philip");
list.add("Paul Smith");
list.add("Raja");
list.add("Ez");
String s = TextUtils.join(", ", list);
This works when I have a list that I manually populate however below is how the code is working right now.
In the onCreate()
callApi(type);
String s = TextUtils.join(", ", participants);
getSupportActionBar().setTitle(s);
In callAPI():
JSONArray participantsR = sub.getJSONArray("referralParticipants");
Log.e("Participants length ", String.valueOf(participantsR.length()));
for (int i = 0; i < participantsR.length(); i++)
{
JSONObject object = participantsR.getJSONObject(i);
String firstname = (String) object.get("fullName");
participants.add(firstname);
Log.e("Times", String.valueOf(i));
}
I'm trying to reproduce your error and am unable to. Here is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
List<String> list = new ArrayList<>();
list.add("Philip Johnson");
list.add("Paul Smith");
list.add("Raja P");
list.add("Ezhu Malai");
String s = TextUtils.join(", ", list);
Log.d(LOGTAG, s);
}
My output is Philip Johnson, Paul Smith, Raja P, Ezhu Malai as expected.
Are you importing the correct TextUtils class?
android.text.TextUtils;
Given the new information, here is my approach:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_temp);
callApi(type, new OnResponseListener<List<String>>() {
#Override public void onResponse(List<String> list) {
getSupportActionBar().setTitle(TextUtils.join(", ", list));
}
});
}
I don't know what networking library you're using, but you may have to define OnResponseListener as an interface. It's very easy:
public interface OnResponseListener<T> {
public void onResponse(T response);
}
You will then need to modify your callApi function to take an instance of OnResponseListener> and call it's onResponse method after completing the call.
I would recommend looking into the Volley library, and reading the Android documentation about simple network calls.
I use StringUtils.join from Apache Common Utilities.
The code is super-simple just the way you wanted,
StringUtils.join(participants,", ");
Works flawlessly for me.
EDIT
As requested, here is the StringUtils.java file for those who just want to use this single utility class and not the entire library.
I don't know what TextUtils does. This will do it.
StringBuffer sb = new StringBuffer();
for (String x : participants) {
sb.append(x);
sb.append(", ");
}
return sb.toString();
Easy enough, just use that.
Try with kotlin
val commaSeperatedString = listOfStringColumn.joinToString { it ->
"\'${it.nameOfStringVariable}\'" }
// output: 'One', 'Two', 'Three', 'Four', 'Five'
I am working on an ecommerce android app. I am trying to fetch records using dreamfactory API for android, based on multiple filters.
Using an AsyncTask named as GetProductsBySubCatIdTask
public class GetProductsBySubCatIdTask extends BaseAsyncRequest {
Context context;
public Products productsRec;
int subCatId;
String sort_str,fltr_str;
public GetProductsBySubCatIdTask(Context context, int subCataId, String sort_str, String fltr_str){
this.context = context;
this.subCatId = subCataId;
this.sort_str = sort_str;
this.fltr_str = fltr_str;
}
#Override
protected void doSetup() throws ApiException, JSONException {
callerName = "getProductsBySubCatId";
serviceName = AppConstants.DB_SVC;
endPoint = "product";
verb = "GET";
// filter to only select the contacts in this group
if(!TextUtils.isEmpty(fltr_str)){
fltr_str = "&&" + fltr_str;
}
else{
fltr_str = "";
}
queryParams = new HashMap<>();
queryParams.put("filter", "sub_category_id=" + subCatId + fltr_str);
queryParams.put("order", sort_str);
applicationApiKey = AppConstants.API_KEY;
sessionToken = PrefUtil.getString(context, AppConstants.SESSION_TOKEN);
}
#Override
protected void processResponse(String response) throws ApiException, JSONException {
//Log.d("Tang Ho"," >>>>> " + response);
productsRec =
(Products) ApiInvoker.deserialize(response, "", Products.class);
}
#Override
protected void onCompletion(boolean success) {
if(success && productsRec != null && productsRec.products.size() > 0){
Log.d("Tang Ho"," >>>>> Success");
}
}
}
I have used filters which is constructed outside the class and provided as parameter, the possible filters are
unit_offerprice < unit_mrp<br>
unit_offerprice = unit_mrp<br>
(unit_offerprice > 200) && (unit_offerprice > 500)<br>
unit_offerprice > 100<br>
unit_offerprice < 600<br>
All the above filters can be used either individually or in combination of 2 or 3 like
unit_offerprice < unit_mrp && unit_offerprice > 100
After escaping the symbols in the string like
unit_offerprice%3Cunit_mrp
Not able to get desired result,
Searched in documentations but din't found exact thing.
what can be the possible solution for this ?
If your filter has multiple conditions, each condition needs to be placed inside parentheses (). Additionally, the proper syntax for joining filters with and is AND, not &&.
Supported logical operators are AND, OR, and NOT.
In your example, this:
unit_offerprice < unit_mrp && unit_offerprice > 100
should be this:
(unit_offerprice < unit_mrp) AND (unit_offerprice > 100)
See these portions of the documentation:
http://wiki.dreamfactory.com/DreamFactory/Features/Database/Records#Filtering_Records
http://wiki.dreamfactory.com/DreamFactory/Tutorials/Querying_records_with_logical_filters
DreamFactory also offers a number of official support avenues, including user forums. http://www.dreamfactory.com/support
Got it resolved by adding parenthesis for multiple filters.
But there was issue using the special characters (like <,>) and
this needed to be
encoded into %3C (for <) and %3E (for >),
the string used for the filtering is :
"(unit_offerprice>100)AND(unit_offerprice<500)"
the encoded form is :
"(unit_offerprice%3E100)AND(unit_offerprice%3C500)"
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;