Android game loop thread crash - java

I am very new to programming and I have a problem with a game which I am trying to make.
Almost every time when I exit the game it was crashing.
After adding: if (canvas != null) beforew canvas.drawColor(Color.CYAN); it does not crash on exit anymore but when I return to the game.
Here is the code: (its not my actual game... there is nothing in OnDraw exept canvas.drawColor(Color.CYAN); that keeps it simple)
GameView.java:
package com.example.test.threadtest;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class GameView extends SurfaceView {
private GameLoopThread theGameLoopThread;
private SurfaceHolder surfaceHolder;
public GameView(Context context) {
super(context);
theGameLoopThread = new GameLoopThread(this);
surfaceHolder = getHolder();
surfaceHolder.addCallback(new SurfaceHolder.Callback() {
public void surfaceDestroyed(SurfaceHolder holder) {
boolean retry = true;
theGameLoopThread.setRunning(false);
while (retry) {
try {
theGameLoopThread.join();
retry = false;
} catch (InterruptedException e) {
}
}
}
public void surfaceCreated(SurfaceHolder holder) {
theGameLoopThread.setRunning(true);
theGameLoopThread.start();
}
public void surfaceChanged(SurfaceHolder holder, int format,
int width, int height) {
// TODO Auto-generated method stub
}
});
}
#Override
protected void onDraw(Canvas canvas) {
if (canvas != null)
canvas.drawColor(Color.CYAN);
}
}
GameLoopThread.java:
package com.example.test.threadtest;
import android.annotation.SuppressLint;
import android.graphics.Canvas;
public class GameLoopThread extends Thread {
static final long FPS = 20;
private GameView theView;
private boolean isRunning = false;
public GameLoopThread(GameView theView) {
this.theView = theView;
}
public void setRunning(boolean run) {
isRunning = run;
}
#SuppressLint("WrongCall") #Override
public void run() {
long TPS = 1000 / FPS;
long startTime, sleepTime;
while (isRunning) {
Canvas theCanvas = null;
startTime = System.currentTimeMillis();
try {
theCanvas = theView.getHolder().lockCanvas();
synchronized (theView.getHolder()) {
theView.onDraw(theCanvas);
}
} finally {
if (theCanvas != null) {
theView.getHolder().unlockCanvasAndPost(theCanvas);
}
}
sleepTime = TPS - (System.currentTimeMillis() - startTime);
try {
if (sleepTime > 0)
sleep(sleepTime);
else
sleep(10);
} catch (Exception e) {
}
}
}
}
MainAcitvity.java:
package com.example.test.threadtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}

Related

How to manage exoplayer with java in android studio?

