How to do something in MainActivity after the AsyncTask onPostExecute is done - android-studio

I am trying to get the LatLngs so I can find the nearest place of the search result, I am trying it this way, but the getLatLngs returns null because it hasn't yet initialized.How do I access stuff from MainActivity after the onPostExecute is done.Thank you in advance.
public class GetNearbyPlaces extends AsyncTask<Object, String, String> {
private ArrayList<LatLng> LatLngs = new ArrayList<>();
private LatLng latLngMain;
private LatLng shortestLatLng;
#Override
protected void onPostExecute(String s) {
List<HashMap<String, String>> nearbyPlacesList = null;
DataParser dataParser = new DataParser();
nearbyPlacesList = dataParser.parse(s);
shortestLatLng = DisplayNearbyPlaces(nearbyPlacesList);
}
private LatLng DisplayNearbyPlaces(List<HashMap<String, String>> nearbyPlacesList)
{
int index = 0;
LatLng shortest;
double shortestDistance = Double.MAX_VALUE;
for(int i = 0;i<nearbyPlacesList.size();i++)
{
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> googleNearbyPlace = nearbyPlacesList.get(i);
String nameOfPlace = googleNearbyPlace.get("place_name");
String vicinity = googleNearbyPlace.get("vicinity");
double lat = Double.parseDouble(googleNearbyPlace.get("lat"));
double lng = Double.parseDouble(googleNearbyPlace.get("lng"));
LatLng latLng = new LatLng(lat,lng);
LatLngs.add(latLng);
markerOptions.position(latLng);
markerOptions.title(nameOfPlace + " : " + vicinity);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
if(mMap!=null)
mMap.addMarker(markerOptions);
}
for(int i = 0;i<LatLngs.size();i++)
{
double deltaLat = latLngMain.latitude - LatLngs.get(i).latitude;
double deltaLng = latLngMain.longitude - LatLngs.get(i).longitude;
double distanceInDegree = Math.sqrt(deltaLat * deltaLat + deltaLng * deltaLng);
double distanceInMeter = distanceInDegree * 4000;
if(distanceInMeter<shortestDistance)
{
shortestDistance=distanceInMeter;
index = i;
}
}
shortest = LatLngs.get(index);
return shortest;
}
public LatLng getShortestLatLng()
{
return shortestLatLng;
}
}
In MainActivity
getNearbyPlaces.execute(transferData).get();
nearestDistance = getNearbyPlaces.getShortestLatLng();

You must initialize your LatLngs field before calling methods on it.
Replace
private ArrayList<LatLng> LatLngs;
to
private ArrayList<LatLng> LatLngs = new ArrayList<>();
In your code, you initialize it only in loop of DisplayNearbyPlaces method, and if, for example,
nearbyPlacesList is empty, then body of this loop does not run and field remains uninitialized.

Related

How does a foreachPartition works in sparks?

