android reflection in enhanced for loop - android

I know some things about reflection because i read this post: call function based on string android
Class c = Class.forName("MyClass");
Method m = c.getMethod("get"+arg);
return (Integer) m.invoke(this);
I am using an enhanced for loop like this:
int check = 0,check2=0;
for(PostValue post : helper.posts)
{
//Name method with a String
if(category.equals(post.getMethodFromStringHere()))
{
check++;
}
}
so what I want is that I can get the method from a string in the if above.
Thanks in advance.
If you need more information you can ask,
EDIT:
try {
int check = 0,check2=0;
Class<?> postValueClass = Class.forName("PackageName.PostValue");
Method m = postValueClass.getMethod("get"+category);
for(PostValue post : helper.posts)
{
String response;
response = (String) m.invoke(post);
if(category.equals(response))
{
check++;
}

Something like that would do the job. i haven't tested it !! You might need to cast some objects.
Class postValueClass = Class.forName("PostValue");
Method getMethodFromStringHereMethod = postValueClass.getMethod("getMethodFromStringHere");
int check = 0;
int check2 = 0;
for(PostValue post : helper.posts)
{
Boolean response = (Boolean) getMethodFromStringHereMethod.invoke(post);
if (response.getBooleanValue())
{
check ++;
}
}

Related

Android + ObjectBox Search Query Issue

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.

Update object in List

I am calling a function in a Class which will update a List Object. I have successfully get the desired object and change the values in it. How do I update back the original list?
Here is my code:
void updateTask(
Guid id, String title, String start, String end, String timeleft) {
final taskToBeUpdated = _tasks.firstWhere((element) => element.id == id);
taskToBeUpdated.title = title;
taskToBeUpdated.start = start;
taskToBeUpdated.end = end;
taskToBeUpdated.timeLeft = timeleft;
}
I know I can use the forloop to achieve this
for (var i = 0; i < _tasks.length; i++) {
if (_tasks[i].id == id) {
_tasks[i].title = title;
_tasks[i].start = start;
_tasks[i].end = end;
_tasks[i].timeLeft = timeleft;
}
}
But is there a shorter way?
Your first code should directly modify the object in the list since dart passes it by reference.
Try run this code to understand how this works:
List a = [{"dod":1}, {"dod":3}];
Map _b = a.firstWhere((e)=>e["dod"]==1);
_b["dod"] = 2;
print (a);

How to detect if a string contains a specific Word

I have this code :
if (currentLocation.distanceTo(myModel.getNearest()) < 900) {
if (said != true) {
String seriousWarning = (myModel.getNearest().getProvider());
tts.speak(seriousWarning, TextToSpeech.QUEUE_ADD, null);
said = true;
warningTxt.setTextColor(Color.RED);
}
I would like to check if there a certain word in the seriousWarning string, knowing that (myModel.getNearest().getProvider()) is the title of the nearest GPS point to the device.
Any help would be much appreciated!
try below piece of code:
boolean isPdf = stringValue.matches(".*\\b"STRING_NAME"\\b.*");
You can use contains() method.
if(seriousWarning.contains("certainword"))
{
//Do something
}
You can use regular expressions to check if a string contains a substring.
This code snippet is from the android developer documentation.
// String convenience methods:
boolean sawFailures = s.matches("Failures: \\d+");
String farewell = s.replaceAll("Hello, (\\S+)", "Goodbye, $1");
String[] fields = s.split(":");
// Direct use of Pattern:
Pattern p = Pattern.compile("Hello, (\\S+)");
Matcher m = p.matcher(inputString);
while (m.find()) { // Find each match in turn; String can't do this.
String name = m.group(1); // Access a submatch group; String can't do this.
use indexOf("String to be checkecked");
if(seriousWarning.indexOf("String to be checkecked") > -1)
{
// your code
}

AsyncTask do not work in for loop

My AsyncTask class do not work inside for loop. Below is my code please review it.
for (int i = 0; i < size; i++) {
String id = careplan_disease_Parser.DiseaseID.get(i);
String method = "GetCarePlan_Comment?CurrentValue=0&OptionId=" + id + "&DiseaseID=" + id + "&OrgId=" + orgId + "";
String link = "GetCarePlan_Comment_dislink";
task = new AsyncTask123();
task.execute(link, method);
method=null;
link=null;
task=null;
}
Task executes only once. so i can't get value from web service second time in a loop.
Please help me how to make it work.
Thanks
You can write a start-method, that gets called in the onPostExecute-part of you AsyncTask. It should look like this:
private void start(int number)
{
if(number == size)
{
//exit
}
else
{
new AsyncTask123().execute(link, method);
}
}
private class AsyncTask123 extends AsyncTask<> {
protected void onPostExecute() {
start(i++);
}
}
This should work, you just have to fit it for your needs.
if you want AsyncTask in for loop then you should call your class like:
new AsyncTask123().execute(link, method);
Not like :
task = new AsyncTask123();
task.execute(link, method);

string index out of bound exception while carrying search operation

when I am carrying out a search operation after fetching the contacts,it shows this exception when I type the letters very fast in the search bar and the application crashes.Could you please help me out to resolve this issue.I am including the portion of the code also along
#Override
public boolean onQueryTextChange(String newtext) {
String searchString = newtext;
int textLength = searchString.length();
ArrayList<Masterlistmodel> type_name_filter = new ArrayList<Masterlistmodel>();
/* String text = edtField.getText().toString(); */
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
textLength))) {
type_name_filter.add(masterarr.get(i));
}
}
type_name_copy = type_name_filter;
listUpdate(type_name_copy);
return true;
}
#Override
public boolean onQueryTextSubmit(String arg0) {
// TODO Auto-generated method stub
return false;
}
First thing I'd point out is that we don't know what kind of object is masterarr, So I'll guess is like an ArrayList.
I'd try not to use the .size() but the .length() method, size is related to capacity and length is related to the amount of items actually in the array.
Also, as #rsinha said, I think a possible mistake is when you try to execute the equalsIgnoreCase method and the Name variable in that iteration has a lenght shorter than the lenght of the String typed by the user, so I would try:
for (int i = 0; i <masterarr.size(); i++) {
String Name = masterarr.get(i).getName();
if (searchString.equalsIgnoreCase(Name.substring(0,
Math.min(textLength,Name.length())))) {
type_name_filter.add(masterarr.get(i));
}
}
Try first using .length() and if does not work, try the changes in the for loop. I see no more in your code I could help with.
You get IndexOutOfBoundsException when you want to access an array index which is out of range. For example:
String[] myArray = new String[10];
myArray[10] = "test"; // 10 is out of limits(0-9)
Would produce such an exception.
with this:
ArrayList<String> result= new ArrayList<String>();
Then you can add elements to this list with the following:
// result[i] = trax.substring(s1+4,s2);
result.add(trax.substring(s1+4,s2));
It will work for you and it will remove this exception.
'textLength' is length of the search string entered by user. An entry of this length may not be in your master list 'masterarr'. You may try:
String Name = masterarr.get(i).getName();
if (Name.startsWith(searchString)) {
type_name_filter.add(masterarr.get(i));
}
Add the first statement in the method "onQueryTextChange"
if(newtext==null) return true;
Then try

Categories

Resources