I want to change from an xml layout to surfaceview using java - android

OK so I'm using xml to set this menu which is supported by the following java code
package starting.rt;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Menu extends Activity implements OnClickListener{
View.OnTouchListener gestureListener;
TextView display;
Button begin;
Button random;
Button game;
TextView counter;
Button next;
Button previous;
Button moreapps;
Button rate;
Random myRandom;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(starting.rt.R.layout.menu);
begin = (Button) findViewById(starting.rt.R.id.Begin);
random = (Button) findViewById(starting.rt.R.id.Random);
display = (TextView) findViewById(starting.rt.R.id.tvResults);
counter = (TextView) findViewById(starting.rt.R.id.tvCounter);
next = (Button) findViewById(starting.rt.R.id.Next);
previous = (Button) findViewById(starting.rt.R.id.Previous);
moreapps = (Button)findViewById(R.id.More);
rate = (Button) findViewById(R.id.rate);
game = (Button) findViewById(R.id.game);
// display.setOnTouchListener(this.gestureListener);
begin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.RelationshipTipsActivity");
startActivity(openStartingPoint);
}});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}});
game.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.GameView");
startActivity(openStartingPoint);
}});
rate.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=" + getPackageName()));
startActivity(i);
}});}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Now what's supposed to be happening is when they click on the game which starts a new java class called GameView it crashes on clicked. Every other button works.
This is the code from GameView
package starting.rt;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread gameLoopThread;
private List<Sprite> sprites = new ArrayList<Sprite>();
private List<TempSprite> temps = new ArrayList<TempSprite>();
private long lastClick;
private Bitmap bmpBlood;
public GameView(Context context) {
super(context);
gameLoopThread = new GameLoopThread(this);
getHolder().addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
gameLoopThread.setRunning(false);
while (retry) {
try {
gameLoopThread.join();
retry = false;
} catch (InterruptedException e) {}
}
}
public void surfaceCreated(SurfaceHolder holder) {
createSprites();
gameLoopThread.setRunning(true);
gameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
}
});
bmpBlood = BitmapFactory.decodeResource(getResources(), R.drawable.blood1);
}
private void createSprites() {
sprites.add(createSprite(R.drawable.bad1));
// sprites.add(createSprite(R.drawable.bad2));
// sprites.add(createSprite(R.drawable.bad3));
// sprites.add(createSprite(R.drawable.bad4));
// sprites.add(createSprite(R.drawable.bad5));
// sprites.add(createSprite(R.drawable.bad6));
// sprites.add(createSprite(R.drawable.good1));
// sprites.add(createSprite(R.drawable.good2));
// sprites.add(createSprite(R.drawable.good3));
// sprites.add(createSprite(R.drawable.good4));
// sprites.add(createSprite(R.drawable.good5));
// sprites.add(createSprite(R.drawable.good6));
}
private Sprite createSprite(int resouce) {
Bitmap bmp = BitmapFactory.decodeResource(getResources(), resouce);
return new Sprite(this, bmp);
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
for (int i = temps.size() - 1; i >= 0; i--) {
temps.get(i).onDraw(canvas);
}
for (Sprite sprite : sprites) {
sprite.onDraw(canvas);
}
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (System.currentTimeMillis() - lastClick > 300) {
lastClick = System.currentTimeMillis();
float x = event.getX();
float y = event.getY();
synchronized (getHolder()) {
for (int i = sprites.size() - 1; i >= 0; i--) {
Sprite sprite = sprites.get(i);
if (sprite.isCollition(x, y)) {
sprites.remove(sprite);
temps.add(new TempSprite(temps, this, x, y, bmpBlood));
break;
}
}
}
}
return true;
}
}
The GameView calls a few other classes for things part of the game but it crashes before it can start. I think it's crashing because it's switching from xml layout to the java surfaceview. Help would be appreciated :) Thanks!

First of all, you should always post in your questions the stacktrace with the exception from the Logcat if your app crashes.
You can't start a SurfaceView directly, instead your custom SurfaceView must be embedded in an Activity like any other view in android. For example:
public class GameViewActivity extends Activity {
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(new GameView(this));
}
}

Related

How to use cameraview in android

