My SecondActivity crashes when have more than Three ImageButton is placed - java

When i am placing three images in my activity it crashes.Can't able to find out
the issue.
First activity
public class SquareMain extends AppCompatActivity {//MainActivity
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {//OnCreate
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_square_main);
mainmusic();
}//OnCreate
public void presshere(View view)//pressherebutton
{
Intent press = new Intent(SquareMain.this, SquareHome.class);
startActivity(press);
}//pressherebutton
public void mainmusic(){//mainmusic
MediaPlayer mainmusic = MediaPlayer.create(SquareMain.this, R.raw.mainmeunsong);//main music
mainmusic.start();//main music
mainmusic.setLooping(true);//main music
}
}//MainActivity
Second activity
public class SquareHome extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_square_home);
}
}
Image button
<ImageButton
android:id="#+id/pressherebutton"
android:layout_width="161dp"
android:layout_height="28dp"
android:layout_marginBottom="8dp"
android:layout_marginTop="8dp"
android:background="#mipmap/squarepresshere"
android:onClick="presshere"
android:scaleType="centerCrop"
android:text="#string/presshere"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.86"
app:srcCompat="#drawable/squarepresshere"
tools:layout_editor_absoluteY="223dp" />
my SecondActivity crashes when more than three image button is placed.
Anyone that might have any idea on how to solve this?

What is the size of those images?? Size of an images is also the factors we have to consider for smooth and comfortable to render images. High resolution images may cause ANR.

You need to terminate your MediaPlayer before leaving the Activity, override onPause method and stop your MediaPlayer. declare your mainmusic as class variable not local.
#Override
protected void onPause() {
super.onPause();
if (mainmusic != null) {
if (mainmusic.isPlaying())
mainmusic.stop();
mainmusic.reset();
mainmusic.release();
}
}

Related

Simple Countdown in Android Studio using JAVA

I'm trying to make simple 60seconds countdown timer in Android Studio using java. Only problem is that it appears like this: "00:60". But I want it to be like this: "60". And also I want to reset and switch to another class as soon as timer hits 0. And when I visit this timer activity I want it to start timer again and so on... Here's my java code:
public class BeginAfter extends AppCompatActivity {
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_begin_after);
textView = findViewById(R.id.timer);
long duration = TimeUnit.MINUTES.toMillis(1);
new CountDownTimer(duration, 1000){
#Override
public void onTick(long l) {
String sDuration = String.format(Locale.ENGLISH,"%02d : %02d"
,TimeUnit.MILLISECONDS.toMinutes(l)
,TimeUnit.MILLISECONDS.toSeconds(l) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l)));
textView.setText(sDuration);
}
#Override
public void onFinish() {
textView.setVisibility(View.INVISIBLE);
}
}.start();
}
}
And here's my xml code:
<TextView
android:id="#+id/timer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#d10e00"
android:textSize="37dp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.064" />
Try:
String sDuration =
String.format(
Locale.ENGLISH,
"%02d",
TimeUnit.MILLISECONDS.toSeconds(l) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(l))
);
This will replace %02d in the String "%02d" with the first given integer in the following arguments of String.format and try to display it with only 2 digits.

How can I control the media player with service?

