i have the next code, and i want to put a method (i am newbie and don´t get how can i do that). Because when i am playing the sound and finish the app, this continue and can´t stop it, and if i put mp.pause(); before this finish(by Exit button) works, BUT if i NEVER pressed Play, my app don´t play the sound after this.
With methods i mean: if (SoundPlaying) mp.pause();
Code:
import com.google.ads.AdRequest;
import com.google.ads.AdView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final AdView adView = (AdView) findViewById(R.id.adView);
adView.loadAd(new AdRequest());
final MediaPlayer mp = MediaPlayer.create(this, R.raw.rain);
final ImageView Play = (ImageView) findViewById(R.id.imageView1);
Play.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
Animation Rotate = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
Play.startAnimation(Rotate);
mp.start();
}});
final ImageView Pause = (ImageView) findViewById(R.id.imageView2);
Pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mp.pause();
Animation Rotate = AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate);
Pause.startAnimation(Rotate);
}});
final ImageView Exit = (ImageView) findViewById(R.id.imageView3);
Exit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
MainActivity.this);
// Setting Dialog Title
alertDialog.setTitle("Do you want to exit?");
// Setting Dialog Message
alertDialog.setMessage("If you liked the app, please Rate us!");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.exit2);
// Setting Positive Yes Button
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// User pressed Yes button. Write Logic Here
finish();
}
});
// Setting Neutral Button
alertDialog.setNeutralButton("Rate us!",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Uri uri = Uri.parse("market://details?id=" + getPackageName());
Intent goToMarket = new Intent(Intent.ACTION_VIEW, uri);
try {
startActivity(goToMarket);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Couldn´t launch Google Play",
Toast.LENGTH_LONG).show();
}
}
});
// Setting Positive "Cancel" Button
alertDialog.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
});
//Orientación de la APP Vertical
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
I think you mean "How do i implement an if statement" rather than method. You need to check if music is playing, and stop it if it is. Then once it has been stopped you can finish the activity.
alertDialog.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (mp.isPlaying()){
mp.stop();
}
finish();
}
});
When you are pausing sound after that write int length = mp.getCurrentPosition();
Like-
int length;
mp.pause();
length = mp.getCurrentPosition();
When user click no button write following code to continue playing from recent postion.
mp.seekTo(length);
mp.start();
And for yes button #Nood already answered.
Related
I am trying to use AlertDialog widget in my app, but whatever I do the app crashes at launch. I know something is messed up or not defined but can't seem to find it.I have defined a button for triggering the alert dialog and set 'yes' and 'no' options for the dialog. Selecting 'yes' will result in exiting the app and showing a toast and Selecting 'no' will close the alert dialog and return to app by showing a toast. This is how it should work on paper but as I said the app will crash on launch.
My code:
package com.example.togglebutton;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends AppCompatActivity {
private Button bt;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bt = (Button) findViewById(R.id.btn);
builder = new AlertDialog.Builder(this);
bt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder.setMessage("Do you want to close this application ?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id, ) {
finish();
Toast.makeText(getApplicationContext(), "you chose yes",
Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
Toast.makeText(getApplicationContext(), "you chose no ",
Toast.LENGTH_SHORT).show();
}
});
AlertDialog alert = builder.create();
alert.setTitle("AlertDialogExample");
alert.show();
}
});
}
}
SOLUTION OF YOUR PROBLEM
You need to set the layout of the activity and in the above-posted code what we can see that it is missing. So just add the line below super.onCreate(savedInstanceState);
setContentView(R.layout.YOUR_LAYOUT_NAME);
NOTE: Replace YOUR_LAYOUT_NAME with the name of the layout file which you have defined for MainActivity.
Because you forgot this line
super.onCreate(savedInstanceState);
setContentView(R.layout.yourLayout);
Add setContentView(R.layout.activity_main) below super.onCreate(savedInstanceState);
Can you please help me about this game that I created, I want to reload the same activity, like restart game in quiz game. I hope you guys can help me, this is the code:
package com.example.splash;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.LinearLayoutCompat;
import androidx.core.widget.ImageViewCompat;
import android.content.Intent;
import android.media.Image;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.provider.MediaStore;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class stagenumbereasy1 extends AppCompatActivity {
Button congratsback,congratshome,congratsforward,reload;
ImageView congrats,tryagain;
Animation fromsmall,fromnothing;
MediaPlayer click,congrats1,die;
#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_stagenumbereasy1);
click = MediaPlayer.create(this, R.raw.click);
congrats1 = MediaPlayer.create(this, R.raw.congrats);
die = MediaPlayer.create(this, R.raw.die);
final Button butt8=(Button)findViewById(R.id.button8);
final Button butt9=(Button)findViewById(R.id.button9);
final Button butt10=(Button)findViewById(R.id.button10);
final Button butt11=(Button)findViewById(R.id.button11);
final Button back=(Button)findViewById(R.id.button12);
final LinearLayout overbox=(LinearLayout)findViewById(R.id.overbox);
final LinearLayout congratsbox=(LinearLayout)findViewById(R.id.congratsbox);
final LinearLayout tryagainbox = (LinearLayout)findViewById(R.id.tryagainbox);
final LinearLayout trybox=(LinearLayout)findViewById(R.id.trybox);
fromsmall = AnimationUtils.loadAnimation(this, R.anim.fromsmall);
fromnothing = AnimationUtils.loadAnimation(this, R.anim.fromnothing);
congratsbox.setAlpha(0);
overbox.setAlpha(0);
tryagainbox.setAlpha(0);
trybox.setAlpha(0);
congratsback=(Button)findViewById(R.id.congratsback);
congratshome=(Button)findViewById(R.id.congratshome);
congratsforward=(Button)findViewById(R.id.congratsforward);
congrats=(ImageView)findViewById(R.id.congrats);
reload=(Button)findViewById(R.id.reload);
tryagain=(ImageView)findViewById(R.id.try1);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent back=new Intent (stagenumbereasy1.this,stagenumber.class);
click.start();
startActivity(back);
}
});
butt8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
click.start();
congrats1.start();
butt8.setEnabled(false);
butt9.setEnabled(false);
butt10.setEnabled(false);
butt11.setEnabled(false);
back.setEnabled(false);
overbox.setAlpha(1);
overbox.startAnimation(fromnothing);
congratsbox.setAlpha(1);
congratsbox.startAnimation(fromsmall);
}
});
congratshome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent home = new Intent(stagenumbereasy1.this, Home.class);
click.start();
startActivity(home);
}
});
congratsforward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent easy2 = new Intent(stagenumbereasy1.this, stagenumbereasy2.class);
click.start();
startActivity(easy2);
}
});
butt9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
click.start();
die.start();
butt8.setEnabled(false);
butt9.setEnabled(false);
butt10.setEnabled(false);
butt11.setEnabled(false);
back.setEnabled(false);
trybox.setAlpha(1);
trybox.startAnimation(fromnothing);
tryagainbox.setAlpha(1);
tryagainbox.startAnimation(fromsmall);
reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reload = new Intent(stagenumbereasy1.this, stagenumbereasy1reload.class);
click.start();
startActivity(reload);
finish();
}
});
}
});
butt10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click.start();
die.start();
butt8.setEnabled(false);
butt9.setEnabled(false);
butt10.setEnabled(false);
butt11.setEnabled(false);
back.setEnabled(false);
trybox.setAlpha(1);
trybox.startAnimation(fromnothing);
tryagainbox.setAlpha(1);
tryagainbox.startAnimation(fromsmall);
reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reload = new Intent(stagenumbereasy1.this, stagenumbereasy1reload.class);
click.start();
startActivity(reload);
finish();
}
});
}
});
butt11.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click.start();
die.start();
butt8.setEnabled(false);
butt9.setEnabled(false);
butt10.setEnabled(false);
butt11.setEnabled(false);
back.setEnabled(false);
trybox.setAlpha(1);
trybox.startAnimation(fromnothing);
tryagainbox.setAlpha(1);
tryagainbox.startAnimation(fromsmall);
reload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent refresh = new Intent(stagenumbereasy1.this, stagenumbereasy1reload.class);
click.start();
startActivity(refresh);
finish();
}
});
}
});
}
}
Image of my game
I actually create another activity to make it happens but when I click the reload button it is going back to home. This is my thesis game.
I don't know if exists a recommended answer in Android docs. But, I think you can call startActivity() and finish(), like:
// Java
startActivity(new Intent(MyActivity.class));
finish();
// Kotlin
startActivity(Intent(MyActivity::java.class));
finish();
This will create a new instance of the activity and destroy the current.
For better performance, you should make tests with Fragments instead resetting an Activity.
You could try recreate(); which would recreate the activity
You could also try Intent intent = new Intent(MyActivity.this, MyActivity.class);
startActivity(intent);
Just simply use intent flags one is INTENT_FLAGS_NEW_TASK
it restart activity
Intent.setflags()
In your current activity recall it
Intent(main.this,main.class)
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
im working on a project and im stuck, what i want is after enabling wifi or internet, the back button(hardware button) should bring me back to SplitScreen.xml instead of closing the app please dont give any code to add , as my code is working fine , insted ,correct my code
}}
To achieve the behavior you want, move your call to open Wireless Settings to the MainActivity, and add a boolean variable to its Intent to indicate whether the Settings should be opened in MainActivity.onCreate.
Total Redo Edit
This is your SplashActivity.java. The only problem you should have is the layout name. I don't remember what you named it.
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog.OnClickListener;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class SplashScreen extends Activity
{
static ConnectivityManager cm;
AlertDialog dailog;
AlertDialog.Builder build;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);// checking
build = new AlertDialog.Builder(this);
setContentView(R.layout.activity_splash);
// if connection is
// there screen goes
// to next screen
// else shows
// message
if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()
|| cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting())
{
Log.e("cm value", "" + cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
.isConnectedOrConnecting());
Toast.makeText(this, "Internet is active", 2000).show();
Thread mythread = new Thread() {
public void run()
{
try
{
sleep(5000);
}
catch (Exception e)
{
}
finally
{
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
startActivity(intent);
finish();
}
}
};
mythread.start();
}
else
{
build.setMessage("This application requires Internet connection. Would you connect to internet ?");
build.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
Intent intent = new Intent(SplashScreen.this,
MainActivity.class);
intent.putExtra("showSettings", true);
startActivity(intent);
finish();
//startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
build.setNegativeButton("No", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
build.setMessage("Are sure you want to exit?");
build.setPositiveButton("Yes", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
finish();
}
});
build.setNegativeButton("NO", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
finish();
Intent intent = new Intent(SplashScreen.this,
SplashScreen.class);
startActivity(intent);
dialog.dismiss();
}
});
dailog = build.create();
dailog.show();
}
});
dailog = build.create();
dailog.show();
}
}
}
And this is your MainActivity.
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.provider.Settings;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.ToggleButton;
import android.widget.Toast;
public class MainActivity extends Activity
{
ToggleButton toggle;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toggle = (ToggleButton)findViewById(R.id.tglbtn1);
toggle.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
if (toggle.isChecked())
{
Toast.makeText(getApplicationContext(), "Boosting For Next 60 Minutes, Minimize the Application", Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Boosting Turned Off", Toast.LENGTH_LONG).show();
}
}
}
);
Intent intent = getIntent();
boolean show = intent.getBooleanExtra("showSettings", false);
if (show)
{
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
}
}
Fix the layout name issue in SplashScreen and you should be good. I just ran this code and it performs as expected.
My Alert dialog message doesn't come out because I cannot get the text of the button. After that the program will directly go to my EventActivity. How can settle this problem?
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.getId() == insertButton.getId()) {
if(colorButton.getText().toString().equals("Color")){
colorAlert.show();
}
}
}
This is variable
AlertDialog colorAlert;
AlertDialog in the OnCreate()
AlertDialog.Builder CA = new AlertDialog.Builder(this);
CA.setTitle("Alert Message!");
CA.setMessage("Please insert the level of important for the event.");
CA.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
colorAlert.dismiss();
startActivity(new Intent(this, EventActivity.class));
}
});
colorAlert = CA.create();
When you compare a String in Java, use YOUR_STRING.equals("Color");
Update:
change your while into if , because your are running it once.
The move your
startActivity(new Intent(this, EventActivity.class));
in your alertbox positive button handler.
Comparing Strings in Java.
Ok look like you need more help, here is one solution... i let you deal with the EventActivity ;)
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class MainActivity extends Activity {
final Context context=this;
public static String EXTRA_MESSAGE;
Button colorButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_test);
colorButton = (Button) findViewById(R.id.button1);
colorButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(colorButton.getText().toString().equals("Color")){
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setMessage("myDialog").setCancelable(false).setPositiveButton("yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
Intent intent = new Intent(MainActivity.this, EventActivity.class);
String message = colorButton.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}).setNegativeButton("cancel", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog myAlert = alertBuilder.create();
myAlert.show();
}
}
});
}
Adding to wtsang02 answer, you shouldn't put your alert.show in a while like this one... I see coming the infinite loop ;)
Can someone explain to me why this AlertDialog crashes?
package com.clicker;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Clicker extends Activity
{
public int clickerNumber = 0;
private TextView clickerText;
private Button clickerButton;
private Button resetButton;
// Called when the activity is first created.
#SuppressWarnings("null")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Declare each of the layout objects
clickerText = (TextView)findViewById(R.id.clickerText);
clickerButton = (Button)findViewById(R.id.clickerButton);
resetButton = (Button)findViewById(R.id.resetButton);
clickerText.setText("0");
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
resetQuestion.setMessage("Are you sure you want to reset the counter?");
resetQuestion.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
clickerNumber = 0;
clickerText.setText("0");
}
});
resetQuestion.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
clickerButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
clickerNumber++;
clickerText.setText(Integer.toString(clickerNumber));
}
});
resetButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
resetQuestion.show();
}
});
};
};
This is a great fail:
final AlertDialog.Builder resetQuestion = null;
resetQuestion.setTitle("Reset?");
You are trying to use a null object, and that (of course) will throw a NullPointerException
This is how I create dialogs (and I think it's the best way to do it):
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.dialogo_layout, null);
final AlertDialog.Builder resetQuestion = new AlertDialog.Builder(YourActivity.this)
// do whatever you want with the resetQuestion AlertDialog
Here, R.layout.dialogo_layout represent a file called dialogo_layout.xml in the res/layout dir that contains the dialog layout.