I am new in Java and have a task to write some application. Faced one problem which can not pass :(
The issue is to update an array element through reflection (app selecting public array to update dinamicaly depending on string app reading from file):
First, i have reflected boolean variables as follows:
activity = activityName(activities[i].substring(0,activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object obj = field;
field.setBoolean(obj, true);
And that worked for me well. But now i need to use arrays instead of regular variables, and tried to make as follows:
activity = activityName(activities[i].substring(0, activities[i].lastIndexOf('.', activities[i].length() - 4)));
Field field = refClass.getField(activity);
Object field_act = field;
field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);
And getting exception "Argument not an array". :(
In field_act.setBoolean(field_act, LMKStorage.currentLmkSlot, true);, field_act is boolean[] i am getting with .getField(activity), LMKStorage.currentLmkSlot is int to determine which position of an array to set and "true" is value to set. The field_act i have to get 100% is an array, because i have not non-array static variables in refClass.
so far i have got studing books i have.But still nothing. Tried to google any examples to update array elements... nothing usefull for me.
Please advice.
For arrays, use java.lang.reflect.Array instead of java.lang.reflect.Field.
Object field_act = field.get(obj);
Array.setBoolean(field_act, LMKStorage.currentLmkSlot, true);
Related
First time having to work with JSON data on my own, even if very simple.
Here is the JSON data I'm working with:
{
"heart" : [92, 108],
"temperature" : [85.08, 85.66],
"conductance" : [4095, 4095]
}
What I'm attempting to do is extract one of the three arrays found within that JSON object, but I'm receiving a JSONException: Not a primitive array: class org.json.JSONArray. Here is a portion of the code that I'm using to extract the array of values associated with "heart":
JSONObject obj = new JSONObject(obtainJSONObject());
JSONArray arr = new JSONArray(obj.getJSONArray("heart")); // This is where the error is occuring
int low = arr.getInt(0);
int high = arr.getInt(1);
I've tried to follow what this solution answered, but can't really make much sense of it: How to Get JSON Array Within JSON Object?
I'm not sure if it has something to do with the way how the JSON data is being formatted? I did check online to see if it was any valid or not at https://jsonformatter.curiousconcept.com/. Any help or insights will be greatly appreciated!
So I am running some code which runs over 300k times. Each time this code runs, it returns up to 300k values. I am currently storing the results I get in an ArrayList:
List<List<Object>> thisList = new ArrayList<List<Object>();
for (int i = 0; i < 300000; i++) {
thisList.add(new ArrayList<Object>());
}
for (int i = 0; i < 300000; i++) {
List<Object> result = someCode();
for (Object obj : result) {
thisList.get(obj.id).add(obj.value);
}
}
In this code, everytime obj is obtained, it has a value obj.id which specifies the index in the List where obj.value has to be stored.
What would be the most efficient way to store the results elsewhere as the search continues? My code seems to stop working past iteration 400, most likely due to low memory issues. I have considered using a simple text document where each line represents a List<Object> but through some Googling, it seems there is no way to append to a specific line, and all suggestions seems to point towards overwriting the entire text document. I've never worked with databases before which is why I am trying to avoid that for now.
Would appreciate if someone can give me suggestions on what I could do.
Edit: Is there a method which does not use a database, where after each iteration of the outer for loop, the data can be stored?
For example, given a file which currently contains
List 0: obj.value1 obj.value2
List 1: obj.value1 obj.value4
...
List 300000: obj.value3 obj.value8
and result contains
{obj<1, 100>, obj<0, 3>, ...}
where each object is of the form obj<id, value>, the file becomes
List 0: obj.value1 obj.value2 obj.value3
List 1: obj.value1 obj.value4 obj.value100
...
List 300000: obj.value3 obj.value8
You could store it in an XML file using JAXB api
Here is a link with a little tutorial on JAXB:
https://dzone.com/articles/using-jaxb-for-xml-with-java
Or you could also store it in a JSON file usin json-simple api
Here's another little tutorial:
https://stackabuse.com/reading-and-writing-json-in-java/
These are the links to download JAXB and json-simple from maven:
JAXB: https://mvnrepository.com/artifact/javax.xml.bind/jaxb-api
json-simple: https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple
Hope it'll be useful to you
I am a freshman learning Java recently. I encountered a problem when using the method get of List in Java.
I am confused of how it works.
Is the object returned by the method created via new or just a reference to the original object in the list?
My code is as follows:
ActivityManager am = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfos = am.getRunningTasks(2);
ActivityManager.RunningTaskInfo currentTaskInfo = taskInfos.get(0);
am.getRunningTasks(2).get(0).description = "value";
Toast.makeText(this,am.getRunningTasks(2).get(0).description, 10).show();
I want to look for a variable which I can modify and set as the identifier for a running task. But it seems I cannot modify the description. Toast shows the description is still null, not value.
No, it doesn't create a new object. It returns the reference to it.
I'm trying to write a plugin for crawljax that runs some javascript code, like this:
String result = browser.executeJavaScript(script).toString();
and the script code:
function getElementPosition(id) {
var element = document.getElementById(id);
return JSON.stringify(elementpos(findPosX(element), findPosY(element)));
}
function elementpos(x, y) {
elementpos = new Object();
elementpos.x = x;
elementpos.y = y;
return elementpos;
}
return getElementPosition("foo");
This returns successfully, but the result always is null, even though if I print out the same thing using document.write, I get a nicely formatted JSON string
{"x":8, "y":24}
Am I misunderstanding something? Is there some weird thing that happens with JSON strings and java? I don't have a lot of experience in javascript, so am I not allowed to just return like that?
I'm testing this out on google chrome, v. 25
Note: I don't think it's got anything to do with Crawljax itself, as theres a separate plugin (written by someone else), which also has a script that returns a JSON string, but that seems to work perfectly fine...
JavaScript is allergic to new Object(); do a shortcut, try the one below, that may solve;
return JSON.stringify({x:findPosX(element), y:findPosY(element)});
Objects created with new Object(); syntax brings many weird problems in javascript.
I don't think the problem here is with new Object(), but commenters please feel free to fill me in if I am wrong on that point. Try this:
function elementpos(x, y) {
var elementpos = new Object();
elementpos.x = x;
elementpos.y = y;
return elementpos;
}
Notice that I have put "var" in front of "elementpos = new Object();". Without that variable definition the first line of the global "elementpos" function is to replace itself with an "elementpos" object. The first time it executes will probably be OK, but the second time will likely fail with an exception as it tries to treat the new Object() result as a function to call.
I was able to execute the code above and stringify the result without any problems under chrome 40. Note also that calling the local variable "result" or something other than the function name would remove some potential confusion here.
New to Java, and can't figure out what I hope to be a simple thing.
I keep "sections" in an array:
//Section.java
public static final String[] TOP = {
"Top News",
"http://www.mysite.com/RSS/myfeed.csp",
"top"
};
I'd like to do something like this:
Article a1 = new Article();
a1.["s_" + section[2]] = 1; //should resolve to a1.s_top = 1;
But it won't let me, as it doesn't know what "section" is. (I'm sure seasoned Java people will cringe at this attempt... but my searches have come up empty on how to do this)
Clarification:
My article mysqlite table has fields for the "section" of the article:
s_top
s_sports
...etc
When doing my import from an XML file, I'd like to set that field to a 1 if it's in that category. I could have switch statement:
//whatever the Java version of this is
switch(section[2]) {
case "top": a1.s_top = 1; break;
case "sports": a1.s_sports = 1; break;
//...
}
But I thought it'd be a lot easier to just write it as a single line:
a1["s_"+section[2]] = 1;
In Java, it's a pain to do what you want to do in the way that you're trying to do it.
If you don't want to use the switch/case statement, you could use reflection to pull up the member attribute you're trying to set:
Class articleClass = a1.getClass();
Field field = articleClass.getField("s_top");
field.set(a1, 1);
It'll work, but it may be slow and it's an atypical approach to this problem.
Alternately, you could store either a Map<String> or a Map<String,Boolean> inside of your Article class, and have a public function within Article called putSection(String section), and as you iterate, you would put the various section strings (or string/value mappings) into the map for each Article. So, instead of statically defining which sections may exist and giving each Article a yes or no, you'd allow the list of possible sections to be dynamic and based on your xml import.
Java variables are not "dynamic", unlink actionscript for exemple. You cannot call or assign a variable without knowing it at compile time (well, with reflection you could but it's far to complex)
So yes, the solution is to have a switch case (only possible on strings with java 1.7), or using an hashmap or equivalent
Or, if it's about importing XML, maybe you should take a look on JAXB
If you are trying to get an attribute from an object, you need to make sure that you have "getters" and "setters" in your object. You also have to make sure you define Section in your article class.
Something like:
class Article{
String section;
//constructor
public Article(){
};
//set section
public void setSection(Section section){
this.section = section;
}
//get section
public String getSection(){
return this.section;
}