I am searching Exoplayer using with ViewPager in java but can not find the full tutorial.
I have issue for stopping and pausing exoplayer while swiping another video.
Is there any tutorial please suggest me.
Adapter.java
package com.daasuu.gpuvideoandroid.Adapter;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.RecyclerView;
import com.daasuu.gpuvideoandroid.Activity.OtherUser.OtherUserProfileActivity;
import com.daasuu.gpuvideoandroid.Model.MainVideoDataModel;
import com.daasuu.gpuvideoandroid.R;
import com.daasuu.gpuvideoandroid.Utils.VideoCache;
import com.daasuu.gpuvideoandroid.databinding.ItemMainVideoBinding;
import com.google.android.exoplayer2.ExoPlayer;
import com.google.android.exoplayer2.MediaItem;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.source.ProgressiveMediaSource;
import com.google.android.exoplayer2.ui.PlayerView;
import com.google.android.exoplayer2.ui.StyledPlayerView;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.cache.CacheDataSource;
import java.util.List;
public class MainVideoAdapter2 extends RecyclerView.Adapter<MainVideoAdapter2.MyViewHolder> {
private Context context;
private List<MainVideoDataModel> data;
private boolean likeFlag = false;
private boolean followFlag = false;
private boolean isPlaying = false;
ExoPlayer exoplayer;
StyledPlayerView styledPlayerView;
public MainVideoAdapter2(Context context, List<MainVideoDataModel> data) {
this.context = context;
this.data = data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemMainVideoBinding binding = DataBindingUtil.inflate(LayoutInflater.from(context), R.layout.item_main_video, parent, false);
return new MyViewHolder(binding);
}
#Override
public void onBindViewHolder(MainVideoAdapter2.MyViewHolder holder, int position) {
MainVideoDataModel model = data.get(position);
holder.setExoplayerStyled(model.getVideo_url());
}
#Override
public int getItemCount() {
return data.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ItemMainVideoBinding binding;
public MyViewHolder(ItemMainVideoBinding binding) {
super(binding.getRoot());
this.binding = binding;
binding.imageUserMainVideo.setOnClickListener(this);
binding.videoView.setOnClickListener(this);
}
// styled exoplayer with cache
void setExoplayerStyled(String video_url){
binding.progressCircular.setVisibility(View.VISIBLE);
exoplayer = new ExoPlayer.Builder(context).build();
styledPlayerView = binding.videoStyledPlayerView;
styledPlayerView.hideController();
styledPlayerView.setUseController(false);
ProgressiveMediaSource mediaSource = new ProgressiveMediaSource.Factory(
new CacheDataSource.Factory()
.setCache(VideoCache.getInstance2(context))
.setUpstreamDataSourceFactory(new DefaultHttpDataSource.Factory()
.setUserAgent("rgcache"))
.setFlags(CacheDataSource.FLAG_IGNORE_CACHE_ON_ERROR)
).createMediaSource(MediaItem.fromUri(video_url));
exoplayer.seekTo(0);
exoplayer.prepare();
exoplayer.pause();
styledPlayerView.setPlayer(exoplayer);
exoplayer.setPlayWhenReady(false);
binding.videoStyledPlayerView.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
#Override
public void onViewAttachedToWindow(View view) {
styledPlayerView.setKeepScreenOn(true);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().play();
}
}
#Override
public void onViewDetachedFromWindow(View view) {
binding.videoStyledPlayerView.getPlayer().stop();
binding.videoStyledPlayerView.getPlayer().clearMediaItems();
exoplayer.seekTo(0);
exoplayer.setPlayWhenReady(false);
exoplayer.stop();
if(binding.videoStyledPlayerView.getPlayer() != null) {
binding.videoStyledPlayerView.getPlayer().pause();
}
}
});
//buffering
exoplayer.addListener(new Player.Listener() {
#Override
public void onIsLoadingChanged(boolean isLoading) {
Player.Listener.super.onIsLoadingChanged(isLoading);
// Log.e("onIsLoadingChanged", String.valueOf(isLoading));
}
#Override
public void onPlaybackStateChanged(int playbackState) {
Player.Listener.super.onPlaybackStateChanged(playbackState);
Log.e("onPlaybackStateChanged", String.valueOf(playbackState));
binding.imgVideoStop.setVisibility(View.GONE);
if (playbackState == 3){
binding.progressCircular.setVisibility(View.GONE);
}
}
#Override
public void onPlayWhenReadyChanged(boolean playWhenReady, int reason) {
Player.Listener.super.onPlayWhenReadyChanged(playWhenReady, reason);
}
});
// touch listener play & pause
binding.videoStyledPlayerView.getVideoSurfaceView().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isPlaying == false){
binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = true;
exoplayer.setPlayWhenReady(false);
}else{
binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = false;
styledPlayerView.setKeepScreenOn(true);
styledPlayerView.setPlayer(exoplayer);
exoplayer.addMediaSource(mediaSource);
exoplayer.prepare();
exoplayer.setPlayWhenReady(true);
exoplayer.setRepeatMode(exoplayer.REPEAT_MODE_ONE);
}
}
});
}
//on click event
#Override
public void onClick(View v) {
if (v == binding.imageUserMainVideo) {
context.startActivity(new Intent(context, OtherUserProfileActivity.class));
}
if (v == binding.videoView) {
Log.e("isPlaying = " , String.valueOf(isPlaying));
if (isPlaying) {
binding.videoView.pause();
// binding.imgVideoStop.setVisibility(View.VISIBLE);
isPlaying = false;
} else {
binding.videoView.start();
// binding.imgVideoStop.setVisibility(View.GONE);
isPlaying = true;
}
}
}
}
}
item.xml
<com.google.android.exoplayer2.ui.StyledPlayerView
android:id="#+id/videoStyledPlayerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="visible"
app:animation_enabled="true"/>
Issues:
After a specific position, it plays previous videos when swipe to next video.
Plays multiple videos on swipe
On swipe back(previous videos) don't stops previous video.
How to stop when to redirect another activity.
Please suggest the solution.
You can use addOnPageChangeListener for getting the user interaction for the view pager. add this code snippet in the onCreate method.In my project ,I handle it like this ::
binding!!.mediaViewPager.addOnPageChangeListener(object : OnPageChangeListener {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageSelected(position: Int) {
if (exoPlayer.isPlaying) {
exoPlayer.pause()
}
}
override fun onPageScrollStateChanged(state: Int) {
exoPlayer.pause()
}
})
Play Exo Player With PageViwer
Link:
https://github.com/google/ExoPlayer/issues/7947
Example:
https://github.com/kakajika/PlayerPagerExample

