easiest way to play mp3 from storage - java

I'm a newbie. I just want to play mp3 in my app.
I've read the documentation and I browsed through many websites including this one.
The steps should be
MediaPlayer.setDataSource(String) or (context, Uri)
.prepare();
.start();
My file is in /storage/emulated/0/New Folder/ztz3.mp3 ..
if i use External.getExternalDirectory().getPath() the result is /storage/emulated/0/
but it just won't play.
I've browsed many sites.. trying many things but it just didn't work.
I've used permission to read external storage.
and the sites I'm browsing has too many different answers which only confused me more.
some use AudioManager.STREAM.. some use MediaPlayer.create.
and I followed that too.. but it just won't play.
public class MainActivity extends AppCompatActivity {
Button buttonPlay;
MediaPlayer mediaPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonPlay = (Button) findViewById(R.id.buttonPlay);
// String filePath = Environment.getExternalStorageDirectory()+
// "/New Folder/ztz_3_adding.mp3";
// String filePath = "/storage/emulated/0/New Folder/ztz_3_adding.mp3";
Log.e("Dir", Environment.getExternalStorageDirectory().toString());
Log.e("Directory", Environment.getExternalStorageDirectory().getPath());
mediaPlayer = new MediaPlayer();
//mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
// mediaPlayer.setDataSource("/storage/emulated/0/New Folder/ztz_3_adding.mp3");
// mediaPlayer.setDataSource("file://storage/emulated/0/New Folder/ztz_3_adding.mp3");
mediaPlayer.setDataSource(getApplicationContext(),
Uri.parse(Environment.getExternalStorageDirectory().getPath()+
"/New Folder/ztz_3_adding.mp3"));
} catch (IOException e) {
e.printStackTrace();
}
try {
mediaPlayer.prepare();
//mediaPlayer.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
buttonPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.start();
}
});
}
}
I think the problem is in the prepare() method.. but I don't know how to fix it.
I've read and tried a site that said to use static MediaPlayer.create or something.
I just want a simple media player that use a string value that I can change anytime to play mp3 files based on the layout.
thanks for the help before...
the log...
02-25 22:10:08.546 17345-17345/com.echo.tesmediaplayer E/Dir:
/storage/emulated/0 02-25 22:10:08.548
17345-17345/com.echo.tesmediaplayer E/Directory: /storage/emulated/0
02-25 22:10:08.563 17345-17345/? E/MediaPlayer: prepareAsync called in
state 1 02-25 22:10:08.564 17345-17345/? E/AndroidRuntime: FATAL
EXCEPTION: main
Process: com.echo.tesmediaplayer, PID: 17345
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.echo.tesmediaplayer/com.echo.tesmediaplayer.MainActivity}:java.lang.IllegalStateException
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2440)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)at
android.app.ActivityThread.access$900(ActivityThread.java:163)at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)at
android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)
Caused by: java.lang.IllegalStateExceptionat
android.media.MediaPlayer._prepare(Native Method) at
android.media.MediaPlayer.prepare(MediaPlayer.java:1158) at
com.echo.tesmediaplayer.MainActivity.onCreate(MainActivity.java:48)
at android.app.Activity.performCreate(Activity.java:6279) at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2393)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2500)
at android.app.ActivityThread.access$900(ActivityThread.java:163) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1362)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:148) at
android.app.ActivityThread.main(ActivityThread.java:5585) at
java.lang.reflect.Method.invoke(Native Method) at
.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:730)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:620)

Do you have the permissions set correctly?
You need:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
See: https://developer.android.com/guide/topics/media/mediaplayer.html#manifest

Related

Error when trying to play mp3 in Android java app with Media Player