I am new to coding and at this point, I made a media player that starts and pauses the audio, has a working seekbar, duration, etc. Now I faced a big issue. The audio can't be played in the background and I found out that I can do this with service but this changes things. I read all kinds of topics on how to control the audio in service with seekbar and all kinds of stuff but nothing helped me. The main problem I face is having the seekbar to control the audio and a text to read the time. If there is someone to help me find a code for this it would be much appreciated.
The layout:
<SeekBar
android:id="#+id/seekBarMusic1"
android:layout_width="match_parent"
android:layout_height="#dimen/_20sdp"
android:layout_marginTop="#dimen/_12sdp"
android:layout_marginLeft="#dimen/_20sdp"
android:layout_marginRight="#dimen/_20sdp"
app:layout_constraintTop_toBottomOf="#+id/cardView"
tools:layout_editor_absoluteX="10dp" />
<TextView
android:id="#+id/playerPositionMusic"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:textColor="#color/remain_black"
android:textSize="25dp"
android:layout_marginBottom="#dimen/_80sdp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="#+id/cardView"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1" />
<TextView
android:id="#+id/text_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="#dimen/_80sdp"
android:text="15:00"
android:textColor="#color/remain_black"
android:textSize="25dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="#+id/cardView"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1" />
<ImageView
android:id="#+id/btPlayMusic"
android:layout_width="80dp"
android:layout_height="80dp"
android:alpha="0.9"
android:background="#drawable/play"
android:theme="#style/Button.White"
app:layout_constraintEnd_toStartOf="#+id/text_time"
app:layout_constraintStart_toEndOf="#+id/playerPositionMusic"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1"
app:tint="#color/remain_black" />
<ImageView
android:visibility="gone"
android:id="#+id/btPauseMusic"
android:layout_width="80dp"
android:layout_height="80dp"
android:alpha="0.9"
android:background="#drawable/pause"
android:theme="#style/Button.White"
app:layout_constraintEnd_toStartOf="#+id/text_time"
app:layout_constraintStart_toEndOf="#+id/playerPositionMusic"
app:layout_constraintTop_toBottomOf="#+id/seekBarMusic1"
app:tint="#color/remain_black" />
The code I used before:
public class m1 extends AppCompatActivity {
ImageView btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
findViewById(R.id.backm1).setOnClickListener(v -> onBackPressed());
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(v -> {
mediaPlayer.start();
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0)
});
btPause.setOnClickListener(v -> {
mediaPlayer.stop();
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
handler.removeCallbacks(runnable);
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
mediaPlayer.setOnCompletionListener(mp -> {
btPause.setVisibility((View.GONE));
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
});
}
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
,TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
public void onPause()
{
if(mediaPlayer != null && mediaPlayer.isPlaying())
{
mediaPlayer.stop();
}
super.onPause();
}
}
The code I am using now:
btPause = findViewById(R.id.btPauseMusic);
btPlay = findViewById(R.id.btPlayMusic);
btPlay.setOnClickListener(v -> {
startService(new Intent(this, BackgroundMusicService.class));
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
});
btPause.setOnClickListener(v -> {
stopService(new Intent(this, BackgroundMusicService.class));
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
});
}
And the service class:
public class BackgroundMusicService extends Service {
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer = MediaPlayer.create(this, R.raw.ding_dong);
mediaPlayer.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
}
You are using different MediaPlayer in the Activity from the one in the backgroundService
you don't need to initialize another mediaPlayer in the activity you have to control the one in the backgroundService with Broadcast receivers like this for example to pause a the mediaPlayer in the backgroundService you do something like this
private BroadcastReceiver pausePlayingAudio = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
pause();
updateMetaData();
buildNotification(PlaybackStatus.PAUSED);
playbackStatus = PlaybackStatus.PAUSED ;
}
};
private void register_pausePlayingAudio(){
IntentFilter intentFilter = new IntentFilter(SongAdapter.ACTION_PAUSE) ;
registerReceiver(pausePlayingAudio , intentFilter) ;
}
and you call register_pausePlayingAudio() in onCreate() of the backGroundService
now say when a user clicks on a button in the activity and you want to pause you use something like this
sendBroadcast(new Intent(SongAdapter.ACTION_PAUSE));
I have and old project not finished doesn't have a seekBar but the seekBar implementation will be similar just instead of pause() you call seekTo() so you can check it
the repo
This article Creating Media player service shows step by step on how you can implement a service to create a Mediaplayer application to run in the background.

Android cannot find symbol variable error