Why this Android Application Package shows an unexpected error when it was run?

All the class is posted serially. This program was correct till the background of "GameActivity" was set by creating a custom view. But after then when i want to add single robot with every single touch in android device, it shows "an unexpected error".
WelcomeActivity
package com.emdad.androidapp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
public class WelcomeActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_welcome);
final Button startButton=(Button) findViewById(R.id.androidButton);
startButton.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
switch (arg1.getAction()) {
case MotionEvent.ACTION_DOWN:
startButton.getBackground().setAlpha(100);
break;
case MotionEvent.ACTION_UP:
Intent intent=new Intent(WelcomeActivity.this, GameActivity.class);
startActivity(intent);
startButton.getBackground().setAlpha(255);
break;
case MotionEvent.ACTION_MOVE:
break;
default:
break;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.welcome, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
GameActivity
package com.emdad.androidapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.view.WindowManager;
public class GameActivity extends Activity {
GameView gameView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
gameView=new GameView(this);
setContentView(gameView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.game, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
GameView
package com.emdad.androidapp;
import java.util.Random;
import android.content.Context;
import android.graphics.Point;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
public class GameView extends SurfaceView implements Callback{
Context context;
SurfaceHolder surfaceHolder;
DrawingThread drawingThread;
public GameView(Context context) {
super(context);
this.context=context;
surfaceHolder=getHolder();
surfaceHolder.addCallback(this);
drawingThread=new DrawingThread(this, context);
}
#Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
}
#Override
public void surfaceCreated(SurfaceHolder arg0) {
try {
drawingThread.start();
} catch (Exception e) {
restartThread();
}
}
private void restartThread() {
drawingThread.stopThread();
drawingThread=null;
drawingThread=new DrawingThread(this, context);
drawingThread.start();
}
#Override
public void surfaceDestroyed(SurfaceHolder arg0) {
drawingThread.stopThread();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Point touchPoint=new Point();
touchPoint=new Point((int)event.getX(), (int)event.getY());
Random random=new Random();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
drawingThread.allRobots.add(new Robot(drawingThread.allPossibleRobots.get(random.nextInt(6)), touchPoint));
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
drawingThread.allRobots.get(drawingThread.allRobots.size()-1).setCenter(touchPoint);
break;
default:
break;
}
return super.onTouchEvent(event);
}
}
DrawingThread
package com.emdad.androidapp;
import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.view.Display;
import android.view.WindowManager;
public class DrawingThread extends Thread{
private Canvas canvas;
private GameView gameView;
private Context context;
boolean threadFlag=false;
Bitmap backgroundBitmap;
int displayX, displayY;
ArrayList<Robot> allRobots;
ArrayList<Bitmap> allPossibleRobots;
public DrawingThread(GameView gameView, Context context) {
super();
this.gameView = gameView;
this.context = context;
initializaeAll();
}
private void initializaeAll() {
WindowManager windowManager=(WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display defaultDisplay=windowManager.getDefaultDisplay();
Point displayDimension=new Point();
defaultDisplay.getSize(displayDimension);
displayX=displayDimension.x;
displayY=displayDimension.y;
backgroundBitmap=BitmapFactory.decodeResource(context.getResources(), R.drawable.background1);
backgroundBitmap=Bitmap.createScaledBitmap(backgroundBitmap, displayX, displayY, true);
initializeAllPossibleRobots();
}
private void initializeAllPossibleRobots() {
allRobots=new ArrayList<Robot>();
allPossibleRobots=new ArrayList<Bitmap>();
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.android));
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.android2));
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.android3));
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.android6));
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.apple));
allPossibleRobots.add(giveResizedRobotBitmap(R.drawable.apple2));
}
private Bitmap giveResizedRobotBitmap(int resourceID) {
Bitmap tempBitmap=BitmapFactory.decodeResource(context.getResources(), resourceID);
tempBitmap=Bitmap.createScaledBitmap(tempBitmap, displayX/5, (tempBitmap.getHeight()/tempBitmap.getWidth())*(displayX/5), true);
return tempBitmap;
}
#Override
public void run() {
threadFlag=true;
while (threadFlag) {
canvas=gameView.surfaceHolder.lockCanvas();
try {
synchronized (canvas) {
updateDisplay();
}
} catch (Exception e) {
e.printStackTrace();
} finally{
if (canvas!=null) {
gameView.surfaceHolder.unlockCanvasAndPost(canvas);
}
}
try {
Thread.sleep(17);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void updateDisplay() {
canvas.drawBitmap(backgroundBitmap, 0, 0, null);
for (int i = 0; i < allRobots.size(); i++) {
Robot temprRobot=allRobots.get(i);
canvas.drawBitmap(temprRobot.robotBitmap, temprRobot.centerX-(temprRobot.width/2), temprRobot.centerY-(temprRobot.height/2), temprRobot.robotPaint);
}
}
public void stopThread() {
threadFlag=false;
}
}
Robot
package com.emdad.androidapp;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.graphics.Point;
public class Robot {
int centerX, centerY;
int height, width;
Bitmap robotBitmap;
Paint robotPaint;
public Robot(Bitmap bitmap) {
robotBitmap=bitmap;
centerX=centerY=0;
height=robotBitmap.getHeight();
width=robotBitmap.getWidth();
robotPaint=new Paint();
}
public Robot(Bitmap bitmap, int cX, int cY) {
this(bitmap);
centerX=cX;
centerY=cY;
}
public Robot(Bitmap bitmap, Point center) {
this(bitmap, center.x, center.y);
}
public void setCenter(Point centerPoint) {
centerX=centerPoint.x;
centerY=centerPoint.y;
}
}

Android thread test does not work

Hi I'm beginner with android development and I have a problem with my following test code:
Main Activity:
package com.test.thread;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView txt = null;
Button btStart = null;
Button btStop = null;
TestClass test = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = (TextView)findViewById(R.id.txtView);
btStart = (Button)findViewById(R.id.bt_start);
btStop = (Button)findViewById(R.id.bt_stop);
test = new TestClass(this, txt);
btStop.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
test.Stop();
}
});
btStart.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Thread t = new Thread(){
#Override
public void run() {
// TODO Auto-generated method stub
try{
synchronized (this) {
wait(50);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
while(test.isStop()){
try {
wait(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
test.DoSomeThing();
}
}
});
}
}catch( InterruptedException e)
{
e.printStackTrace();
}
}
};
t.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
TestCLas.java:
package com.tutorial.sample;
import android.content.Context;
import android.widget.TextView;
import android.widget.Toast;
public class TestClass{
private boolean stopIter = false;
private TextView txtV = null;
private int count = 0;
private Context ctx = null;
public TestClass(Context ct, TextView tv) {
// TODO Auto-generated constructor stub
txtV = tv;
stopIter = false;
count = 0;
ctx = ct;
}
public boolean isStop() { return stopIter; }
public void Stop()
{
Toast.makeText(ctx, "stop the test" , Toast.LENGTH_LONG).show();
count = 0;
txtV.setText(Integer.toString(count));
stopIter = true;
}
public void DoSomeThing(){
txtV.setText(Integer.toString(count));
}
}
I want to manage my activity's viewer with threads. I launch a thread in order to modify TextView's text (each sec) when the start button is clicked and stop it when stop button is clicked. But it does not work, it crashes without any exception. Can someone help me please?
wait(1000);
This should NEVER be done on the UI thread.
The UI thread is the one that update the GUI, and communicates with Android to say everything is working as expected. When you have a thread delay on the UI thread, the message to and from the android system get held back, and you app appears to the system as if it has crashed.

