How to pass a multidimensional double array in Android? - android

I am trying to pass my double array from one activity to the other. However I cannot figure out how to do this, as the methods I' ve tried just give me error messages.
This is what I' ve tried in my MainActivity:
intent.putExtra("nutritional_value", temp.nutritional_value);
(in case necessary: I have defined the variable 'temp' in a third java class like this):
SingleItem temp = list.get(position);
This is what I' ve tried to do in my second activity:
double[][] nutritional_value = intent.getDoubleArrayExtra("nutritional_value", 0);
I' m not exactly new to Android but I' m still in the learning curve, please tell me if you know how I can fix this, I would really appreciatie it.
Thanks

Try serialzing the array, something along the lines of
double[][] nutritional_value =....
Bundle bundle = new Bundle();
bundle.putSerializable("array_array", nutritional_value );

You can't like that. putExtra doesn't take multidimentsional . You'll need to either:
Wrap it in a Parcelable class you will have to write.
Serialize it in some other way. Gson to string for example. Gson will cope with multidimensional arrays.
getDoubleArrayExtra refers to a single dimensional array of double values.

Related

Passing an array of GeoCodes from 1 intent to another

Just wondering what the best way to pass an array list of GeoCodes is?
I can seem to put the arraylist into the intent okay using
saveRouteIntent.putExtra("waypoints", waypoints);
But I cant see how I would get the list in the new activity.
I could build two double arraylists and pass them across and then create the geocode array list again on the other side but im assuming there is a better method?
Use serializable while passing data through putExtra()
First Activity:
ArrayList<String> waypoints= new ArrayList<String>();
saveRouteIntent.putExtra("waypoints", waypoints);
In the other Activity:
ArrayList<String> myList = (ArrayList<String>) getIntent().getSerializableExtra("waypoints");
If its an array you can use serializable to putExtra() , but in this case you'll have to implement your own subclass that extends BasicNameValuePair , for a perfect implementation try this.

Restoring an ArrayList of custom objects