I am new to apache spark and am trying to run a custom nearest neighbor algorithm on an RDD that has been partitioned into 2 parts using a custom partitioner. The JavaPairRDD contains the graph details and the random object created on the graph.
According to my logic, I am building subgraphs for each partition, and I am running a custom algorithm on each subgraph. It seems to be working "although not properly". I am not sure if this is the correct way to apply action in each partition. I am adding my code and the results as well. Comments and suggestions are highly appreciated.
// <Partition_Index_Key, Map<Source_vertex, Map<Destination Vertex, Tuple2<Edge_Length, ArrayList of Random Objects>>
JavaPairRDD<Object, Map<Object, Map<Object, Tuple2<Double, ArrayList<RoadObject>>>>> adjVertForSubgraphsRDD = jscontext
.parallelizePairs(adjacentVerticesForSubgraphs)
.partitionBy(new CustomPartitioner(CustomPartitionSize));
//applying foreachPartition action on JavaPairRDD
adjVertForSubgraphsRDD.foreachPartition(
new VoidFunction<Iterator<Tuple2<Object, Map<Object, Map<Object, Tuple2<Double, ArrayList<RoadObject>>>>>>>() {
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public void call(
Iterator<Tuple2<Object, Map<Object, Map<Object, Tuple2<Double, ArrayList<RoadObject>>>>>> tupleRow)
throws Exception {
int sourceVertex;
int destVertex;
double edgeLength;
int roadObjectId;
boolean roadObjectType;
double distanceFromStart;
CoreGraph subgraph0 = new CoreGraph();
CoreGraph subgraph1 = new CoreGraph();
while (tupleRow.hasNext()) {
Map<Object, Map<Object, Tuple2<Double, ArrayList<RoadObject>>>> newMap = tupleRow.next()
._2();
if ((Integer.parseInt(String.valueOf(tupleRow.next()._1())) == 0)) {
for (Object srcVertex : newMap.keySet()) {
for (Object dstVertex : newMap.get(srcVertex).keySet()) {
if (newMap.get(srcVertex).get(dstVertex)._2() != null) {
sourceVertex = Integer.parseInt(String.valueOf(srcVertex));
destVertex = Integer.parseInt(String.valueOf(dstVertex));
edgeLength = newMap.get(srcVertex).get(dstVertex)._1();
subgraph0.addEdge(sourceVertex, destVertex, edgeLength);
for (int i = 0; i < newMap.get(srcVertex).get(dstVertex)._2()
.size(); i++) {
int currentEdgeId = subgraph0.getEdgeId(sourceVertex, destVertex);
roadObjectId = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getObjectId();
roadObjectType = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getType();
distanceFromStart = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getDistanceFromStartNode();
RoadObject rn0 = new RoadObject();
rn0.setObjId(roadObjectId);
rn0.setType(roadObjectType);
rn0.setDistanceFromStartNode(distanceFromStart);
subgraph0.addObjectOnEdge(currentEdgeId, rn0);
}
} else {
sourceVertex = Integer.parseInt(String.valueOf(srcVertex));
destVertex = Integer.parseInt(String.valueOf(dstVertex));
edgeLength = newMap.get(srcVertex).get(dstVertex)._1();
subgraph0.addEdge(sourceVertex, destVertex, edgeLength);
}
}
}
} else if ((Integer.parseInt(String.valueOf(tupleRow.next()._1())) == 1)) {
for (Object srcVertex : newMap.keySet()) {
for (Object dstVertex : newMap.get(srcVertex).keySet()) {
if (newMap.get(srcVertex).get(dstVertex)._2() != null) {
sourceVertex = Integer.parseInt(String.valueOf(srcVertex));
destVertex = Integer.parseInt(String.valueOf(dstVertex));
edgeLength = newMap.get(srcVertex).get(dstVertex)._1();
subgraph1.addEdge(sourceVertex, destVertex, edgeLength);
for (int i = 0; i < newMap.get(srcVertex).get(dstVertex)._2()
.size(); i++) {
int currentEdgeId = subgraph1.getEdgeId(sourceVertex, destVertex);
roadObjectId = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getObjectId();
roadObjectType = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getType();
distanceFromStart = newMap.get(srcVertex).get(dstVertex)._2().get(i)
.getDistanceFromStartNode();
RoadObject rn1 = new RoadObject();
rn1.setObjId(roadObjectId);
rn1.setType(roadObjectType);
rn1.setDistanceFromStartNode(distanceFromStart);
subgraph1.addObjectOnEdge(currentEdgeId, rn1);
}
} else {
sourceVertex = Integer.parseInt(String.valueOf(srcVertex));
destVertex = Integer.parseInt(String.valueOf(dstVertex));
edgeLength = newMap.get(srcVertex).get(dstVertex)._1();
subgraph1.addEdge(sourceVertex, destVertex, edgeLength);
}
}
}
}
}
// Straight forward nearest neighbor algorithm from each true to false.
ANNNaive ann = new ANNNaive();
System.err.println("-------------------------------");
Map<Integer, Integer> nearestNeighorPairsSubg0 = ann.compute(subgraph0, true);
System.out.println("for subgraph0");
System.out.println(nearestNeighorPairsSubg0);
System.err.println("-------------------------------");
System.err.println("-------------------------------");
Map<Integer, Integer> nearestNeighorPairsSubg1 = ann.compute(subgraph1, true);
System.out.println("for subgraph1");
System.out.println(nearestNeighorPairsSubg1);
System.err.println("-------------------------------");
}
});

How to animate a filled triangle (drawn by a path) in Android Studio