I'm trying to play an mp3 file which is stored in my res/raw folder properly. But it seems quite difficult to reach this aim. I have a button inside a destination defined in an navigation schema. Its name is : English. Inside its code we can find this listener attached to the only button in its view....
//Button related to play btn
view.findViewById(R.id.btn_audio).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AssetFileDescriptor afd = getActivity().getResources().openRawResourceFd(R.raw.a01);
try {
player.setDataSource(afd.getFileDescriptor());
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
When the button is pressed, the error is:
E/MediaPlayer: error (1, -2147483648)
W/System.err: java.io.IOException: Prepare failed.: status=0x1
at android.media.MediaPlayer._prepare(Native Method)
at android.media.MediaPlayer.prepare(MediaPlayer.java:1163)
at com.example.myapplication.Ingles$3.onClick(Ingles.java:74)
W/System.err: at android.view.View.performClick(View.java:5198)
at android.view.View$PerformClick.run(View.java:21147)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
And I have no idea why and what to do now to solve this...Any clue?
Try Closing the File Descriptor
MediaPlayer.Prepare() will throw an IOException when using an AFD only if the AFD provided cannot be read (see MediaPlayer.setDataSource()). The developer is totally responsible for closing the file descriptor created, and not closing it can cause conflicts upon compilation. You can do that directly after MediaPlayer.setDataSource() is called.
Sets the data source (AssetFileDescriptor) to use. It is the caller's responsibility to close the file descriptor. It is safe to do so as soon as this call returns. (see AssetFileDescriptor.close())
view.findViewById(R.id.btn_audio).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AssetFileDescriptor afd = getActivity().getResources().openRawResourceFd(R.raw.a01);
try {
player.setDataSource(afd.getFileDescriptor());
afd.close();
player.prepare();
player.start();
} catch (IOException e) {
e.printStackTrace();
}
}
});
If the problem persists, this might mean that your file is corrupt or not the correct format. The more probable answer is that you haven't correctly retrieved your RAW file.

splash screen is not working in android 6

I have added splash screen in my app but the app crashes when is run on Android 6. The interesting thing is that the app runs fine on Android 9.
Don't know what to do.
Target SDK - 28.
min SDK= 19
it is showing error on oncreate method while run app on android 6
splash.java
import android.os.Bundle;
import android.os.Handler;
public class splash extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // it showing error here.
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 4000;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent splashintent=new Intent(splash.this,MainActivity.class);
startActivity(splashintent);
finish();
}
}, SPLASH_TIME_OUT);
}
}
logs
06-22 16:17:30.930 10294-10294/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.napps.wallpaper, PID: 10294
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.napps.wallpaper/com.napps.wallpaper.splash}: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5896)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f07009e
at android.content.res.Resources.getValue(Resources.java:1595)
at androidx.appcompat.widget.AppCompatDrawableManager.loadDrawableFromDelegates(AppCompatDrawableManager.java:331)
at androidx.appcompat.widget.AppCompatDrawableManager.getDrawable(AppCompatDrawableManager.java:198)
at androidx.appcompat.widget.TintTypedArray.getDrawableIfKnown(TintTypedArray.java:86)
at androidx.appcompat.app.AppCompatDelegateImpl.<init>(AppCompatDelegateImpl.java:260)
at androidx.appcompat.app.AppCompatDelegate.create(AppCompatDelegate.java:182)
at androidx.appcompat.app.AppCompatActivity.getDelegate(AppCompatActivity.java:520)
at androidx.appcompat.app.AppCompatActivity.onCreate(AppCompatActivity.java:71)
at com.napps.wallpaper.splash.onCreate(splash.java:13)
at android.app.Activity.performCreate(Activity.java:6298)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2608)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2725) 
at android.app.ActivityThread.-wrap12(ActivityThread.java) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1572) 
at android.os.Handler.dispatchMessage(Handler.java:111) 
at android.os.Looper.loop(Looper.java:207) 
at android.app.ActivityThread.main(ActivityThread.java:5896) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679) 
There might be problem with your drawable Image. While copying image Please check the folder in which you are copying.
Try to add the image in drawable folder not drawable-21
I would suggest to remove old image and Add Image again to proper directory.

Android recieving classcastexception despite being in correct class