MediaPlayer plays double sounds on change orientation

I have a big problem with this app. The problem with it is that when the orientation changes to landscape and then change it to portrait the music twice tracks plays at the same time. But when i start the app on portrait i have no problem with it.
package com.phone.sensor;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
public class sensorActivity extends Activity implements SensorEventListener{
public boolean musStatus = false;
public boolean musDeclare = true;
public MediaPlayer mp = null;
Sensor accelerometer;
SensorManager sm;
TextView acceleration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState == null){
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
} else {
if(mp != null){
mp.stop();
mp.reset();
mp = null;
}
}
setContentView(R.layout.activity_main);
sm=(SensorManager) getSystemService(SENSOR_SERVICE);
accelerometer=sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sm.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
acceleration=(TextView)findViewById(R.id.acceleration);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putBoolean("musStatus", musStatus);
outState.putBoolean("musDeclare", musDeclare);
}
public Object onRetainCustomNonConfigurationInstance() {
return this.mp;
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
acceleration.setText("X: "+event.values[0]+
"\nY: "+event.values[1]+
"\nZ: "+event.values[2]);
float x = event.values[0];
float y = event.values[1];
float z = event.values[2];
if(y > 8.9) {
if(musDeclare == true)
{
mp = MediaPlayer.create(this, R.raw.alexander);
musDeclare = false;
}
if(musStatus == false)
{
mp.start();
musStatus = true;
}
}
if(y < 5)
{
if(musStatus == true)
{
mp.stop();
mp.reset();
mp = null;
musStatus = false;
musDeclare = true;
}
}
}
}
Try putting this block of code in the OnPause method of your class
if(mp != null && mp.IsPlaying()){
mp.stop();
mp.reset();
mp = null;
}
}