I'm following this example from http://developer.android.com to build a simple app to find the last known location. I get the cannot find symbol variable error for the variables, mLastLocation, mLatitudeText and mLongitudeText in the following code snippet in the activity file:
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
The variables aren't defined in the sample too. How can I fix this?
You need to define the two mentioned TextView widgets in your UI or main_activity.xml file
....
<TextView
android:text="-"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textview1"
/>
<TextView
android:text="-"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textview2"
/>
....
..and then reference them in the code in your MainActivity.java file.
For mLastLocation, well it needs to be Location type, since the function getLastLocation returns a Location type.
public class MainActivity extends ActionBarActivity implements
ConnectionCallbacks, OnConnectionFailedListener {
Location mLastLocation;
TextView mLatitudeText,mLongitudeText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mLatitudeText=(TextView)findViewById(R.id.textview1);
mLongitudeText=(TextView)findViewById(R.id.textview2);
}
...
#Override
public void onConnected(Bundle connectionHint) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
}
}
The link to the android developers website isn't pointing to a specific tutorial, so I can speak directly to that one. However, the mLatitudeText and mLongitudeText appear to be simple TextViews. If they aren't created, you can just create them and add them to the activity yourself.

About variables and screen touch events

I'm rather new to all this, so please bear with me.
what I want to do: interchange the position of two squares on the screen as soon as the user touches the screen.
what I've done so far: in my layout xml, I've used a frame layout end defined the two squares:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frame1"
android:layout_width="260dp"
android:layout_height="540dp"
android:layout_gravity="center_horizontal" >
<EditText
android:id="#+id/square1"
android:enabled="false"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/textlines"
android:clickable="false"
android:gravity="center"
android:inputType="none"
android:text="#string/C1"
android:textSize="25sp" />
<EditText
android:id="#+id/square2"
android:enabled="false"
android:layout_width="50dp"
android:layout_height="50dp"
android:background="#drawable/textlines"
android:clickable="false"
android:gravity="center"
android:inputType="none"
android:text="#string/C2"
android:textSize="25sp" />
Then in Java, I've done the following:
public class Activity1 extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
EditText square1 = (EditText) findViewById(R.id.square1);
int cc1x = 210;
int cc1y = 410;
square1.setX(cc1x);
square1.setY(cc1y);
EditText square2 = (EditText) findViewById(R.id.square2);
int cc2x = 310;
int cc2y = 410;
square2.setX(cc2x);
square2.setY(cc2y);
int ccdumx = 410;
int ccdumy = 410;
}
In order to get the initial screen - so far so good. The two variables ccdumx and ccdumy are just there for an intermediate storage of one of the two squares when interchanging them
So now I add an event listener to detect a screen touch, followed by the changing of the coordinate variables:
#Override
public boolean onTouchEvent(MotionEvent event) {
ccdumx = cc1x;
ccdumy = cc1y;
cc1x = cc2x;
cc1y = cc2y;
cc2x = ccdumx;
cc2y = ccdumy;
square1.setX(cc1x);
square1.setY(cc1y);
square2.setX(cc2x);
square2.setY(cc2y);
}
but then the variables aren't recognized, nor are the squares' names. When I declare them all again in this bloc, it does work, but then my logic only works one time; I can't switch the squares back, since the variables of the coordinates are always reset by the declaration, followed by the switch of positions... I'm kinda stuck here I was thinking maybe switching first to another activity, but then again, I might have the same problem there... Any help is most appreciated.
PS. I hope the formatting of the code turns out ok, first timer for me. If not, please accept my apologies.
Because all these variables are local to method onCreate(). You need to define them globally to whole class, i.e. outside method onCreate().
The java code in first block of your question should be changed to this.
public class Activity1 extends ActionBarActivity {
int cc1x, cc1y, cc2x, cc2y, ccdumx, ccdumy;
EditText square1, square2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout1);
square1 = (EditText) findViewById(R.id.square1);
cc1x = 210;
cc1y = 410;
square1.setX(cc1x);
square1.setY(cc1y);
square2 = (EditText) findViewById(R.id.square2);
cc2x = 310;
cc2y = 410;
square2.setX(cc2x);
square2.setY(cc2y);
ccdumx = 410;
ccdumy = 410;
}
//... rest of the code
You could just make your variables Global
like this
EditText square1;
EditText square2;
int cc1x;
....
protected void onCreate(Bundle savedInstanceState){
square1 = (EditText) findViewById(R.id.square1);
.....
}

Creating a Singleton CountDownTimer in Android

