I'm writing android app, which drawing 4 graphs in 1 plot. Graph data is stored in object GraphViewData(x,y). I also have List which contains 4 GraphVieData objects.
I want to give user ability to switch off/on some graphs.
I tried to write myList.set(index, null) to hide graph and then myList.set(index, myObject) to show it again, but every time the List size is changing. So I'm getting IndexOutOfBound exception.
Please, tell me why the List size is changing? Here is List.set() description:
Replaces the element at the specified location in this List with the
specified object. This operation does not change the size of the List.
Code:
public void removeSerie(int id){
graphSeries.set(id, null);
Log.d("CurrentListSize: ", graphSeries.size() + "");
}
public void addSerie(GraphViewData series, int id){
graphSeries.set(id, series);
}
There is a discrepancy between the javadocs for List.set(int, T) between Java and Android. This is worrying, but you should resolve it as following:
The Oracle version of the javadoc is definitive for Java. A List implementation is permitted to change the list size on set.
The Android version of the javadoc should be viewed as incorrect as a source for Java. You could argue that it is correct for Android, but that doesn't really help if you are dealing with code that wasn't specifically written for Android. (For example, code that was written for Java and then compiled for Android.)
The standard List classes in Java and Android won't do this. (Check the source code to be sure, but I'd be extremely surprised if any of them did without the javadocs saying so.)
A custom / 3rd-party List class could do this, and still follow the Java List contract (though arguably not the Android contract).
There are no guarantees that a custom / 3rd-party List class will follow either contract. This renders the whole argument moot ... unless you can persuade the relevant author / supplier to change the relevant list class. (And good luck with that, because it will probably break other peoples' code!!)
So what should you do? I recommend:
If you want to be able to do this with set, make sure that you are using a list class that supports it. Check the code of the list class if necessary.
Otherwise, change your algorithm.
Related
I'm a decent C++ programmer, good enough to do what I want. But I'm working on my first Android App (obviously not C++ related), and I'm having an issue where I'd like to translate what I know from C++ over to the XML/Java used in Android Studio.
Basically I have (in C++) an array of structures. And maybe I didn't do the perfect search, but I sure as heck tried to look around for the answer, but I didn't come up with anything.
How would I go about placing an array of structures inside the XML file and utilizing it in Java?
As a bit of a buffer, let me say that I'm not really looking for code, just verification that this is possible, and a method on how to go about it. I don't mind researching to learn what I want, but I haven't come up with anything. Like I said, I probably haven't googled it properly because I'm unsure of exactly how to ask it.
EDIT: So it appears that XML doesn't have a structure (or anything similar? not sure). But I can utilize a Java class with public variables. Now my question is more or less: What would be the best way to go about inserting all the information into the array/class/variables?
In C++ terms, I could neatly place all the info into a text file and then read from it, using a FOR loop to place all the info in the structures. Or, if I don't want to use an outside source/file, I could hardcode the information into each variable. Tedious, but it'd work. I'm not sure, in Android terms, if I could use the same method and pack in a text file with the app, and read from the file using a FOR loop to insert the information into the array/class/variables
class answerStruct
{
public String a;
public boolean status;
};
class questionStruct
{
public String q;
answerStruct[] answer = new answerStruct[4];
};
I'm not placing this here to brag at my super high tech program, but to give a visual, and frankly that's less I have to write out. This is the method I plan on going with. But, being Java, I'm open to possibly better options. My question still stands as far as inputting information into the variables. Hard code? or does Android/Java allow me to place a text file with my app, and read from it into the variables?
XML is just a markup language for tree-structured data, and imposes no restrictions on how you name or structure your tree nodes.
What I think that you're looking for is an XML Object Serialiser: a way to serialise your in-memory structure into XML for a more permanent storage, and then at a later run, deserialise it back into memory. There are many XML Serialisers for Java, each with an own proprietary XML format.
I've used Simple XML in the past, and found it easy and flexible.
Is there any method which performs similar tasks to the GetDriveType() method of Microsoft Visual C++. I've already gone through the FileSystemView class of Java Swing. But the method available there are limited and does not fulfill my requirement.
So please tell me someone if Java defines any such method for Windows platform or Platform Independent.
You can use File.listRoots() method. It will list all the drives in your system.
And to get detail information about that drive you can use the following code.
List roots = Arrays.asList(File.listRoots());
for(File f:roots)
{
String s = FileSystemView.getFileSystemview().getSystemTypeDescription(f);
}
This code shows the actual information of drives and other PnP devices. Use this link to know more. And according to your question you must be want to know the hardware details of connected drives to PC. Use JNI if you want to do all code in java.
Are you using JDK7?
If so, there is FileStore which returns the type as a String.
However, looking at the source code itself (FileStore.java) there is a warning that the return value might be implementation specific.
I was working on creating a weather application in Java using Weather Underground and I found that it does have data for some cities.
Initially, I was planning on using GeopIP to get the user's location automatically but since the support for cities is limited I decided to let the user choose the city every time the program starts.
I want the user to be able to choose a city from one that is supported by Weather Underground. The user will enter the name and as he/she enters the name, the possible locations will be displayed in a way similar to the one shown in the picture.
My question is:
How do I implement this search feature ?
My initial guess was to create a Vector containing all the names of the cities and then use brute force to find the match and display in a JPopup or a JWindow containing a JList but I guess there has to be a better method
Rephrase:
What I do not understand is WHAT INFO do I keep in the data structure I must use ? Should I manually create a list of cities that Weather Underground supports or is there another way to do it ?
Take a look at the Trie data structure (also known as digital tree or prefix tree). Autocompletion is one of the most common examples of it's usefulness.
The following article has a nice an very approachable explanation:
Roll your own autocomplete solution using Tries.
if you google autosuggestcombobox you will get some interesting results:
This one is written in JavaFX - I have used and extended it myself already. It is quite useful. What you get "for free" with JavaFX: a context menu with right-mouse click which is auto-generated containing some of the usual "stuff", like cut, copy & paste and even undo! So, I can recommend that solution. To get into JavaFX isn't so hard - and I think it is much easier to learn than Swing - and looks so much cooler! However this implementation has some drawbacks - especially when the layout is not left-aligned, because it is simply a text field on top of a combobox.
OK - but if you want to stick to Swing - you could probably use this one. I haven't used that myself, but the code looks quite straightforward and pretty clean - cleaner than the implementation for JavaFX I must admit (but that had some nice features). So - maybe you try - and extend it? It is built simply on JComboBox.
Can I compare 2 Objects using the Eclipse - Expressions tool, am trying to debug a Java program. The max I can do is, add both the objects to Expressions and manually expand the object to compare, I wish there was like, select 2 Object (of same kind - Class, Of course) and say "Compare" and Eclipse parses both the objects and highlights all the differences..
PS: I'm not lazy to do this manually, its just that the Object I'm dealing with is very complicated, like its got 10 levels or arraylist of Objects :)
Not a elegant solution but it has worked well for me in the past is to include something like gson or other json parser in your classpath. Then in the Display view type:
new Gson().gson.toJson(yourObject1)
and
new Gson().gson.toJson(yourObject2)
Then use the json ouput save it to files and use a file comparison tool.
Longwinded but with complex objects its often worth it.
They can be as detailed or simple as you want them to be.
Using a equals expression in the Display view may tel you if two objects are the same, but if their different, it won't tell you what those differences are.
Consider using Eclipse detail formatters. They are awesome.
Eclipse's Inspect view can often be littered with unwanted data that just clutters your mind and what your really interested in. The ouput you decide to display is your choice with detail formatters.
See the link below for an idea of how to use them.
http://www.howardism.org/Technical/Eclipse/Eclipse_Detail_Formatter.html
Find "Display" view under debug category. It is not open by default in the java debug perspective. You will be able to execute pretty much arbitrary java statements during the debug session.
The project I'm working on requires me to write lots of repetitive code. For example, if I want to load a image file called "logo.png" in my code, I would write something like this:
Bitmap logoImage;
...
// Init
logoImage = load("logo.png")
...
// Usage
logoImage.draw(0, 0);
..
// Cleanup
logoImage.release();
Having to write this code to use every new image is a pain, including having to specify that logoImage should load the file "logo.png".
As I'm working on a Java Android game and images are used a lot in inner loops, I really want to avoid slow things like making virtual function calls and e.g. accessing arrays/maps/object fields when I can avoid it. Copying an idea from the Android API (the generated R class), I thought I could run a utility before compiling to generate some of this repetitive code for me. For example, the actual code in the project file would be reduced to just this:
logoImage.draw(0, 0);
Using some command-line tools (e.g. grep, sed), I can look for every instance of "Image.draw(..." and then generate the other required code automatically i.e. code to load/release the file .png and declare "Bitmap logoImage" somewhere. This code could either be added to a new class or I could add placeholders in my code that told the code generator where to insert the generated code.
To display a new image, all I would need to do is just copy the image file to the right directory and add one line of code. Nice and simple. This avoid approaches like creating an array of images, defining labelled int constants to references the array and having to specify which filename to load.
Is this a really bad idea? It seems a bit of a hack but I can see no easier way of doing this and it does seem to drastically clean up my code. Are there any standard tools for doing this simple kind of code generation (i.e. the tool doesn't need to understand the meaning of the code)? Does anyone else do things like this to make up for language features?
It would be a bad idea to use code generation for something like this. (IMO, code generation should be reserved for situations where you need to generate vast amounts of code, and this doesn't sound like that situation.)
If the boilerplate code in your current solution concerns you, a better solution (than code generation) is to implement an image registry abstraction; e.g.
public class ImageRegistry {
private Map<String, Image> map = new HashMap<String, Image>();
public synchronized Image getImage(String filename) {
Image image = map.get(filename);
if (image == null) {
image = load(filename);
map.put(filename, image);
}
return image;
}
public synchronized void shutdown() {
for (Image image : map.valueSet()) {
image.release();
}
map.clear(); // probably redundant ...
}
}
Replace logoImage.draw(0, 0) and the like with:
registry.getImage("logo.png").draw(0, 0);
remove all of the load calls, and replace all of the release calls with a single call to registry.shutdown().
EDIT in response to the OP's comments below:
... but I mention that I'm writing a game for a phone. A HashMap lookup every time I'm drawing a sprite will kill performance.
Ah ... I remember you from another thread.
You are (yet again) making assumptions about performance without any basis in actual performance measurements. Specifically, you are assuming that HashMap lookup is going to be too expensive. My gut feeling is that the time taken to do the lookup will be a small percentage ( < 10% ) of the time taken to draw the image. At that point, it is approaching the level at which it is unnoticable to users.
If your measurements (or gut feeling) tells you that a hashmap lookup is too expensive, it is a trivial modification to write this:
Image image = registry.getImage("logo.png");
while (...) {
...
image.draw(0, 0);
}
For example, Google even go as far as to recommend you don't use iterators in inner loops because these cause the GC to fire when the Iterator objects are deallocated.
That is irrelevant and inaccurate.
A HashMap lookup using a String key does not generate garbage. Not ever.
Using an iterator in an inner loop does not "cause the GC to fire when the Iterator objects are deallocated". In Java, you don't deallocate objects. That is C/C++ thinking.
Instantiating an iterator in an inner loop does new an object, but the GC will only fire if the new operation hits the memory threshold. This happens only occasionally.
Also, writing "file_that_does_not_exist.png" will not be picked up as a compile time error with your example.
Neither your original solution, or the code generation approach can give you a compile time error for a missing file either.
Avoid code-generation. It often makes code hard to maintain.
In your case why don't you just make:
public class ImageUtils {
public static void drawAndRelease(String name) {
logoImage = load(name)
logoImage.draw(0, 0);
logoImage.release();
}
}
and then just call:
ImageUtils.drawAndRelease("logo.png");
If there is more code between these methods - well, then they are atomic methods and you won't know where to put them in case you use code-generation.
I second Bozho's answer about avoiding code generation, but if you have to write repeatable snippets of code, any good IDE usually has some built in support for specifying your own snippets with variables and everything. IntelliJ IDEA has this feature, it's called Live Templates. I would guess both Eclipse and NetBeans has similar functionality.
You transfer complexity to code generation, and it (generation) is not trivial and may be buggy.
Code is harder to read and maintain. Some clear rules to design and coding are more helpful here.
Several ways:
Eclipse code2code, you cod in template using template language such as FreeMarker, groovy, etc
eclipse sqLite plugin for Android autogenerates sqlite code
MotoDevStudio4android has code snippets which yo could use