In my app (which is a game), I have an 'Enemy' class, for example like so:
public class Enemy extends Sprite implements Serializable {
public Enemy(EnemyType type){
super();
}
}
I have then declared an ArrayList like so:
ArrayList<Enemy> enemyList = new ArrayList<Enemy>();
To which I can add enemies:
enemyList.add(bird);
enemyList.add(bee);
When saving to the Bundle I simply put:
bundle.putSerializable("Enemies", enemyList);
And when restoring from the Bundle, I have this:
enemyList = (ArrayList<Enemy>) savedState.getSerializable("Enemies");
Now, it does seem to restore the arraylist (I can check it's size and it is always correct - ie, the same size on restoring from the bundle, as it was when saving to the bundle.
I have also logged for example, the first index of the ArrayList and sure enough it lists the enemy instance as being there.
However, if I try to manipulate the ArrayList at any time post-restoration, I get an exception telling me that I'm trying to perform [whatever action] on a Null object (enemyList).
If I simply populate the list myself, so have something like:
enemyList = (ArrayList<Enemy>) savedState.getSerializable("Enemies");
enemyList.add(bird);
enemyList.add(bee);
Then everything works as expected.
I'm assuming this has something to do with the fact that the super class of Enemy isn't serialised? However, if I serialise this, I get a 'notSerializableException' error.
Please note, I'm not really too worried about saving/restoring the actual Enemy objects to the Bundle, I can handle this manually. Rather I just want the list to be in the same state as it was. And I thought that what was stored in the ArrayList were just references to the objects in question, therefore I can't work out why this is happening?
Any ideas what I'm doing wrong or is there a better method to achieve that which I'm trying to achieve?
The recommended way of doing this in Android is to make the objects you want to persist to be Parcelable. This is a type of serialization specific to Android.
Have a look at the official documentation here

Out Of Memory Android while loading my pub vars

Block Array or multidimensional array Variables. For some reason my app is throwing out of memory on my loading of my pub vars class. This started happening when I started using Block Arrays. It works on actual devices but not on the emulators. Any thoughts? Should I set my block arrays to actual needs?
Current Block Arrays:
public static String[][] Name = new String[1000][1000];
however I only use maybe 10 or so. Is the device allocating space for the potential of the 1000 and is that why it is errors out? If so, how can I use these as the need may grow and I do not want to put a small limit on it. Thanks in advance for any thoughts.
With
public static String[][] Name = new String[1000][1000];
you are allocating 1 million strings (1000x1000) which is quite a bunch. If the information on this page is correct each string at least takes 40 bytes, so that would be around 39 Mbytes in your case and this can easily be too much memory on the heap for 1 activity. I would start there to refactor if you are only using 10. There is probably a better solution than your approach but without any more details on your code it's hard to give them. But of the top of my head, why not use a Set<String> or List<String> ?
Edit: So it's seems to me that you just want a Collection that scales dynamically. For that array is not the best choice. There are many of datatypes for that but one simple example whould be an ArrayList which also uses a array as backing datatype but by default will be instanciated with a capacity of 10 and expands dynamically if you continue to add elements
List<String> stringList = new ArrayList<String>();
stringList.add("string1");
stringList.add("string2");
...
If you want each element to have its own list of strings just create an object for that:
public class CompoundString {
private String key;
private List<String> stringList;
...
}
and use it like this
List<CompoundString> compoundStringList = new ArrayList<CompoundString>();
compoundStringList.add(new CompoundString("string1", new ArrayList<String>());
or just use a map:
Map<String,List<String>> stringMap = new HashMap<String,List<String>>();
stringMap.put("string1", new ArrayList<String>());
This is pretty basic concept in most programming languages and I would start to read some docs about the various collections:
http://docs.oracle.com/javase/7/docs/api/java/util/List.html
http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
http://docs.oracle.com/javase/7/docs/api/java/util/Map.html
http://www.mkyong.com/java/what-is-the-different-between-set-and-list/

Handling arraylists created in a custom class (newbie confusion)

Basically, I need to add items to the arraylist. Am I correct in using a separate class (this is in part what I am practicing here) or is that a stupid idea because it is basically just an arraylist. I thought I would create a class because I want to randomise additions to it, etc. Alternately, since it is just an arraylist class, should I use "extends arraylist" or something similar??? Code examples most welcome. I am obviously missing some crucial programming theory here. Thank you.
NOTE I have removed what I think is unrelated code
I have a main:
public class cgame2 extends Activity {
private ArrayList<Integer> cToChooseFromImages; // clear image list
colourlist colourlistused = new colourlist();
colourlist userscolourlist = new colourlist();
....truncated....towards the end of my code I have......
colourlistused.randomaddnewitem();
And I have a class (called colourlist):
import java.util.ArrayList;
import java.util.Random;
import android.util.Log;
public class colourlist {
private ArrayList<Integer> clist;
private int picked;
int imagetodisp;
public colourlist() {
}
public void randomaddnewitem() {
Random randomtouse = new Random(System.nanoTime());
picked = randomtouse.nextInt(3);
clist.add(picked); // this is where the program crashes according to log info
}
public void addnewitem(int itemtoadd) {
clist.add(itemtoadd);
}
.....etc.....
If you're adding functionality to ArrayList, the best way is just the way you have done it.
Create a member ArrayList of your class and create functions to extend the behavior. This is called Composition.
Contrast with Inheritance, or creating a subclass of ArrayList, which can create more problems by unnecessarily coupling your implementation to ArrayList.
Don't forget to initialize the list. The best way would be:
List<Integer> clist = new ArrayList<Integer>();
Use the interface List to make your code more flexible if you choose to change the specific list implementation later.
Creating a class for your array list isn't a bad idea, classes in and of themselves are data structures, and this will allow to manipulate the data easier. By having the array list in it's own class, you will be able to get it, set it, send it, alter it, etc, with ease. However, when it comes to creating classes, you generally want to create classes that could be considered objects. If you are a beginning programmer, I would recommend exploring and researching object oriented analysis and design, as that will help you determine what should and shouldn't be classes.
And, as others have pointed out, make sure you initialize your array list:
List<Integer> clist = new ArrayList<Integer>();
As for extending ArrayList vs. List, I would use ArrayList because 1. It has all the methods and functionality of List (because is is an implementation of List) and 2. It is backed by an array, which is what you are using. Just my preference, feel free to do some research and figure out what is going to work best for what you need; a List may be all you need, in which case, you should use that.
One other things I will point out, since it looks like you are creating a game, is that if you are going to pass and object, in your case and ArrayList, you are going to want to get familiar with the Parcelable interface. It is what will allow you to pass data from one activity to another. Here is a link that will get you started, along with a tutorial that might offer some insight to what is needed:
Tutorial for Parceleable:
http://shri.blog.kraya.co.uk/2010/04/26/android-parcel-data-to-pass-between-activities-using-parcelable-classes/
Developer Info:
http://developer.android.com/reference/android/os/Parcelable.html
Best of luck!

Android: Initialize a two dimensional array of type <class>

I'm sure that this is some basic misunderstanding on my part, but ...
I want to have a class:
public class Foo {
String bar;
}
And the declare a two dimensional array of them:
Foo[][] foobar = new Foo[3][3];
Which works fine, but when I get to that point and look at foobar, each element is null. Now I can initialize each element at this point, but this just seems wrong. I don't know if I need to have some special constructor in my class or what.
I'm new to Android and Java, so any help would be appreciated.
Dan
you do have to initialize each element. what you're doing is creating an empty 2 dimensional array of 9 elements. what you can do, however is to have a for loop nested within another for loop that initializes each element to a new Object() (or whatever class you need). in that case nothing will be null.

Categories

Resources