I'm a beginner in android and I've written an activity. It contains a CountDownTimer that counts down from a particular value. It also contains a Button that loads text information and a textview to display count.
Below is the code for Activity1:
public class Screen extends Activity1 implements OnClickListener {
private static final int MILLIS_PER_SECOND = 1000;
private static final int SECONDS_TO_COUNTDOWN = 1;
TextView Time;
int totaltime;
Button startTimer, howTo, pause;
protected CountDownTimer MyTimer;
int PracticeCount;
long tot;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.pushupscreen);
getRefs();
getSpeed();
getCount();
setTotalTime();
startTimer.setOnClickListener(this);
pause.setOnClickListener(this);
}
private void getRefs() {
// Initialize layout resources
Time = (TextView) findViewById(R.id.tvTime);
startTimer = (Button) findViewById(R.id.bStart);
howTo = (Button) findViewById(R.id.btHowTo);
pause = (Button) findViewById(R.id.bPause);
howTo.setOnClickListener(this);
}
private void getTheCount() {
//get count from SharedPreferences
}
private void getSpeed() {
//get speed from SharedPreferences
}
private void setCount(){
totalTime=speed*count;}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v == startTimer) {
try {
showTimer(time);
} catch (NumberFormatException e) {
// method ignores invalid (non-integer) input and waits
// for something it cant use
}
} else if (v == pause) {
MyTimer.cancel();
Timer.setText("Resume");
} else if (v == howTo) {
//Launch screen containing information
}
}
private void showTimer(long time) {
if (MyTimer != null) {
MyTimer.cancel();
}
MyTimer = new CountDownTimer(tot2, MILLIS_PER_SECOND) {
#Override
public void onTick(long millisUntilFinished) {
tot = millisUntilFinished;
long seconds = millisUntilFinished / 1000;
Time.setText(String.format("%02d", seconds / 60) + ":"
+ String.format("%02d", seconds % 60));
}
#Override
public void onFinish() {
Time.setText("KABOOM!");
}
}.start();
}
}
And here is the layout file for this:
<TextView
android:id="#+id/tvTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:gravity="center"
android:padding="10dip"
android:text="#string/starttime"
android:textSize="60sp" />
<Button
android:id="#+id/bStart"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:text="Start" />
<Button
android:id="#+id/bPause"
android:layout_width="150dp"
android:layout_height="wrap_content"
android:layout_above="#+id/tvTime"
android:layout_toRightOf="#+id/btHowTo"
android:text="Pause" />
<TextView
android:id="#+id/tvCount"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/btHowTo"
android:layout_centerHorizontal="true"
android:layout_marginTop="39dp"
android:text="25"
android:textSize="80sp"
android:textAlignment="center"/>
My questions:
1.How do I create 4 activities that use the same layout and the same timer? Each Activity loads a different content in the textview and a different screen on the click of HowTo button.
2.How can Activity1 be designed to run for 1/4th the time set and pass remaining time to Activity2? Is it possible?
I would really appreciate any help and advice that you can provide. Thanks.
A couple things here.
Its very easy to re-use layouts. In each activity's onCreate you would just call:
setContentView(R.layout.pushupscreen); The pushupscreen.xml file can be shared across all activities this way.
What you probably want to do is persist a timestamp to some common data source for all the activities. This could be a write to a SharedPreferences file: Documentation here. Then as each activity resumes, check how much time has already passed by comparing this timestamp to the current timestamp. You could also pass the timestamp as an extra in the intent to start up the subsequent activities. The documentation for that can be found here and here
You could make a custom control, which is basically a new class which inherits some other control's class (for example a LinearLayout or a RelativeLayout). You could then load a view's XML to your new layout or programmatically create new controls inside your control. More info here:
Custom components in Android
After a 1/4 of your countdown period, you can create and send an Intent to start a new activity in the onTick method. You can also put the remaining 3/4 as a millisecond value (of type long) in an intent extra. You can then obtain this value in the new activity and invoke a custom CountDownTimer child there for the rest of your countdown. Then you can finally execute what you wish after the countdown is done in the onFinish() method.

Categories