I'm trying to build a jigsaw-like app for Android that involves the user moving polygonal pieces around the screen by touch event.
I can draw - for example - a triangle, and fill it. I can also move it smoothly round the screen but it leaves a trace - so that the screen rapidly fills up :-(
So I am wondering how to adjust the onDraw method so that the previous positions of the triangle are not included. Or is there some other technique? The question has been asked once before but did not get a satisfactory answer. I am quite new to Android work so I am sure a kind expert will be able to point me in the right direction!
The view:
public class GameView extends View {
public Triangle T1;
Paint paint = new Paint();
private Path path;
public GameView(Context context) {
super(context);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.GREEN);
initTriangle();
}
public void initTriangle() {
int T1Points[][] = new int[3][2];
T1Points[0][0] = -200;
T1Points[0][1] = -100;
T1Points[1][0] = 200;
T1Points[1][1] = -100;
T1Points[2][0] = 0;
T1Points[2][1] = 100;
float[] position = new float[2];
position[0] = (float) 200.0;
position[1] = (float) 100.0;
T1 = new Triangle("T1", T1Points, position);
path = T1.getPath();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float[] pos = new float[2];
pos[0] = event.getX(); //nextx;
pos[1] = event.getY(); //nexty;
T1.setPosition(pos );
Path path = new Path();
path = T1.getPath();
postInvalidate();
return true;
}
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
}
Triangle class:
public class Triangle {
public int[][] myPoints;
public Path path;
public String myname;
public float[] position;
public Triangle (String name, int[][] newpoints, float[] posn) {
myPoints = new int[4][2];
int i;
for (i = 0; i < 3; i++) {
myPoints[i][0] = newpoints[i][0];
myPoints[i][1] = newpoints[i][1];
}
myPoints[3][0] = newpoints[0][0]; // closed circuit for future needs
myPoints[3][1] = newpoints[0][1];
path = new Path();
position = new float[2];
position[0] = posn[0];
position[1] = posn[1];
myname = name;
updatePath();
}
public void setPosition(float[] newPosition){
position[0] = newPosition[0];
position[1] = newPosition[1];
updatePath();
}
public void updatePath(){
int startx = myPoints[0][0] + Math.round(position[0]);
int starty = myPoints[0][1] + Math.round(position[1]);
path.moveTo(startx,starty);
for (int i = 1; i < myPoints.length; i++)
{
int newx = myPoints[i][0] + Math.round(position[0]);
int newy = myPoints[i][1] + Math.round(position[1]);
path.lineTo(newx,newy);
}
path.close();
}
public Path getPath() {
return path;
}
}
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
uk.mydomain.animatedtriangle.GameView gameView = new uk.mydomain.animatedtriangle.GameView(this);
RelativeLayout relativeLayout = new RelativeLayout(this);
RelativeLayout.LayoutParams relativeParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
relativeLayout.setLayoutParams(relativeParams);
setContentView(relativeLayout);
relativeLayout.addView(gameView);
}
Sorted! Just needed to add a path.reset() at the end of onDraw.

Best Practice to limit NotesViewEntryCollection from getAllEntries