I have an activity with a viewpager containing 2 fragments, inside each fragment contains a list, from this list a button can be pressed that creates a new fragment in the viewpager, this works fine until I create a new activity and close it, after the new activity is closed and I return to the previous activity pressing the button to create a new fragment again now gives a classcastexception, almost as if the closed activity is still open, but it is not, I have tried searching this issue and cant find any examples of this being encountered by anyone else which makes me wonder how this could be happening, I will post some code examples below, any help will go a long way thanks.
Click listener in ListAdapter:
holder.rlStatusContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add new comment fragment and set page
try {
((HomeFragmentActivity) activity).addCommentFragment(data.get(finalPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Method in activity:
public void addCommentFragment(ArrayList<Object> fragmentExtras) {
list.add(NavigationFragment.newInstance(9, getApplicationContext(), this, fragmentExtras));
adapter.notifyDataSetChanged();
pager.setCurrentItem(list.size());
}
Error received:
12-13 13:37:50.177 17262-17262/test.test.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.test.com.test, PID: 17262
java.lang.ClassCastException: test.test.com.test.activities.NewPostActivity cannot be cast to test.test.com.test.activities.HomeFragmentActivity
at test.test.com.test.adapters.ListHomeAdapter$4.onClick(ListHomeAdapter.java:462)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

IllegalArgumentException In An AsyncTask On Rotate

I have successfully sent an email in the background and displayed a progress dialog to the user as said email is sent. However when the user flips the screen while the dialog is up I get an IllegalArgumentException. I have tried using a WeakReference object and it doesn't seem to be fixing the problem. This is my AsyncTask class.
private class SendMailTask extends AsyncTask<Mail, String, EmailStatusResponce> {
private final WeakReference<ProgressDialog> weakReference;
public SendMailTask() {
ProgressDialog progressDialog = new ProgressDialog(SendReportActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.setCancelable(false);
progressDialog.show();
weakReference = new WeakReference<>(progressDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected EmailStatusResponce doInBackground(Mail... mail) {
return mail[0].send();
}
#Override
protected void onPostExecute(EmailStatusResponce result) {
super.onPostExecute(result);
if (result != null && weakReference != null) {
weakReference.get().dismiss(); // This is where the exception is thrown.
if (result.isSuccess()) {
Intent intent = new Intent(SendReportActivity.this, MainActivity.class);
startActivity(intent);
}
else {}
}
}
This is the exception
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{688d3e2 V.E...... R......D 0,0-1026,348} not attached to window manager
Thanks in advance for any and all help.
EDIT: More logcat
--------- beginning of crash
12-11 16:22:40.154 1976-1976/com.blazapps.allenfamilymedicine E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blazapps.allenfamilymedicine, PID: 1976
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f89e667 V.E...... R......D 0,0-760,232} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:362)
at android.app.Dialog.dismiss(Dialog.java:345)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:168)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:138)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
I still do no know why the exception is being thrown but because I save lots of information in EmailStatusResponse I can just surround the exception with a try catch and if the task was complete I get the result I expected.
try {
weakReference.get().dismiss();
} catch (Exception e) {}
If anyone can figure a better solution I would really appreciate it. I hate just catching exceptions. There is usually a better way.

Activity getting destroyed when starting another activity for file viewing

I'm performing file viewing operation as follows:
private void openFile(File file, String format) {
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = "*/*";
if (format.length() > 0) {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(format);
if (mimeType == null)
mimeType = "*/*";
} else
mimeType = "*/*";
intent.setDataAndType(path, mimeType);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_NoCompatibleApp, Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
} else {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_DocNotFound, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is working fine, as I get app chooser pop-up for the filetypes which has multiple apps related to it(for eg. kingsoft office and polaris office for word file) OR directly file is opened for the filetypes which has only one app related to it(HTMLViewer for html file).
What I don't understand is my main activity is getting destroyed in few moments after calling file viewer activity. I've checked this by placing logs in onPause(), onStop() and onDestroy(). So, after file viewing is done, when I press back key, instead of taking back to app, it navigated to main menu.
I tried with startActivityForResult(intent, 1); instead of startActivity(intent); hoping that it'll preserve my main activity as it'll be waiting for result, but to no avail.
Please note that I've added android:configChanges="orientation|screenSize" in manifest file and
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
in java file.
Am I doing anything wrong?
Any help appreciated.
Sometimes, mind you, "Sometimes", I get follwing messages on log:
file:// Uri exposed through Intent.getData()
java.lang.Throwable: file:// Uri exposed through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
at android.net.Uri.checkFileUriExposed(Uri.java:2338)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.startActivityForResult(Activity.java:3423)
at android.app.Activity.startActivityForResult(Activity.java:3384)
at android.app.Activity.startActivity(Activity.java:3626)
at android.app.Activity.startActivity(Activity.java:3594)
at com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
at com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
at com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3809)
at android.view.View.performClick(View.java:4424)
at android.view.View$PerformClick.run(View.java:18383)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Add these lines to your Intent and try to Start Activity,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(Your_MimeType);
I m using this code in my App
String MimeType = URLConnection.guessContentTypeFromName(myFile.getAbsolutePath());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MimeType);
Uri uri_path = Uri.fromFile(myFile);
intent.setDataAndType(uri_path, MimeType);
try
{
_context.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(_context,"Activity Not Found..", Toast.LENGTH_SHORT).show();
}
Refer this link also for better understanding
Hope it will help you.
Activity can get destroyed any time. If someone has some data to retain one can do as follows:
class MyActivity {
private String mMyString;
public void onSaveInstanceState(Bundle b) {
b.putString("MYDATA", mMyString);
super.onSaveInstanceState(b);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState)
if(savedState != null) {
mMyString = savedState.getString("MYDATA");
}
}
You can this way create your own subclass private static class State implements Serializable and save it in onSaveInstanceState()

Categories

Resources