Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I am trying to play a sound on button click but it is giving a null pointer exception. I looked at some answers on StackOverflow but nothing helped
package com.example.testproject;
import androidx.appcompat.app.AppCompatActivity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = findViewById(R.id.button);
final MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.dice_sound);
btn.setOnClickListener(v -> {
mp.start();
mp.release();
});
}
}
Error: As per the error showing in Logcat the variable mp is considered as null. I can't find out the fix for it.
The error is occurring because the sound .wav is not supported by the device that I am running on the test app. It is running on a different device that supports .wav file format. I have converted the file type to mp3 and now it is working on both devices.
Thanks to everyone for your reply...
Try this in your click listener
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setLooping(true);
try {
mediaPlayer.setDataSource(this, R.raw.dice_sound);
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.start(); // if app craches on this line commit it then check
} catch (Exception e) {
e.printStackTrace();
}
Make sure that you should stop the mediaplayer before exist from the activity. You can do this in the click of the stop button. if you dont want to add the stop button then in the activity life cycle you should override onDestory and stop the player in the onDestory function.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I just try to play some sounds in android studio by clicking on pictures (imageViews).
I gave each picture a tag in the xml file:
<ImageView
android:id="#+id/imageView3"
android:onClick="playPhrase"
android:layout_width="150dp"
android:layout_height="150dp"
android:tag="internet"
app:srcCompat="#drawable/rouven" />
In the main Activity i have this code but it keeps crashing:
public class MainActivity extends AppCompatActivity {
public void playPhrase(View view) {
Button buttonPressed = (Button) view;
Log.i("Button pressed", buttonPressed.getTag().toString());
MediaPlayer mediaPlayer = MediaPlayer.create(this,
getResources().getIdentifier(buttonPressed.getTag().toString(),
"raw", getPackageName()));
mediaPlayer.start();
}
}
Can't i call this method like that? How to solve that? Im a beginner :-)
Thanks for your help
Carlo
1 put a music file to the /res/raw , such as in.wav, in.mp3 media file (here name it as in)
2 change the code to:
public void playPhrase(View view) {
MediaPlayer mediaPlayer = MediaPlayer.create(this,
R.raw.in);
mediaPlayer.start();
}
This question already has answers here:
How to run an activity only once like Splash screen
(5 answers)
Closed 1 year ago.
I have a Android App built in Android studio, on this app, I am using a Walkthrough Activity.
How can set this activity in a way that when a button is clicked, this page won't show again.
This is the function "public void onFinishButtonPressed()" and this is the part where I added onlick listener to the button, how should it be done in a way that once this function is called, this activity will not open again.
I have tried to implement a code to show activity only on first time run, but it is still not the desired result, i really want this page to keep showing until using clicks on that button.
Thanks for your help in advance.
My code;
package com.frigate.vpn.view;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.frigate.vpn.R;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughActivity;
import com.shashank.sony.fancywalkthroughlib.FancyWalkthroughCard;
import java.util.ArrayList;
import java.util.List;
public class Walkthrough extends FancyWalkthroughActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FancyWalkthroughCard fancywalkthroughCard1 = new FancyWalkthroughCard("Welcome to Frigate Media VPN", "Let me show you why so many people love Frigate Media VPN", R.drawable.find_restaurant1);
FancyWalkthroughCard fancywalkthroughCard2 = new FancyWalkthroughCard("We Protect your Privacy", "Internet access is mind free, we'll keep you safe",R.drawable.pickthebest);
FancyWalkthroughCard fancywalkthroughCard3 = new FancyWalkthroughCard("Fast & Limitless!", "We provide you the fastest servers without limits.",R.drawable.chooseurmeal);
FancyWalkthroughCard fancywalkthroughCard4 = new FancyWalkthroughCard("Frigate Media VPN is 100% Free", "You do not have to worry about paying for expensive VPN, we give you everything for free.",R.drawable.mealisonway);
fancywalkthroughCard1.setBackgroundColor(R.color.white);
fancywalkthroughCard1.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard2.setBackgroundColor(R.color.white);
fancywalkthroughCard2.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard3.setBackgroundColor(R.color.white);
fancywalkthroughCard3.setIconLayoutParams(300,300,0,0,0,0);
fancywalkthroughCard4.setBackgroundColor(R.color.white);
fancywalkthroughCard4.setIconLayoutParams(300,300,0,0,0,0);
List<FancyWalkthroughCard> pages = new ArrayList<>();
pages.add(fancywalkthroughCard1);
pages.add(fancywalkthroughCard2);
pages.add(fancywalkthroughCard3);
pages.add(fancywalkthroughCard4);
for (FancyWalkthroughCard page : pages) {
page.setTitleColor(R.color.black);
page.setDescriptionColor(R.color.black);
}
setFinishButtonTitle("Get Started");
showNavigationControls(true);
setColorBackground(R.color.white);
//setImageBackground(R.drawable.restaurant);
setInactiveIndicatorColor(R.color.grey_600);
setActiveIndicatorColor(R.color.colorGreen);
setOnboardPages(pages);
}
#Override
public void onFinishButtonPressed() {
Intent intent = new Intent(Walkthrough.this, MainActivity.class);
startActivity(intent);
finish();
}
}
Why not just use a global boolean variable named "isFinishedButtonPressed" set to false by default and when the button is pressed set it to true, and with the correct conditions it should do what you want, no ?
This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 2 years ago.
I am a novice Android Developer.
I have created a package-private class which extends Application, and contains the required code for specific functions. I basically want to display if the user-selected button is the correct choice or not, via a toast. Since I have to call this code for many activities, I just created a package-private class for it. However, on clicking the button, the app crashes. Please see the code given below for reference.
I cannot change the onClick method to non-static because if I do that, Android Studio shows an error, and if I change it to static, I am unable to use the method getApplicationContext(), because it is not accessible inside static blocks.
I think that using view.getContext() is causing the crash.
Is there any workaround, or a solution?
Your help would be greatly appreciated. Thanks :)
Here is the code for your reference.
activity.java:
public class activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(functions.select);
functions.makeLayout(expression, buttons);
}
}
Here is the code which crashes the app.
functions.java:
class functions extends Application {
private static int idx;
public static View.OnClickListener select=new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_index=(int) view.getTag();
if(selected_index==idx)
{
Toast.makeText(view.getContext(), "Correct.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.GREEN);
}
else
{
Toast.makeText(view.getContext(), "Wrong.", Toast.LENGTH_LONG).show();
((Button) view).setTextColor(Color.RED);
}
}
};
Okay, I figured out that it was not view.getContext() but the line int selected_index=(int) view.getTag(); which was causing the crash. I solved it first making it into a string and then int by using the following code:
String selected_index=view.getTag.toString();
int sidx=Integer.parseInt(selected_index);
The first splashscreen hidden after 5 secondes.
I want to add a second splashscreen like the first before enter in MainActivity.
in #drawable/background_1 <= This is the first image splashscreen I added.
in #drawable/background_2 <= I need to add this image in second splashscreen.
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background_1" >
</RelativeLayout>
SplashScreen.java
package org.sbynight.app;
import android.app.Activity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;
public class SplashScreen extends Activity {
private static String TAG = SplashScreen.class.getName();
private static long SLEEP_TIME = 5; // Sleep for some time
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE); // Removes title bar
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Removes notification bar
setContentView(R.layout.splash);
// Start timer and launch main activity
IntentLauncher launcher = new IntentLauncher();
launcher.start();
}
private class IntentLauncher extends Thread {
#Override
/**
* Sleep for some time and than start new activity.
*/
public void run() {
try {
// Sleeping
Thread.sleep(SLEEP_TIME*1000);
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
// Start main activity
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(intent);
SplashScreen.this.finish();
}
}
}
Problem Solved - UPDATE OF POST -
1.I create a "SplashScreen2.java" + "Splash2.xml"
2.I added #drawable>background_2 (the second image of splashscreen)
3.I added to In Manifest splash2.....
In my SplashScreen.java, I deleted this code:
// Start main activity
Intent intent = new Intent(SplashScreen.this, MainActivity.class);
SplashScreen.this.startActivity(intent);
SplashScreen.this.finish();
In my SplashScreen.java, Replace by this code :
/**** Create Thread that will sleep for 5 seconds ****/
Thread background = new Thread() {
public void run() {
try {
// Thread will sleep for 1 seconds
sleep(1*1000);
// After 1 seconds redirect to another intent
Intent i=new Intent(getBaseContext(),SplashScreen2.class);
startActivity(i);
//Remove activity
finish();
} catch (Exception e) {
}
}
};
// start thread
background.start();
In my Splashscreen2.java, I added the same code like SplashScreen.java,
Surely with this code now to start the MainActivity.class
// Start main activity
Intent intent = new Intent(SplashScreen2.this, MainActivity.class);
SplashScreen2.this.startActivity(intent);
SplashScreen2.this.finish();
Problems Solved! I have now 2 SplashScreen!
This use-case goes against the Android design guidelines.
Please think about how your users would get a good user experience using your app and get access to your content fast.
Designing Help into Your App
Don't show unsolicited help, except in very limited cases
Naturally, you want everyone to quickly learn the ropes, discover the
cool features, and get the most out of your app. So you might be
tempted to present a one-time introductory slideshow, video, or splash
screen to all new users when they first open the app. Or you might be
drawn to the idea of displaying helpful text bubbles or dialogs when
users interact with certain features for the first time.
In almost all cases, we advise against approaches like these because:
They're interruptions. People will be eager to start using your app,
and anything you put in front of them will feel like an obstacle or
possibly an annoyance, despite your good intentions. And because they
didn't ask for it, they probably won't pay close attention to it.
They're usually not necessary. If you have usability concerns about an
aspect of your app, don't just throw help at the problem. Try to solve
it in the UI. Apply Android design patterns, styles, and building
blocks, and you'll go a long way in reducing the need to educate your
users.
Source: http://developer.android.com/design/patterns/help.html
I don't really understand why you would want to add a second "splash screen". If you really did want to do it, why not make the MainActivity your SplashScreenActivity and then move onto a new activity from there.
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 8 years ago.
Improve this question
So I've been learning and trying to build upon an app I made by following an online tutorial. It is a simple, bare bones, note taking application. The mainActivity simply shows note objects in a list view. The second screen/activity is the one I'm currently working on, trying to add code where I can. So far I've added a save button that will simply save the text/string value and take the user back to the main activity. I would like some feedback as to my implementation of the onButtonSave method:
public class NoteEditorActivity extends Activity {
private NoteItem note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = this.getIntent();
note = new NoteItem();
note.setKey(intent.getStringExtra("key"));
note.setText(intent.getStringExtra("text"));
EditText et = (EditText) findViewById(R.id.noteText);
et.setText(note.getText());
et.setSelection(note.getText().length());
// I'm wondering if this is the correct way to call my onButtonSave method
onButtonSave();
}
private void saveAndFinish() {
EditText et = (EditText) findViewById(R.id.noteText);
String noteText = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("key", note.getKey());
intent.putExtra("text", noteText);
setResult(RESULT_OK, intent);
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override
public void onBackPressed() {
saveAndFinish();
}
// This is the code I've added for the save button.
public void onButtonSave(){
final Button button = (Button) findViewById(R.id.saveButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
button.setText("Saved!");
saveAndFinish(); }
});
}
}
I assume you are curious as to whether or not you have covered all your cases. Breaking up the setup of listeners and UI components from your onCreate into separate methods can be a good practice for easier readability when there are a lot of things being initialized.
You cover the case when the back button is used.
You cover the case when the user presses the button.
From what can be seen you also cover the case with the menu selection of leaving the screen. A couple people have talked best about how to detect whether the screen goes to the background or not. If you really want to catch all cases, you can do your save within the onPause() of an Activity. This will be fired if you press back, go home or call another activity.
Distinguishing between another activity and the home button is tough. But some people have pointed towards onUserHint() as a way to detect this. Just thought I would provide some feedback to what I can understand of your question.