I'm facing an issue regarding cameraview. Do I have to import something since the error goes "cannot resolve flurgle" for import com.flurgle.camerakit.CameraView;
My permissions in manifest file are already set.
Heres the code using cameraview(taken from "https://blog.mindorks.com/android-tensorflow-machine-learning-example-ff0e9b2654cc.html" )
package com.example.mujtaba.basicai.Machine_Learning;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.mujtaba.basicai.R;
import com.flurgle.camerakit.CameraListener;
import com.flurgle.camerakit.CameraView;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ImageRecognition extends AppCompatActivity {
private static final int INPUT_SIZE = 224;
private static final int IMAGE_MEAN = 117;
private static final float IMAGE_STD = 1;
private static final String INPUT_NAME = "input";
private static final String OUTPUT_NAME = "output";
private static final String MODEL_FILE = "file:///android_asset/tensorflow_inception_graph.pb";
private static final String LABEL_FILE =
"file:///android_asset/imagenet_comp_graph_label_strings.txt";
private Classifier classifier;
private Executor executor = Executors.newSingleThreadExecutor();
private TextView textViewResult;
private Button btnDetectObject, btnToggleCamera;
private ImageView imageViewResult;
private cameraView cameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_recognition);
cameraView = (CameraView) findViewById(R.id.cameraView);
imageViewResult = (ImageView) findViewById(R.id.imageViewResult);
textViewResult = (TextView) findViewById(R.id.textViewResult);
textViewResult.setMovementMethod(new ScrollingMovementMethod());
btnToggleCamera = (Button) findViewById(R.id.btnToggleCamera);
btnDetectObject = (Button) findViewById(R.id.btnDetectObject);
cameraView.setCameraListener(new CameraListener() {
#Override
public void onPictureTaken(byte[] picture) {
super.onPictureTaken(picture);
Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);
bitmap = Bitmap.createScaledBitmap(bitmap, INPUT_SIZE, INPUT_SIZE, false);
imageViewResult.setImageBitmap(bitmap);
final List<Classifier.Recognition> results = classifier.recognizeImage(bitmap);
textViewResult.setText(results.toString());
}
});
btnToggleCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.toggleFacing();
}
});
btnDetectObject.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cameraView.captureImage();
}
});
initTensorFlowAndLoadModel();
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
#Override
protected void onPause() {
cameraView.stop();
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
executor.execute(new Runnable() {
#Override
public void run() {
classifier.close();
}
});
}
private void initTensorFlowAndLoadModel() {
executor.execute(new Runnable() {
#Override
public void run() {
try {
classifier = TensorFlowImageClassifier.create(
getAssets(),
MODEL_FILE,
LABEL_FILE,
INPUT_SIZE,
IMAGE_MEAN,
IMAGE_STD,
INPUT_NAME,
OUTPUT_NAME);
makeButtonVisible();
} catch (final Exception e) {
throw new RuntimeException("Error initializing TensorFlow!", e);
}
}
});
}
private void makeButtonVisible() {
runOnUiThread(new Runnable() {
#Override
public void run() {
btnDetectObject.setVisibility(View.VISIBLE);
}
});
}
}

check what image is set to image view each 500 ms

I am working on this small game where each 500 ms an image is set to the image view
so what i want to check is when i click one of the arrow images(left,right,up,down) to check if it is equal to the random image ...if so then the score increases by 1.
here is my layout
https://i.stack.imgur.com/wPxZB.png
and here is my code
package com.andreh.catchthatarrow;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Timer;
import java.util.TimerTask;
public class GameActivity extends AppCompatActivity {
ImageView img_up;
ImageView img_down;
ImageView img_left;
ImageView img_right,imgRand;
private int time = 600;
private static int SCORE = 0;
private TextView score;
int pos = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
score = (TextView)findViewById(R.id.textView3);
img_up = (ImageView)findViewById(R.id.imgUp);
img_down = (ImageView)findViewById(R.id.imgDown);
img_left = (ImageView)findViewById(R.id.imgLeft);
img_right = (ImageView)findViewById(R.id.imgRight);
imgRand = (ImageView)findViewById(R.id.changeable);
final int [] arrBuckets = {R.drawable.arrow_left,R.drawable.arrow_right,R.drawable.up,R.drawable.down};
Timer mTimer = new Timer();
mTimer.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
#Override
public void run() {
pos = arrBuckets[(int) (Math.random() * arrBuckets.length)];
imgRand.setImageResource(pos);
if(time>10 || time<20) time=100;
}
});
}
},0,time);
img_up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==2){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==3){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_left.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==0){
SCORE++;
score.setText(SCORE+"");
}
}
});
img_right.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(pos==1){
SCORE++;
score.setText(SCORE+"");
}
}
});
}
}
You are checking the data in the index and you need the position so use this instead:
pos = Array.asList(arrayBuckets).indexOf((int) (Math.random() * arrBuckets.length));
img_up.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) {
if(pos==2)
{
SCORE++;
score.setText(SCORE+"");
}
});