I want to create better web service that display collection from NotesView with pagination.
And I have found some performance issue of View.getAllEntries from bigger view.
On MongoDB, I can use findAll() with skip() and limit().
How can I do like that on Domino ?
Use the ViewNavigator class. If you are paging through a large view, it is much faster than view.getAllEntries().
You can acquire an instance of ViewNavigator with view.createViewNav() or a similar method. For best performance, call view.setAutoUpdate(false) before you acquire the navigator.
You can find lots more information by searching the web. This article looks like a good place to start.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.ibm.commons.util.io.json.JsonJavaObject;
import lotus.domino.NotesException;
import lotus.domino.View;
import lotus.domino.ViewColumn;
import lotus.domino.ViewEntryCollection;
import lotus.domino.ViewNavigator;
import lotus.domino.ViewEntry;
private String consultView(View view, int counter,int position) throws Exception{
String strValue = "";
ViewNavigator nav;
int count = 0;
view.setAutoUpdate(false);
nav = view.createViewNav();
nav.setEntryOptions(ViewNavigator.VN_ENTRYOPT_NOCOUNTDATA);
nav.setBufferMaxEntries(400);
int limit = counter;
int skippedEntries = nav.skip(position);
String number = "";
if (skippedEntries == position) {
Map<Integer, String> columnNameMap = new HashMap<Integer, String>();
for (ViewColumn col : (List<ViewColumn>) view.getColumns()) {
if (col.getColumnValuesIndex() < 65535) {
columnNameMap.put(col.getColumnValuesIndex(), col.getItemName());
}
}
List nodeData = new ArrayList();
ViewEntry entry = nav.getCurrent();
while (entry != null && count <= (limit - 1)) {
if (!entry.isCategory()) {
try {
HashMap<String, Object> entryMap = new HashMap<String, Object>();
count++;
List<Object> columnValues = entry.getColumnValues();
entryMap.put("unid", entry.getUniversalID());
entryMap.put("position", entry.getPosition('.'));
entryMap.put("pos", entry.getPosition('.'));
entryMap.put("userpos", count);
for (Integer index : columnNameMap.keySet())
entryMap.put(columnNameMap.get(index).toString(),columnValues.get(index));
nodeData.add(entryMap);
} catch (Exception e) {
e.printStackTrace();
}
}
ViewEntry tmpentry = nav.getNext(entry);
entry.recycle();
entry = tmpentry;
}
JsonJavaObject returnJSON = new JsonJavaObject();
returnJSON.put("errorcode", 0);
returnJSON.put("errormessage", "");
returnJSON.put("total",getViewCount(view));
returnJSON.put("data", nodeData);
strValue = returnJSON.toString();
}
nav.recycle();
view.recycle();
return strValue;
}
private int getViewCount(View view) throws NotesException {
int count = 0;
ViewEntryCollection entryCollection = view.getAllEntries();
count = entryCollection.getCount();
entryCollection.recycle();
return count;
}
}
This below function get all AllEntries from view and the outputs result in JSON object. Please try the following and let me know if it works.
private String consultView(View view, int counter,int position) throws Exception{
String strValue = "";
ViewNavigator nav;
int count = 0;
view.setAutoUpdate(false);
nav = view.createViewNav();
nav.setEntryOptions(ViewNavigator.VN_ENTRYOPT_NOCOUNTDATA);
nav.setBufferMaxEntries(400);
int limit = counter;
int skippedEntries = nav.skip(position);
String number = "";
int inde = 111;
if (skippedEntries == position) {
Map<Integer, String> columnNameMap = new HashMap<Integer, String>();
for (ViewColumn col : (List<ViewColumn>) view.getColumns()) {
if (col.getColumnValuesIndex() < 65535 && Utilisties.containsVar(viewObject.getRetCols(), col.getItemName())) {
columnNameMap.put(col.getColumnValuesIndex(), col.getItemName());
}
}
List nodeData = new ArrayList();
ViewEntry entry = nav.getCurrent();
while (entry != null && count <= (limit - 1)) {
if (!entry.isCategory()) {
try {
HashMap<String, Object> entryMap = new HashMap<String, Object>();
count++;
List<Object> columnValues = entry.getColumnValues();
entryMap.put("unid", entry.getUniversalID());
entryMap.put("position", entry.getPosition('.'));
entryMap.put("pos", entry.getPosition('.'));
entryMap.put("userpos", count);
for (Integer index : columnNameMap.keySet())
entryMap.put(columnNameMap.get(index).toString(),columnValues.get(index));
nodeData.add(entryMap);
} catch (Exception e) {
e.printStackTrace();
}
}
ViewEntry tmpentry = nav.getNext(entry);
entry.recycle();
entry = tmpentry;
}
JsonJavaObject returnJSON = new JsonJavaObject();
returnJSON.put("errorcode", 0);
returnJSON.put("errormessage", "");
if(viewObject.getGetCount())
returnJSON.put("total",getViewCount(view));
returnJSON.put("data", nodeData);
strValue = returnJSON.toString();
}
nav.recycle();
view.recycle();
return strValue;

How do you make Music shuffle on Android Studio? Using or without using arrays

I need help making the songs Shuffle (mixed) but I don't know how and also I want it to go to another music each time without repeating.
public class MusicMix {
private Music music1, music2, music3, music4, music5,music6,music7,music8,music9,music10,music11,music12,music13,music14,music15,music16,music17;
music1 = Gdx.audio.newMusic(Gdx.files.internal("musicA.mp3"));
music2 = Gdx.audio.newMusic(Gdx.files.internal("musicB.mp3"));
music3 = Gdx.audio.newMusic(Gdx.files.internal("musicC.mp3"));
music4 = Gdx.audio.newMusic(Gdx.files.internal("musicD.mp3"));
music5 = Gdx.audio.newMusic(Gdx.files.internal("musicE.mp3"));
music6 = Gdx.audio.newMusic(Gdx.files.internal("musicF.mp3"));
music7 = Gdx.audio.newMusic(Gdx.files.internal("musicG.mp3"));
music8 = Gdx.audio.newMusic(Gdx.files.internal("musicH.mp3"));
music9 = Gdx.audio.newMusic(Gdx.files.internal("musicJ.mp3"));
music10 = Gdx.audio.newMusic(Gdx.files.internal("musicK.mp3"));
music11 = Gdx.audio.newMusic(Gdx.files.internal("musicL.mp3"));
music12 = Gdx.audio.newMusic(Gdx.files.internal("musicM.mp3"));
music13 = Gdx.audio.newMusic(Gdx.files.internal("musicN.mp3"));
music14 = Gdx.audio.newMusic(Gdx.files.internal("musicO.mp3"));
music15 = Gdx.audio.newMusic(Gdx.files.internal("musicP.mp3"));
music16 = Gdx.audio.newMusic(Gdx.files.internal("musicQ.mp3"));
music17 = Gdx.audio.newMusic(Gdx.files.internal("musicR.mp3"));
}
First of all create first an array that should make your life easier. Instead of manually doing it one by one.
Array<Music> musics = new Array<Music>();
for (int i = 65; i < 25; i++) {
//The ascii of 65 = A
char ascii = (char) i;
Music music = Gdx.audio.newMusic(Gdx.files.internal("music" + ascii + ".mp3"));
musics.add(music);
}
Then after that just call this method. It's a built-in method in Libgdx. This method should answer your question.
musics.shuffle();
I tried to implement your requirement in this way.
public class TestGame extends Game {
private Array<String> musicName;
private Array<Music> musicList;
private IntArray intArray;
#Override
public void create() {
musicName=new Array<String>(new String[]{"sound/x1.ogg","sound/x2.ogg","sound/x3.ogg","sound/x4.ogg","sound/x5.ogg"});
musicList=new Array<Music>();
intArray=new IntArray();
for (String path:musicName) {
Music music=Gdx.audio.newMusic(Gdx.files.internal(path));
musicList.add(music);
intArray.add(musicName.indexOf(path,true));
music.setOnCompletionListener(new OnComplete(this));
}
int value=MathUtils.random(musicList.size-1);
intArray.removeValue(value);
musicList.get(value).play();
}
public class OnComplete implements Music.OnCompletionListener {
private TestGame testGame;
public OnComplete(TestGame game){
testGame=game;
}
#Override
public void onCompletion(Music music) {
testGame.playUnPlayedMusic();
}
}
public void playUnPlayedMusic(){
int value ;
if(intArray.size>0) {
value = intArray.get(MathUtils.random(intArray.size - 1));
intArray.removeValue(value);
}else {
for (int i=0;i<musicList.size;i++)
intArray.add(i);
value = intArray.get(MathUtils.random(intArray.size - 1));
intArray.removeValue(value);
}
Music music= musicList.get(value);
music.play();
}
#Override
public void render() {
}
}

Undetected Null Pointer Exception

I have an error regarding Null Pointer Exception and I can't find the exact location of the error in my program. I have searched for probable solutions online but I find none of them helpful. I know what Null Pointer Exception is but I can't pinpoint what went wrong in my code. Any help will be appreciated, thanks.
Here's my code:
LevelOneScreen.java
public class LevelOneScreen implements Screen {
private final ThumbChase app;
WalkAnimate walkAnimate;
private Stage stage;
private Image levelOneImage;
private Image holdStartImage;
public Image walkRightImage;
public Image walkLeftImage;
public float deltaTime = Gdx.graphics.getDeltaTime();
public LevelOneScreen(final ThumbChase app){
this.app = app;
this.stage = new Stage(new StretchViewport(app.screenWidth,app.screenHeight , app.camera));
}
#Override
public void show() {
Gdx.input.setInputProcessor(stage);
walkAnimate = new WalkAnimate();
levelOneBackground();
holdStart();
ninjaWalk(); ==>ERROR1:LevelOneScreen.java:54
}
public void holdStart(){
Texture holdStartTexture = new Texture("HoldStart.png");
holdStartImage = new Image(holdStartTexture);
float holdStartImageW = holdStartImage.getWidth();
float holdStartImageH = holdStartImage.getHeight();
float holdStartImgWidth = app.screenWidth*0.8f;
float holdStartImgHeight = holdStartImgWidth *(holdStartImageH/holdStartImageW);
holdStartImage.isTouchable();
holdStartImage.setSize(holdStartImgWidth,holdStartImgHeight);
holdStartImage.setPosition(stage.getWidth()/2-holdStartImgWidth/2,stage.getHeight()/2-holdStartImgHeight/2);
stage.addActor(holdStartImage);
holdStartImage.addListener(new ActorGestureListener(){
public void touchDown (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};
});
}
public void levelOneBackground(){
Texture levelOneTexture = new Texture("BGBlue Resize.png");
levelOneImage = new Image(levelOneTexture);
levelOneImage.setSize(app.screenWidth,app.screenHeight);
levelOneImage.setPosition(0,0);
stage.addActor(levelOneImage);
levelOneImage.addListener(new ActorGestureListener(){
public void touchDown (InputEvent event, float x, float y, int pointer, int button){
holdStartImage.setVisible(false);
};
});
}
public void ninjaWalk(){
ERROR2==> TextureRegion ninjaWalkRight = new TextureRegion(walkAnimate.getCurrentFrameRight());
TextureRegion ninjaWalkLeft = new TextureRegion(walkAnimate.getCurrentFrameLeft());
walkRightImage = new Image(ninjaWalkRight);
walkLeftImage = new Image(ninjaWalkLeft);
float walkImageW = walkRightImage.getWidth();
float walkImageH = walkRightImage.getHeight();
float walkImageWidth = app.screenWidth*0.15f;
float walkImageHeight = walkImageWidth*(walkImageH/walkImageW);
walkLeftImage.isTouchable();
walkRightImage.isTouchable();
walkRightImage.setSize(walkImageWidth,walkImageHeight);
walkLeftImage.setSize(walkImageWidth,walkImageHeight);
walkRightImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
walkLeftImage.setPosition(stage.getWidth()/2-walkImageWidth/2,0);
walkLeftImage.addAction(moveBy(3f,3f,3f));
stage.addActor(walkLeftImage);
}
#Override
public void render(float delta) {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
walkAnimate.update(deltaTime);
update(delta);
}
public void update(float delta){
stage.act(delta);
stage.draw();
app.batch.begin();
app.batch.end();
}
#Override
public void resize(int width, int height) {
}
#Override
public void pause() {
}
#Override
public void resume() {
}
#Override
public void hide() {
}
#Override
public void dispose() {
stage.dispose();
}
}
WalkAnimate.java
public class WalkAnimate {
public ThumbChase app;
public Stage stage;
private Animation walkAnimationRight;
private Animation walkAnimationLeft;
private Texture walkSheetRight;
private Texture walkSheetLeft;
private TextureRegion[] walkFramesRight;
private TextureRegion[] walkFramesLeft;
private TextureRegion currentFrameRight;
private TextureRegion currentFrameLeft;
private float stateTime;
private Rectangle bound; //used for positioning and collision detection
private static final int FRAME_COLS_WALK = 3;
private static final int FRAME_ROWS_WALK= 2;
private float screenWidth = Gdx.graphics.getWidth();
private float screenHeight = Gdx.graphics.getHeight();
public float currentFrameWidth = (float)(screenHeight*0.15);
public float currentFrameHeight = (float)(screenHeight*0.15);
public float walkSheetWidth;
public float walkSheetHeight;
public WalkAnimate () {
walkSheetRight = new Texture("ninjaWalkRight.png");
walkSheetWidth = walkSheetRight.getWidth();
walkSheetHeight = walkSheetRight.getWidth();
TextureRegion[][] tmp = TextureRegion.split(walkSheetRight, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int) walkSheetRight.getHeight() / FRAME_ROWS_WALK);
walkFramesRight = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
int index = 0 ;
for (int i = 0; i < FRAME_ROWS_WALK; i++) {
for (int j = 0; j < FRAME_COLS_WALK; j++) {
walkFramesRight[index++] = tmp[i][j];
}
}
walkAnimationRight = new Animation(0.044f, walkFramesRight);
stateTime = 0f;
walkSheetLeft = new Texture("ninjaWalkLeft.png");
walkSheetWidth = walkSheetLeft.getWidth();
walkSheetHeight = walkSheetLeft.getWidth();
TextureRegion[][] tmp1 = TextureRegion.split(walkSheetLeft, (int) walkSheetRight.getWidth() / FRAME_COLS_WALK, (int)walkSheetLeft.getHeight() / FRAME_ROWS_WALK);
walkFramesLeft = new TextureRegion[FRAME_COLS_WALK * FRAME_ROWS_WALK];
int index1 = 0;
for (int i = 0; i < FRAME_ROWS_WALK; i++) {
for (int j = 0; j < FRAME_COLS_WALK; j++) {
walkFramesLeft[index1++] = tmp1 [i][j];
}
}
walkAnimationLeft = new Animation(0.044f, walkFramesLeft);
stateTime = 0f;
}
public Rectangle getBound(){
return bound;
}
public void update(float delta){
stateTime += delta;
currentFrameRight = walkAnimationRight.getKeyFrame(stateTime, true);
currentFrameLeft = walkAnimationLeft.getKeyFrame(stateTime, true);
}
public TextureRegion getCurrentFrameRight(){
return currentFrameRight;
}
public TextureRegion getCurrentFrameLeft(){
return currentFrameLeft;
}
}
And here's the error:
> java.lang.NullPointerException
> at
> com.badlogic.gdx.graphics.g2d.TextureRegion.setRegion(TextureRegion.java:112)
> at
> com.badlogic.gdx.graphics.g2d.TextureRegion.<init>(TextureRegion.java:63)
> at
> com.jpfalmazan.thumbchaseninja.GameScreens.LevelOneScreen.show(LevelOneScreen.java:54)
> at com.badlogic.gdx.Game.setScreen(Game.java:61)
> at
> com.jpfalmazan.thumbchaseninja.GameScreens.MenuScreen$1.clicked(MenuScreen.java:82)
> at
> com.badlogic.gdx.scenes.scene2d.utils.ClickListener.touchUp(ClickListener.java:89)
> at
> com.badlogic.gdx.scenes.scene2d.InputListener.handle(InputListener.java:58)
> at com.badlogic.gdx.scenes.scene2d.Stage.touchUp(Stage.java:353)
> at
> com.badlogic.gdx.backends.android.AndroidInput.processEvents(AndroidInput.java:379)
> at
> com.badlogic.gdx.backends.android.AndroidGraphics.onDrawFrame(AndroidGraphics.java:457)
> at
> android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1516)
> at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1240)
you can find the exact line in logcat logs, you can see the activity name as well as the line of code and by clicking on it you will be redirected to the individual Activity on same line..
Hope this will help you.
One of your textures is either named wrong, or you are attempting to access it before it has been loaded.
You can tell by this exception;
com.badlogic.gdx.graphics.g2d.TextureRegion.setRegion(TextureRegion.java:112)
This mean that the texture region cannot map the texture identifier to a valid texture in your program, so either ninjaWalkRight or ninjaWalkLeft does not exist or is not loaded.
If you are using texture packer then ensure your files are called ninjaWalkRight and ninjaWalkLeft.
Also use the AssetManager to ensure these files are loaded before trying to access them as that may be an issue also.
Looks like you don't call walkAnimate.update(dt) before calling walkAnimate.getCurrentFrameRight() the first time, so walkAnimate.getCurrentFrameRight() returns null.
Moreover, in ninjaWalk() you create two actors (walkRightImage and walkLeftImage), only add one to the stage and never update the texture of it. You should rework your concept: Create one actor at startup, store it in a field and change the texture of it in your render/update method.

Resources