Array creation - Zygote error - android

I am relatively new to Android and i want to create an array that increases in size and i declared an array like this:
private Sprite something[]; //sprite is my custom class that does sprites
And i want to add elements like this, but it gives me error...
something[i++] = new Sprite(spriteSheet,numRows,numColumns,true,x,y);
//i is number of elements and Sprite(...) is the constructor
Can someone tell me what i am doing wrong here, and why i get the zygote error and a null pointer exception?
Thanks!

Java doesn't really work like Javascript does. Arrays have fixed size, as per something = new Sprite[10]; where the element indices of something are 0 to 9.
The functionality you want can however be achieved using List<Sprite> something = new ArrayList<Sprite>();, and then something.add(new Sprite(spriteSheet, numRows, numColumns, true, x, y));.
EDIT:
Iteration of an ArrayList works like this:
List<Sprite> sprites = new ArrayList<Sprite>();
for(Sprite sprite : sprites)
{
sprite.print();
}
However, the following statement:
List<Sprite> sprites = new ArrayList<Sprite>();
for(Sprite sprite : sprites)
{
sprites.remove(sprite);
}
Will throw a ConcurrentModificationException.
Therefore, you can either use an iterator manually:
List<Sprite> sprites = new ArrayList<Sprite>();
Iterator<Sprite> iterator = sprites.iterator();
while(iterator.hasNext())
{
Sprite sprite = iterator.next();
...
iterator.remove();
}
Or, personally when I need to modify the elements on the list during iteration, I use the following:
List<Sprite> sprites = new ArrayList<Sprite>();
for(int i = 0; i < sprites.size(); i++)
{
Sprite sprite = sprites.get(i);
...
sprites.remove(i--);
}
Although if I remember correctly, the iterator is the recommended approach.

Related

Graphview not showing all x axis values

See picture below, trying to figure out why they it is skipping the '1', '3', and so forth.
Where i set the series and graph:
DataPoint[] dataPoints = new DataPoint[rankList.size()]; // declare an array of DataPoint objects with the same size as your list
for (int i = 0; i < rankList.size(); i++) {
dataPoints[i] = new DataPoint(i, Double.parseDouble(rankList.get(i))); // not sure but I think the second argument should be of type double
}
BarGraphSeries<DataPoint> series2 = new BarGraphSeries<DataPoint>(dataPoints); // This one should be obvious right? :)
series2.setAnimated(true);
series2.setTitle("Random Curve 1");
series2.setColor(Color.GREEN);
series2.setSpacing(30);
series2.setDataWidth(1);
graph2.getViewport().setMinX(-1);
graph2.getViewport().setMaxX(12);
graph2.addSeries(series2);
The right info is being plotted, but i've tried a bunch of stuff from the docs and get get it to work.
Sorry I misunderstood your question...
This will help:
yourGraph.getGridLabelRenderer().setNumHorizontalLabels(numberOfBars);
It actually shows all bars. You've set series2.setSpacing(30);.
Instead do series2.setSpacing(0);.

Filling a texture pattern over another texture in unity

I am trying to create a character customization in unity for android. Now the scenario is that i have a dress model which is a texture2D, also a number of patterns and colors that the user can apply on this model of dress. Now when the user applies a pattern on to the dress i need to change the dress to be displayed in that pattern. For color i was able to change the rgb value to the desired color value. But for the pattern I will need to traverse through each pixel of the dress and apply the patterns corresponding color to the pixel of the dress. I achieved this by the following code.
IEnumerator Print() {
Texture2D tex = DressTexture;
Color32[] DressColor = tex.GetPixels32();
Color32[] PatternColor = PatternTexture.GetPixels32();
int j = 0;
Texture2D NewDressPattern = new Texture2D(tex.width, tex.height, TextureFormat.ARGB32, false);
for(int i = 0; i < DressColor.Length; i++) {
if(DressColor[i].a != 0) {
DressColor[i] = PatternColor[j];
j++;
if(j == PatternColor.Length - 1) {
j = 0;
}
}
else {
j = 0;
}
yield return null;
}
NewDressPattern.SetPixels32(DressColor);
NewDressPattern.Apply();
Debug.Log("texture created");
Sprite spr = Sprite.Create(NewDressPattern, new Rect(0, 0, tex.width, tex.height), Vector2.zero);
Debug.Log("sprite created");
sprite.sprite = spr;
}
Now the problem is this operation is too slow to complete. Any suggestions for a better way to achieve this would be really helpful. Also i am not aware of shaders much.
Texture operations always require some time consuming processing. There are workarounds you can do to minimize the impact on user. Like doing calculations multithreaded or nonblocking (I think that's what you are doing right now). But they will only minimize the problem, won't solve it.
You did not mention if the texture used in a 2D environment as a sprite or used on a 3D model.
For a 2D game:
What I would do is I would use a separate sprite for each object. Then I would overlap sprites and the result will exactly be like what you are trying to do above.
For a 3D model:
You can use some simple shaders to overlap multiple textures. Just Google it and you will have plenty of examples. Simple shaders like these does not require rocket science knowledge :)
Also, render-to-texture technique can be used to pre-render multiple texture passes. For example, the code below uses built-in "Diffuse Detail" shader to combine Texture2D objects and put result in RenderTexture:
public RenderTexture PreRenderCustomDressTexture(int customTextureWidth, int customTextureHeight, Texture2D pattern1, Texture2D pattern2)
{
RenderTexture customDressTexture = new RenderTexture( customTextureWidth, customTextureHeight, 32, RenderTextureFormat.ARGB32, RenderTextureReadWrite.Default );
Material blitMaterial = new Material( Shader.Find( "Diffuse Detail" ) );
blitMaterial.SetColor( "_Color", Color.white );
blitMaterial.SetTexture( "_MainTex", pattern1 );
blitMaterial.SetTexture( "_Detail", pattern2 );
Graphics.Blit( pattern1, customDressTexture, blitMaterial );
return customDressTexture;
}