when i changed orientation portrait to landscape i want layout should change for landscape and video is start from same position in android?

This is my whole code for media player only the problem is when i changed the orientation video is playing from beginning what should i do.I also add the "android:configChanges="orientation|screenSize|keyboardHidden" in menifest. please help
//MediaPlayerActivity.java
package com.focusmedica.ud_en_acne;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.VideoView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
public class MediaPlayerActivity extends Activity implements SeekBar.OnSeekBarChangeListener {
ImageView pauseAndResume,refresh,next,prev,screenshot,pencil;
SeekBar videoProgress;
private Handler mHandler = new Handler();;
private Utilities util;
TextView current;
boolean playFlag,isTrue=false;
VideoView videoView;
int vDuration;
LinearLayout linear;
RelativeLayout relate;
View mView;
private Paint mPaint;
private Canvas mCanvas;
/*static int[] video_url=new int[]{
R.raw.introduction,R.raw.causes,R.raw.risk_factors,R.raw.types_of_acne,
R.raw.signs_and_symptoms,R.raw.treatment,R.raw.prevention_and_self_care,
};*/
int video_url=R.raw.introduction;
String path = Environment.getExternalStorageDirectory()
+ File.separator + "Pictures/screenshot.png";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play);
//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
videoView=(VideoView)findViewById(R.id.videoView);
videoProgress=(SeekBar)findViewById(R.id.seekbar);
videoProgress.setOnSeekBarChangeListener(this);
pauseAndResume=(ImageView) findViewById(R.id.btnPauseResume);
relate=(RelativeLayout) findViewById(R.id.relate);
linear=(LinearLayout)findViewById(R.id.linear);
screenshot=(ImageView)findViewById(R.id.btnScreenshot);
refresh=(ImageView)findViewById(R.id.btnRefresh);
pencil=(ImageView)findViewById(R.id.btnPencil);
current=(TextView)findViewById(R.id.current);
linear.setVisibility(View.INVISIBLE);
util = new Utilities();
Bundle extras = getIntent().getExtras();
final int position = extras.getInt("position");
final Uri uri=Uri.parse("android.resource://" + getPackageName() + "/"+ video_url);
MediaMetadataRetriever retriever = new MediaMetadataRetriever();
retriever.setDataSource(this, Uri.parse("android.resource://" + getPackageName() + "/"+ video_url));
String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
vDuration = Integer.parseInt(time );
relate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (linear.getVisibility() == View.INVISIBLE) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
linear.setVisibility(View.VISIBLE);
}
}, 100);
}else{
linear.setVisibility(View.INVISIBLE);
}
}
});
refresh.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (isTrue == true) {
relate.removeView(mView);
mView = new DrawingView(MediaPlayerActivity.this);
relate.addView(mView);
}
}
});
pencil.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(isTrue==false) {
mView = new DrawingView(MediaPlayerActivity.this);
relate.addView(mView, new ViewGroup.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT));
init();
isTrue=true;
}else if(isTrue==true){
relate.removeView(mView);
isTrue=false;
}
}
});
pauseAndResume.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (pauseAndResume.getDrawable().getConstantState()== getResources().getDrawable(R.drawable.pause).getConstantState())
{
videoView.pause();
pauseAndResume.setImageResource(R.drawable.play1);
}
else
{
videoView.start();
pauseAndResume.setImageResource(R.drawable.pause);
}
}
});
screenshot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Bitmap bitmap = takeScreenshot(MediaPlayerActivity.this,uri);
saveBitmap(bitmap);
}
});
playVideo(uri);
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//Toast.makeText(getApplicationContext(),"seekbar progress: "+progress, Toast.LENGTH_SHORT).show();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration =vDuration;
int currentPosition = util.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
videoView.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
//canvas
private void init() {
mPaint = new Paint();
mPaint.setDither(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
}
private Bitmap takeScreenshot(Context context, Uri uri) {
MediaMetadataRetriever mediametadataretriever = new MediaMetadataRetriever();
try {
mediametadataretriever.setDataSource(context, uri);
Bitmap bitmap = mediametadataretriever.getFrameAtTime(videoView.getCurrentPosition()*1000);
Bitmap mainBitmap= ThumbnailUtils.extractThumbnail(bitmap, videoView.getWidth(), videoView.getHeight(), 2);
Bitmap bmOverlay = Bitmap.createBitmap(videoView.getWidth(), videoView.getHeight(), bitmap.getConfig());
relate.setDrawingCacheEnabled(true);
Bitmap bitmap1=relate.getDrawingCache();
mCanvas=new Canvas(bmOverlay);
mCanvas.drawBitmap(mainBitmap,new Matrix(), null);
mCanvas.drawBitmap(bitmap1, 0,0, null);
if(null != mainBitmap)
{
return bmOverlay;
}
return bmOverlay;
} catch (Throwable t) {
return null;
} finally {
try
{
mediametadataretriever.release();
}
catch(RuntimeException e) { }
}
}
private void saveBitmap(Bitmap bitmap) {
FileOutputStream fos;
try {
fos =new FileOutputStream(path);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
sentmail(path);
} catch (FileNotFoundException e) {
Log.e("GREC", e.getMessage(), e);
} catch (IOException e) {
Log.e("GREC", e.getMessage(), e);
}
}
private void sentmail(String path) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
new String[]{"p.ashish029#gmail.com"});
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"Acne");
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT,
"Screenshot of image");
emailIntent.setType("image/jpg");
Uri myUri = Uri.parse("file://" + path);
emailIntent.putExtra(Intent.EXTRA_STREAM, myUri);
startActivity(Intent.createChooser(emailIntent, "Send mail..."));
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = vDuration;
long currentDuration = videoView.getCurrentPosition();
// Displaying Total Duration time
//total.setText(""+util.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
current.setText(""+util.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int)(util.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", ""+progress);
videoProgress.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
private void playVideo(Uri uri) {
if (videoView.isPlaying() )
{
videoView.stopPlayback();
}
videoView.setVideoURI(uri);
videoView.start();
updateProgressBar();
videoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
playFlag=false;
finish();
}
});
}
//Canvas
private class DrawingView extends View {
private Path path;
private Bitmap mBitmap;
public DrawingView(Context context) {
super(context);
path = new Path();
mBitmap = Bitmap.createBitmap(relate.getWidth(), relate.getHeight(), Bitmap.Config.ARGB_8888);
Canvas mCanvas = new Canvas(mBitmap);
}
private ArrayList<PathWithPaint> _graphics1 = new ArrayList<PathWithPaint>();
#Override
public boolean onTouchEvent(MotionEvent event) {
PathWithPaint pp = new PathWithPaint();
if (event.getAction() == MotionEvent.ACTION_DOWN) {
path.moveTo(event.getX(), event.getY());
path.lineTo(event.getX(), event.getY());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
path.lineTo(event.getX(), event.getY());
pp.setPath(path);
pp.setmPaint(mPaint);
_graphics1.add(pp);
}
invalidate();
return true;
}
#Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (_graphics1.size() > 0) {
canvas.drawPath(
_graphics1.get(_graphics1.size() - 1).getPath(),
_graphics1.get(_graphics1.size() - 1).getmPaint());
}
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_play);
onCreate(new Bundle());
}
}
Android provides a way to store current states and retrieve them when orientation changes.
Override onSaveInstanceState(Bundle savedInstanceState) method in your activity and save the state of the video you are playing,
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save current video progress
savedInstanceState.putLong("videoProgress", videoView.getProgress());
super.onSaveInstanceState(savedInstanceState);
}
and in your onCreate() method you can retrieve video progress as,
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);first
if (savedInstanceState != null) {
currentProgress = savedInstanceState.getLong("videoProgress");
videoView.setProgress(currentProgress);
}
...
}