The application App(process com.example.app) has stopped unexpectedly [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
My problem:
I actually want to set the visibility of my ImageView on random basis. I mean each Image View will be Visible randomly after few milliseconds but my my app unexpectedly crashes all the time. Though, I'm new to android development but good at Java J2SE. Please tell me what I'm doing is it a blunder or a mistake by chance? please! thanks in advance!
package com.example.app;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends Activity {
private Button b;
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
Thread t=new Thread(new MyThread());
t.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private class MyThread implements Runnable{
Random randomGenerator = new Random();
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
try {
Thread.currentThread().sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.getStackTrace();
}
}
}
}
}
THE EDITED CODE:
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
Random randomGenerator = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1=new ImageView(this);
I1=(ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2=new ImageView(this);
I2=(ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3=new ImageView(this);
I3=(ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4=new ImageView(this);
I4=(ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T=(TextView)findViewById(R.id.time);
s=(TextView)findViewById(R.id.score);
runOnUiThread(new Runnable() //run on ui thread
{
int n;
public void run(){
while(true){
n=randomGenerator.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
You must be getting an exception as above. You need to update ui on the UI thread. You are updating UI in the thread. Hence the exception and crash.
Inside your thread use runOnUiThread to update UI
runOnUiThread(new Runnable() //run on ui thread
{
public void run()
{
while(true){
n=randomGenerator.nextInt(8);
if(n==1){
I1.setVisibility(View.VISIBLE);
}
....
}
}
});
Also remove this I1=new ImageView(this); since you are initializing as I1=(ImageView) findViewById(R.id.imag1);
Edit:
I would recommend using a Handler for this purpose
int n;
Handler m_handler;
Runnable m_handlerTask ;
Random r;
Declare the above as class variables;
Inside the activity onCrate() use a handler as below
r= new Random();
m_handler= new Handler();
m_handlerTask = new Runnable()
{
#Override
public void run() {
n=r.nextInt(4)+1;
if(n==1){
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==2){
I2.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==3){
I3.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if(n==4){
I4.setVisibility(View.VISIBLE);
I1.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
}
m_handler.postDelayed(m_handlerTask, 50);
// 50 milli seconds. set this to desired number
}
};
m_handlerTask.run();
And remember to stop the handler when not required
m_handler.removeCallbacks(m_handlerTask);
I think you want full code. You can use timer. see the following code.
public class MainActivity extends Activity {
public ImageView I1;
public ImageView I2;
public ImageView I3;
public ImageView I4;
public TextView T;
public TextView s;
int n;
Timer t;
TimerTask task;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
I1 = (ImageView) findViewById(R.id.imag1);
I1.setVisibility(View.INVISIBLE);
I2 = (ImageView) findViewById(R.id.imag2);
I2.setVisibility(View.INVISIBLE);
I3 = (ImageView) findViewById(R.id.imag3);
I3.setVisibility(View.INVISIBLE);
I4 = (ImageView) findViewById(R.id.imag4);
I4.setVisibility(View.INVISIBLE);
T = (TextView) findViewById(R.id.time);
s = (TextView) findViewById(R.id.score);
startTimer();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void startTimer() {
//Random randomGenerator = new Random();
//n=randomGenerator.nextInt(8);
final Random randomGenerator = new Random();
t = new Timer();
task = new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
//n++;
n=randomGenerator.nextInt(8);
if (n == 1) {
I1.setVisibility(View.VISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 2) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.VISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 3) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.VISIBLE);
I4.setVisibility(View.INVISIBLE);
}
if (n == 4) {
I1.setVisibility(View.INVISIBLE);
I2.setVisibility(View.INVISIBLE);
I3.setVisibility(View.INVISIBLE);
I4.setVisibility(View.VISIBLE);
}
}
});
}
};
t.scheduleAtFixedRate(task, 0, 1000);
}
}
This will work perfectly. I hope this will help you.
It is perfect ! 100%
package com.example.abc;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Test extends Activity {
public Button B;
public Button B1;
public TextView S;
int count=0;
Random randomGenerator = new Random();
int n;
int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
B=new Button(this);
B=(Button)findViewById(R.id.button1);
B.setVisibility(View.INVISIBLE);
B1=new Button(this);
B1=(Button)findViewById(R.id.button2);
B1.setVisibility(View.INVISIBLE);
S=(TextView)findViewById(R.id.score);
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
B.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
count+=1;
S.setText(Integer.toString(count));
}
});
runThread();
}
private void runThread() {
new Thread() {
public void run() {
while ( i++ < 1200) {
if(i==1200){
startActivity(new Intent(Test.this,Game.class));
break;
}
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
n = randomGenerator.nextInt(4)+1;
if(n==2){
B.setVisibility(View.VISIBLE);
B1.setVisibility(View.INVISIBLE);
}
if(n==4){
B.setVisibility(View.INVISIBLE);
B1.setVisibility(View.VISIBLE);
}
}
});
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.test, menu);
return true;
}
}

Categories