Android Can't save to an array - android

I have global array. When i want to save something in some method and after that show it from that array it has error NullPointerException. Array is Object type. Code is like this
class Something {
public CoordinatesObject[] coordinates;
Something() {
coordinates = new CoordinatesObject[4];
}
public String myMethod() {
if (coordinates.length==0){
coordinates[0] = new CoordinatesObject(0,0);
}
}
return Integer.toString(coordinates[0].getX());
}
What's wrong?
Sorry I have updated the code. I've created a new array in constructor

You created an array with this line:
coordinates = new CoordinatesObject[4];
and then you're trying to create CoordinatesObject like that:
if (coordinates.length==0){
coordinates[0] = new CoordinatesObject(0,0);
}
but coordinates.length is going to be equal to 4 which means an object of CoordinatesObject class won't be created.

You need to actually allocate space for the array, right now you just have a reference to nothing.
Also note that arrays are fixed-length, you may want to consider using a collection (like a list) instead, depending on your needs.

You have to create the Array with new as well.

Currently, you have a NULL reference. As the previous poster points out, you need to define and create some space for your array.

Related

How can I overwrite the data in an element of an array of structures?

So, I have this structure:
typedef struct{
int serialNumber;
char name[100];
float price;
int quantity;
}Products;
And I created an array of structures dynamically.
The task was to 'simulate' a grocery store, with the user able to add and edit the items sold by the store. The following code snippets are for editing structure data.
void overwrite(Products store){
printf("Enter new serial number: ");
scanf("%d", &(store.serialNumber));
getchar();
printf("Enter new product name: ");
fgets(store.name, 100, stdin);
store.name[strlen(store.name)-1]='\0';
printf("Enter new product price: ");
scanf("%f", &(store.price));
printf("Enter new product quantity: ");
scanf("%d", &(store.quantity));
}
void editData(Products *store, int storeCapacity){ //storeCapacity needed to invoke printData(), assume a working code for the function.
int choice;
printData(store, storeCapacity);
printf("Enter slot number of product here: ");
scanf("%d", &choice);
overwrite(store[choice]);
}
Here's the catch, even though this code works, when I try to print the data, the data displays the values which should be overwritten. Have I forgotten to do something? I wish you could help me.
BTW, I code on an Android phone.
void overwrite(Products store){
C is pass by value, you need to pass a pointer to Products (i.e., Products *store) and modify the overwrite call in editData accordingly.
Basically the problem is that in C you pass arguments by value. So when you specify this signature
void overwrite(Products store)
and you invoke it somewhere:
Products myStore;
overwrite(myStore);
what happens is that a copy of myStore is created and placed on the stack, then the value is passed to the function. This means that every modification done to the Products object inside overwrite applies on the passed copy, not on the original object. This copy is then discarded when exiting the scope of overwrite function.
To solve this problem you must pass a pointer to the object, that is passed by value but being an address will point to the exact same myStore object. This is done in this way:
void overwrite(Products* store)
{
..
scanf("%f", &store->price);
..
}
Products myStore;
overwrite(&myStore);
According to Ouah, I passed the structure as the value itself, which did happen in my code.
So what I did is...
void overwrite(Products * store){ //formal parameter changed into a pointer
//codes here
}
And...
overwrite(&(store[choice])); /* actual parameter changed into a pointer by affixing ampersand*/
Further explanations of the codes' misbehavior were explained by Jack. I extend my gratitudes to you. The code now worked as it should be.

Adding items to Array List with specified objects

I am working in a translator kind of app and i need some help.
I have a class with getters and setters for my Array List objects. Each object has a phrase, a meaning, and usage.
so i have this to create my list:
ArrayList<PhraseCollection> IdiomsList = new ArrayList<PhraseCollection>();
now how do i add these objects to the list, each object containing the phrase, its meaning, and a use in a sentence?
For Example: The Layout would be something like this
Phrase
Kick the bucket
Meaning
When someone dies
Usage
My grandfather kicked the bucket
Thanks a lot
this is what i came up with that worked for me
private void loadIdioms() {
//creating new items in the list
Idiom i1 = new Idiom();
i1.setPhrase("Kick the bucket");
i1.setMeaning("When someone dies");
i1.setUsage("My old dog kicked the bucket");
idiomsList.add(i1);
}
ArrayList has a method call add() or add(ELEMENT,INDEX);
In order to add your objects you must first create them
PhraseCollection collection=new PhraseCollection();
then create the ArrayList by
ArrayList<PhraseCollection> list=new ArrayList<PhraseCollection>();
add them by :
list.add(collection);
Last if you want to render that in your ListView item, you must override the toString() in your PhraseCollection.
I suppose you would use the add(E) method (http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#add(E)).
Here is an example using your example provided.
public class Phrase {
public final String phrase, meaning, usage;
//TODO: implement getters?
public Phrase(String phrase, meaning, usage) {
this.phrase = phrase;
this.meaning = meaning;
this.usage = usage;
}
}
and use it like this:
// create the list
ArrayList<Phrase> idiomsList = new ArrayList<Phrase>();
// create the phrase to add
Phrase kick = new Phrase("kick the bucket", "When someone dies", "My grandfather kicked the bucket");
// add the phrase to the list
idiomsList.add(kick);

Cannot restore Object from Instance state: parsing error

I am trying to restore an array of Objects from a savedInstanceState. I added each one to the Bundle individually here: (rhythm is the array of Objects)
#Override
public void onSaveInstanceState(Bundle outState){
outState.putInt("numParts",rhythm.length);
for(int index = 0;index<rhythm.length;++index){
outState.putSerializable(""+index,rhythm[index].beat);
}
super.onSaveInstanceState(outState);
}
When the onRestoreInstanceState() method is called, I try to assign my rhythm array with the Objects from the Instance State here: (it isn't null)
#Override
public void onRestoreInstanceState(Bundle savedInstanceState){
rhythm = new Part[savedInstanceState.getInt("numParts")];
for(int index = 0; index<rhythm.length;++index){
Object middleMan =savedInstanceState.getSerializable(""+index);
if(middleMan==null){
System.out.println("It's null...");
}
rhythm[index]=(Part) middleMan;
}
}
It throws a ClassCastException when I parse to a Part every time. Part implements Serializable. Why is it not allowing me to parse? Will I need to do custom serialization?
Please help!
I am guessing that Part is a type that you have created? So instead of treating Part as an array
rhythm = new Part[savedInstanceState.getInt("numParts")];
You want to instantiate a new Part object like so:
rhythm = new Part(savedInstanceState.getInt("numParts"));
Other assumptions:
rhythm is a member variable
The constructor for Part takes a single integer
Okay I just did it as the whole array and it worked... I don't really know why, but it did. Thanks for giving me the idea to just pass the whole array. #Error 454

how to link my getEmptyForeignCollection() object with my parent object?

I want to persist an object with two foreignCollections.
But when I try to query the object, my foreignId is always null.
I already read this answers but it doesn't really help me: Collections in ORMLite
VOPerception perception = new VOPerception();
perception.setOrientation(daoOrientation.createIfNotExists(
orientationLocalizer.getCurrentOrientation()));
ForeignCollection<VOAccessPoint> fAp =
daoPerception.getEmptyForeignCollection("accessPoints");
fAp.addAll(wifiLocalizer.getCurrentScanResultMap());
perception.setAccessPoints(fAp);
daoPerception.create(perception);
List<VOPerception> list = daoPerception.queryForAll();
here data are correctly stored but VOAccessPoint objects have no link with the parent VOPerception object.
Here are my two classes:
public class VOPerception {
#DatabaseField(generatedId=true)
private int per_id;
#ForeignCollectionField(eager=true)
ForeignCollection<VOAccessPoint> accessPoints;
...
}
public class VOAccessPoint{
#DatabaseField(generatedId=true)
private int ap_id;
#DatabaseField(foreign=true,columnName="apForeignPerception_id")
private VOPerception apForeignPerception;
...
}
Your queryForAll() is returning no objects because none of your VOAccessPoint instances ever set their apForeignPerception field to be perception. Adding the VOAccessPoint objects using the ForeignCollection added them to the DAO but did not automagically assign their apForeignPerception field.
You should do something like:
...
Collection<VOAccessPoint> points = wifiLocalizer.getCurrentScanResultMap();
for (VOAccessPoint point : points) {
point.setApForeignPerception(perception);
}
fAp.addAll(points);
...
I can see how you might think that this would be handled automagically but at the time they are added to the ForeignCollection, the perception is not even assigned. I suspect that there is a missing feature for ORMLite here or at least a better exception.
I would recommend to use assignEmptyForeignCollection(Obj parent, fieldName). This will create a new foreign collection and all objects you will add via add(Obj element) will have the parent value set automatically.

Bundle of array of arraylist

How can I put an array of arrayList into a Bundle?
ArrayList < myObjects >[] mElements;
Make YourObject implement the Parcelable interface, then use bundle.putParcelableArraylist(theParcelableArraylist).
Edit: whoops misread the question. Why do you want to save an array of arraylist? If its for persisting in an orientation change, maybe you want to use onRetainNonConfigurationInstance instead?
Edit 2: Ok, here goes. Create a new Wrapper class that implements Parcelable (note that myObjects also have to be parcelable). The writeToParcel method will look something like this:
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(mElements.length);
for(ArrayList<MyObject> element : mElements) {
dest.writeParcelableArray(element.toArray(new MyObject[0]), flags);
}
}
And the constructor:
private Wrapper(Parcel in) {
int length = in.readInt();
//Declare list
for (int i = 0; i < length; i++) {
MyObject[] read = in.readParcelableArray(Wrapper.class.getClassLoader());
//add to list
}
}
Not possible using bundle, as bundle allows arraylist of primitives only...
Try to use parcleable or application level data or static variable (bad practice).
If your objects support serialization, marked with the Serializable interface, then you should be able to use bundle.putSerializable.
ArrayList supports Serializable , but I'm not sure about a plain array.
I just use putSerializable(myarraylistofstuff) and then I get back with a cast using get(), you just need to silence the unchecked warning. I suspect (correct me if wrong) you can pass any object faking it as Serializable, as long you stay in the same process it will pass the object reference. This approach obviously does not work when passing data to another application.
EDIT: Currently android passes the reference only between fragment, I've tried to pass an arbitrary object to an Activity, it worked but the object was different, same test using arguments of Fragment showed same Object instead.
Anyway it deserializes and serializes fine my Object, if you have a lot of objects it's better to use Parcel instead

Categories

Resources