Unable to access views in android

I am using metaio sdk. I am trying to simply toggle the visibility of two imageviews when pressing a button but it is not working.
My layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/ma_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#00000000" >
-----
<ImageView
android:id="#+id/zoomIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_marginTop="4dp"
android:layout_marginRight="4dp"
android:background="#drawable/zooming"
android:onClick="seeZoom" />
<ImageView
android:id="#+id/scrollerBg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#drawable/scrollerbg"
android:visibility="invisible"/>
<ImageView
android:id="#+id/scroller"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#drawable/scroller"
android:visibility="invisible"/>
---
</RelativeLayout>
My code:
import android.view.MotionEvent;
import java.util.List;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.MeasureSpec;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import com.metaio.sdk.jni.IGeometry;
import com.metaio.sdk.jni.IMetaioSDKAndroid;
import com.metaio.sdk.jni.Vector3d;
import android.os.Environment;
import com.metaio.sdk.ARViewActivity;
import com.metaio.sdk.jni.EPLAYBACK_STATUS;
import com.metaio.sdk.jni.IMetaioSDKCallback;
import com.metaio.sdk.jni.MovieTextureStatus;
import com.metaio.sdk.jni.Rotation;
import com.metaio.sdk.MetaioDebug;
import com.company.abc.R;
public class MainActivity extends ARViewActivity
{
public RelativeLayout mGUIView;
//public ImageView imgView1;
//public ImageView imgView2;
Camera camera;
private IGeometry tdp1, tdp2, tdp3, tdp4, tdp5, tdp6, tdp7, sal1, sal2;
boolean isTorchOn=false;
Parameters camParams;
public ImageView basePng;
public ImageView zoomIcon;
ImageView scroller;
public LayoutParams scrollerParams;
ImageView scrollerBg;
public LayoutParams scrollerBgParams;
boolean afc;
int counter;
int displayWidthbyTwo;
int displayHeightbyTwo;
int scrollerW;
int scrollerH;
int scrollerBgW;
int scrollerBgH;
int ZoomValue=0;
int maxZoomLevel;
int maxZoombyfour;
boolean zoomSupported;
boolean isZoomBarVisible=false;
private MetaioSDKCallbackHandler mCallbackHandler;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
MetaioDebug.enableLogging(true);
mCallbackHandler = new MetaioSDKCallbackHandler();
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
displayWidthbyTwo=metrics.widthPixels/2;
displayHeightbyTwo=metrics.heightPixels/2;
PackageManager PM= this.getPackageManager();
afc = PM.hasSystemFeature(PackageManager.FEATURE_CAMERA_AUTOFOCUS);
setContentView(R.layout.mainactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mGUIView = (RelativeLayout) getLayoutInflater().inflate(R.layout.mainactivity, null);
zoomIcon = (ImageView) mGUIView.findViewById(R.id.zoomIcon);
scroller = (ImageView) mGUIView.findViewById(R.id.scroller);
scrollerBg = (ImageView) mGUIView.findViewById(R.id.scrollerBg);
scroller.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollerW = scroller.getMeasuredWidth()/2;
scrollerH = scroller.getMeasuredHeight()/2;
scrollerParams = (LayoutParams) scroller.getLayoutParams();
scrollerParams.topMargin = displayHeightbyTwo-150-scrollerH;
scroller.setLayoutParams(scrollerParams);
scrollerBg.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
scrollerBgW = scrollerBg.getMeasuredWidth()/2;
scrollerBgH = scrollerBg.getMeasuredHeight()/2;
scrollerBgParams = (LayoutParams) scrollerBg.getLayoutParams();
scrollerBgParams.topMargin = displayHeightbyTwo-scrollerBgH;
scrollerBg.setLayoutParams(scrollerBgParams);
scroller.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
LayoutParams layoutParams = (LayoutParams) scroller.getLayoutParams();
switch(event.getAction())
{
case MotionEvent.ACTION_MOVE:
//Get y coord of the touch point relative to screen
int y_cord = (int) event.getRawY();
//Restrict scroller bewtween center of screen +- 150
if(y_cord>(displayHeightbyTwo+150))
y_cord = displayHeightbyTwo+150;
if(y_cord<(displayHeightbyTwo-150))
y_cord = displayHeightbyTwo-150;
//Set zoom levels at various steps
if(y_cord<=displayHeightbyTwo-90){
camParams.setZoom(0);
Log.i("Zooming:","0");
ZoomValue=0;}
if(y_cord<=displayHeightbyTwo-30 && y_cord>displayHeightbyTwo-90){
camParams.setZoom(maxZoombyfour);
Log.i("Zooming:","1");
ZoomValue=1;}
if(y_cord<=displayHeightbyTwo+30 && y_cord>displayHeightbyTwo-30){
camParams.setZoom(maxZoombyfour*2);
Log.i("Zooming:","2");
ZoomValue=2;}
if(y_cord<=displayHeightbyTwo+90 && y_cord>displayHeightbyTwo+30){
camParams.setZoom(maxZoombyfour*3);
Log.i("Zooming:","3");
ZoomValue=3;}
if(y_cord>displayHeightbyTwo+90){
camParams.setZoom(maxZoomLevel);
Log.i("Zooming:","4");
ZoomValue=4;}
camera.setParameters(camParams);
scrollerParams.topMargin = y_cord-scrollerH;
scroller.setLayoutParams(scrollerParams);
break;
default:
break;
}
return true;
}
});
}
#Override
protected int getGUILayout()
{
// TODO: return 0 in case of no GUI overlay
return R.layout.mainactivity;
}
#Override
protected void onStart()
{
super.onStart();
// hide GUI until SDK is ready
//if (!mRendererInitialized)
//mGUIView.setVisibility(View.GONE);
// add GUI layout
addContentView(mGUIView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
}
#Override
protected void loadContents()
{
// Load desired tracking data for planar marker tracking
String Path = "storage/sdcard1/AS/tdp/";
//final String trackingConfigFile = AssetsManager.getAssetPath("Tracking.xml");
boolean result = metaioSDK.setTrackingConfiguration(Path+"Tracking.xml");
String movie1Path = Path + "movie1.3gp";
tdp1 = metaioSDK.createGeometryFromMovie(movie1Path, false) ;
tdp1.setCoordinateSystemID(1);
tdp1.setScale(new Vector3d(4.0f,4.0f,4.0f));
tdp1.startMovieTexture(true); // loop = true;
}
#Override
protected void onGeometryTouched(IGeometry geometry) {
// TODO Auto-generated method stub
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
#Override
public void onSurfaceChanged(int width, int height) {
//always call the super implementation first
super.onSurfaceChanged(width, height);
camera=IMetaioSDKAndroid.getCamera(this);
camParams = camera.getParameters();
if(afc){
List<String> focusModes = camParams.getSupportedFocusModes();
if(focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE))
camParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
else if (focusModes.contains(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO))
camParams.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
camera.setParameters(camParams);
}
if(camParams.isZoomSupported()){
this.runOnUiThread(new Runnable(){
public void run(){
zoomIcon.setVisibility(View.VISIBLE);
}
});
maxZoomLevel = camParams.getMaxZoom();
maxZoombyfour = Math.round(maxZoomLevel/4);
zoomSupported=true;
}
}
#Override
protected IMetaioSDKCallback getMetaioSDKCallbackHandler()
{
return mCallbackHandler;
}
final class MetaioSDKCallbackHandler extends IMetaioSDKCallback
{
}
public void showTorch(View v) {
if(isTorchOn){
IMetaioSDKAndroid.stopTorch(this);
isTorchOn=false;
}
else{
IMetaioSDKAndroid.startTorch(this);
isTorchOn=true;
}
}
public void seeZoom(View v) {
if(isZoomBarVisible){
scroller.setVisibility(0);
//scrollerBg.setVisibility(View.INVISIBLE);
isZoomBarVisible=false;
Log.i("ss","ss");
}
else{
scroller.setVisibility(1);
isZoomBarVisible=true;
Log.i("ss","ss");
}
}
public void seeSettings(View v) {
Intent intent = new Intent(this, Settings.class);
startActivity(intent);
//finish();
}
public void seeCatalog(View v) {
Intent intent = new Intent(this, CatalogueActivity.class);
startActivity(intent);
//finish();
}
}
I am trying in multiple ways since hours but none of them work . plesae tell me how to access the views from xml. This code used to work previously but it is not working now. Android programming really seems frustrating.
Thanks in advance
You must use setContent(R.layout.your_layout); inside onCreate
Like this
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//mGUIView = (RelativeLayout) getLayoutInflater().inflate(R.layout.scan, null);
setContent(R.layout.your_layout);
scroller = (ImageView) mGUIView.findViewById(R.id.scroller);
scrollerBg = (ImageView) mGUIView.findViewById(R.id.scrollerBg);
}
I guess the error is at 'R',
All you need to do is import your package.R
Example
...
import com.yourpackage.yourappname.R; //Import this
#Override
public void onCreate(Bundle savedInstanceState) {
MetaioCloudPlugin.startJunaio(null, getApplicationContext());
super.onCreate(savedInstanceState);
setContentView(R.layout.mainactivity);
...
Then it should work fine :D
I encountered the same issue before. I managed to solve it by clearing the cache, data and uninstall the app from the device. It is working after I re-publish the app to the testing device. Maybe you could try it.

Starting new activity triggered by boolean in GameThread (android)

I am making a "Defend the castle" style android application. The game is complete, however I just need help closing my surfaceview and starting a new activity for when the the player has lost the game.
The condition for losing the game is just a boolean variable in my GameThread class. The variable is called "lost" and is by default set to false. When the life of the castle drops below 1, lost is set to true and a sound effect plays.
Ideally, I would like to stop the currently looping sound effects and open a new activity (which is already made and working) upon lost=true.
The main activity is as follows:
import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
try {
mGameView.mThread.onTouch(event);
} catch(Exception e) {}
return true;
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// ignore orientation/keyboard change
super.onConfigurationChanged(newConfig);
}
}
The surfaceview is created in this class called GameView:
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
public class GameView extends SurfaceView implements Callback {
Context mContext;
GameThread mThread;
public GameView(Context context) {
super(context);
this.mContext = context;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
Log.d(this.getClass().toString(), "in SurfaceChanged()");
}
//#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceCreated()");
mThread.running = true;
mThread.start();
}
//#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.d(this.getClass().toString(), "in SurfaceDestroyed()");
boolean retry = true;
mThread.running = false;
while (retry) {
try {
mThread.join();
retry = false;
} catch (InterruptedException e) {
}
GameThread.music.stop();
GameThread.groan1.stop();
GameThread.groan2.stop();
GameThread.walk.stop();
GameThread.music.release();
GameThread.groan1.release();
GameThread.groan2.release();
GameThread.walk.release();
GameThread.shoot.release();
}
}
}
The GameThread class contains all of the drawing, the logic and all a run method (below).
#Override
public void run() {
// check if condition here
if(lost){
mContext.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(mContext, LoseActivity.class);
mContext.startActivity(intent);
}
});
}
else{
if (running == true) {
while (running) {
Canvas c = null;
try {
c = mHolder.lockCanvas();
if (width == 0) {
width = c.getWidth();
height = c.getHeight();
player.x = 50;
player.y = 45;
}
synchronized (mHolder) {
long now = System.currentTimeMillis();
update();
draw(c);
ifps++;
if (now > (mLastTime + 1000)) {
mLastTime = now;
fps = ifps;
ifps = 0;
}
}
} finally {
if (c != null) {
mHolder.unlockCanvasAndPost(c);
}
}
}
}
}
The activity that I want to start is called LoseActivity.class. Thank you in advance for any and all help. If anybody needs any further code/explanations, I will be more than happy to post it.
Use runOnUiThread for starting Activity from Thread as:
Change your main Activity as:
public class MainActivity extends Activity {
Button btn_startGame;
Activity activity;
GameView mGameView;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
activity = this;
setContentView(R.layout.main);
btn_startGame = (Button) findViewById(R.id.btnStartGame);
btn_startGame.setOnClickListener(new OnClickListener() {
//#Override
public void onClick(View v) {
mGameView = new GameView(activity,MainActivity.this);
setContentView(mGameView);
mGameView.mThread.doStart();
}
});
}
///your code.....
Change your GameView class as:
public class GameView extends SurfaceView implements Callback {
Context mContext;
Activity contextx;
GameThread mThread;
public GameView(Context context,Activity contextx) {
super(context);
this.mContext = context;
this.contextx=contextx;
getHolder().addCallback(this);
mThread = new GameThread(getHolder(), mContext, new Handler() {
#Override
public void handleMessage(Message m) {
// Use for pushing back messages.
}
});
setFocusable(true);
}
//your code here..........
#Override
public void run() {
// check if condition here
if(lost){
contextx.runOnUiThread(new Runnable() {
#Override
public void run() {
//start Activity here
Intent intent = new Intent(contextx, LoseActivity.class);
contextx.startActivity(intent);
}
});
}
else{
//your code here.........

Categories

Resources