Why is my Body returning null?

I'm using AndEngine to make a game for the Android platform. I need to detect if a circular body contacts a circular sprite. To do this, I'm calculating the centers and radii of both and using pythag to determine if they are indeed touching. However, I keep getting a nullpointerexception when I try to get the x coordinate of my body. spriteNum increases every time the screen it touched and a sprite is created. Any ideas why? My code:
public class grow implements Runnable{
Sprite sp;
Body body[] = new Body[100];
public grow(Sprite sprite){
sp = sprite;
}
#Override
public void run() {
float radf, rads; //fill radius/stationary radius
float[] fill; //fillx/stationaryx
float fx=0, fy=0, sx, sy;
while(down){
//Log.e("Tag","Running thread. Down = "+Boolean.toString(down));
yourSprite[spriteNum].setScale(scale += 0.1);
fill = yourSprite[spriteNum].getSceneCenterCoordinates();
fill[0]=fx;
fill[1]=fy;
radf=yourSprite[spriteNum].getHeightScaled()/2;
Log.e("Fill X before for",Float.toString(fx));
if(spriteNum>0)
for(int x=0;x<spriteNum;x++){
rads=yourSprite[x].getHeightScaled()/2;
sx = body[x].getWorldCenter().x; //Null pointer exception
sy = body[x].getWorldCenter().y;
if(Math.sqrt(Math.pow((fx-sx),2)+Math.pow((fy-sy),2))<(radf+rads))
down = false;
Log.e("Fill x",Float.toString(fx));
Log.e("Stat x",Float.toString(sy));
}
try {
Thread.sleep(75);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
body[spriteNum] = PhysicsFactory.createCircleBody(mPhysicsWorld, yourSprite[spriteNum], BodyType.DynamicBody, FIXTURE_DEF);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(yourSprite[spriteNum], body[spriteNum], true, true));
if(body[0]!=null)
Log.e("Body created","not null"); //This says it's not null, but when I did the same thing just inside of my for() loop and it did say it was null
}
I guess it's because you have initialized body array Body body[] = new Body[100] but not individual Body elements in it. So when you access body[x] it returns null. You should also initialize body elements in array. Something like:
for(int i=0; i<body.length; i++) {
// probably some cod here..
body[i] = new Body(..);
// probably some cod here..
}
Another cause that came into my mind for your problem is, you said:
spriteNum increases every time the screen it touched and a sprite is
created.
So it can be possible that you have initialized some body elements on startup and then when sprite count increases you do not create new elements in body array, so when you try body[0] it is not null but for new sprites for which body elements may not have been initialized you get null and thus NPE.

Andengine - adding sprites avoiding collisions with existing

I'm creating sprites and adding it to scene in loop in random places. I just want to check if newly created Sprite will cause collision with one of existing ones. Is there any simple way to check it?
When you create a new sprite, add user data to it:
sprite.setUserData("sprite");
And then, after you created a positioned the sprite, before you add it iterate over the existing sprites:
int count = scene.getChildCount();
for(int i = 0; i < count; i++) {
IEntity entity = scene.getChild(i);
if(entity instanceof Sprite) {
if(entity.getUserData().equals("sprite"))
if(((Sprite)entity).collidesWith(newSprite))
//Don't add the new sprite.
}
The user data can be anything you want, it doesn't have to be a string.

Integer Array Handling

I have a 2D game that uses two integer arrays to track x and y coordinates as shown below:
private int gridX[] = { 0,0,0,0,0 }
private int gridY[] = { 0,0,0,0,0 }
The problem is I can have a LOT of objects on the screen that needs to be tracked. Is there a way to add integers / create new blocks as needed? IE in a loop, do something like
gridX[].add(); or something like that. I'm relatively new to java and droid development and I'm having trouble finding a good tutorial or example that shows how to do this without having to initialize the gridX and gridY to sizes of 100 or so.
This is important, as I am about 90% sure that all those unused 0's are causing androids garbage cleanup to lag my application.
Why dont you use an array list instead of an Integer array?
that way you can dynamically add items to the list
ArrayList<Integer> myList = new ArrayList<Integer>();
myList.add(1);
myList.add(2);
Why not also use the Point class?
List<Point> points = new ArrayList<Point>();
points.add(new Point(0, 0));
points.add(new Point(50, 70));
Point point = points.get(1);
Log.d("MyApp", String.format("The point is: (%d, %d)", point.x, point.y);
This way you are keeping track of your x and y coordinates together and there is less opportunity for error.

Categories

Resources