I'm trying to run a simple test app to stream music from an online shoutcast radio but I'm always getting an error about MediaPlayer setDataSource() method.. This is the log:
08-26 11:33:42.268 17698-17698/com.example.bruno.radioteste D/MainActivity﹕ Attempt to play http://50.7.98.106:8398
08-26 11:33:42.268 17698-17698/com.example.bruno.radioteste E/MediaPlayer﹕ Unable to create media player
08-26 11:33:42.268 17698-17698/com.example.bruno.radioteste W/System.err﹕ java.io.IOException: setDataSource failed.: status=0x80000000
08-26 11:33:42.278 17698-17698/com.example.bruno.radioteste W/System.err﹕ at android.media.MediaPlayer._setDataSource(Native Method)
The code is very simple, and from what I've been searching it should work just fine.. The layout's xml:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="BassDrive-http://50.7.98.106:8398"
android:onClick="play" />
And the activity class:
public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener {
private static final String TAG = MainActivity.class.getSimpleName();
private MediaPlayer player;
private boolean isPlaying = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
player = new MediaPlayer();
player.setOnPreparedListener(this);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
public void play(View view) {
if(isPlaying) {
player.stop();
isPlaying = false;
} else {
try {
String stationIp = ((Button)view).getText().toString().split("-")[1];
Log.d(TAG, "Attempt to play " + stationIp);
player.setDataSource(stationIp);
player.prepareAsync();
isPlaying = true;
} catch(Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Trying to start...");
mp.start();
}
#Override
protected void onStop() {
super.onStop();
// clear media player
player.stop();
player.release();
player = null;
}
There are two possible cases,
Have you added this permission in your manifest?
<uses-permission android:name="android.permission.INTERNET" />
If yes, then android is not able to decode your stream. To test this you can try some other stream. For example, try a spotify 30-second preview stream http://d318706lgtcm8e.cloudfront.net/mp3-preview/d9d8686acc79916d2db76abdaa2c18a594fed332
Related
I'm trying to implement an interstitial Ad activity insite my application whic is called every time that the user opens the settings.
The prblem is that even if the Ad unit ID is correct and the ad loading code is the same as google shows in their documentation the interstital ad doesn't load and always returns null.
I Also thought that maybe the app didn't have enough time to load the ad and then show it between the transaction from MainActivity to SettingsActivity, so i tried to start the IntersttitalAd with a PostDelayed runnable handler, but didn't work either.
Can anyone tell me why?
This is the InterstitialAdActivity:
public class InterstitialadActivity extends Activity {
private final String TAG = "Interstitialad debug";
private ProgressDialog progress;
private InterstitialAd mInterstitialAd;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progress = new ProgressDialog(this);
progress.setTitle("Loading Ad");
progress.setMessage("Wait while loading Interstitial Ad...");
progress.setCancelable(false); // disable dismiss by tapping outside of the dialog
progress.show();
AdRequest adRequest = new AdRequest.Builder().build();
InterstitialAd.load(
this,
AD_UNIT,
adRequest,
new InterstitialAdLoadCallback() {
#Override
public void onAdLoaded(#NonNull InterstitialAd interstitialAd) {
// The mInterstitialAd reference will be null until
// an ad is loaded.
mInterstitialAd = interstitialAd;
Log.i(TAG, "onAdLoaded");
interstitialAd.setFullScreenContentCallback(
new FullScreenContentCallback() {
#Override
public void onAdDismissedFullScreenContent() {
// Called when fullscreen content is dismissed.
// Make sure to set your reference to null so you don't
// show it a second time.
Log.d(TAG, "The ad was dismissed.");
progress.dismiss();
finish();
}
#Override
public void onAdFailedToShowFullScreenContent(AdError adError) {
// Called when fullscreen content failed to show.
// Make sure to set your reference to null so you don't
// show it a second time.
Log.d(TAG, "The ad failed to show.");
progress.dismiss();
finish();
}
#Override
public void onAdShowedFullScreenContent() {
// Called when fullscreen content is shown.
Log.d(TAG, "The ad was shown.");
}
});
}
#Override
public void onAdFailedToLoad(#NonNull LoadAdError loadAdError) {
// Handle the error
String error =
String.format(
"domain: %s, code: %d, message: %s",
loadAdError.getDomain(), loadAdError.getCode(), loadAdError.getMessage());
Log.d(TAG,"onAdFailedToLoad() with error: " + error);
mInterstitialAd = null;
}
});
// Show the ad if it's ready. Otherwise toast and restart the game.
if (mInterstitialAd != null) {
mInterstitialAd.show(this);
Log.d(TAG,"ad was shown");
} else {
Log.d(TAG,"ad was null");
progress.dismiss();
finish();
}
}
And this is how i call it the SettingsActivity:
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
...
if(!MainActivity.isPro) {
Intent myIntent = new Intent(SettingsActivity.this, InterstitialadActivity.class);
startActivity(myIntent);
}
}
I'm trying to show ad When user presses on sound card 10 times but when I press on sound card 10th time no ad is shown and no sound plays anymore until I press stop button after which sound plays again until I press it 10 times again
Part of my main activity:
..
MobileAds.initialize(this,
"ca-app-pub-2470537820941001~1050614569");
mInterstitialAd = new InterstitialAd(this);
mInterstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
mInterstitialAd.loadAd(new AdRequest.Builder().build());
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mPowerSaverChangeReceiver);
if (mSoundPlayer != null) {
mSoundPlayer.release();
mSoundPlayer = null;
}
}
#Override
public void onResume() {
super.onResume();
if (mSoundPlayer == null) mSoundPlayer = new SoundPlayer(MainActivity.this);
}
#Override
public void onPause() {
super.onPause();
if (mSoundPlayer != null) {
mSoundPlayer.release();
mSoundPlayer = null;
}
}
this is my sound player class:
class SoundPlayer {
private MediaPlayer mPlayer;
private Context mContext;
private static final String TAG = "SoundPlayer";
private int counter = 0;
private void playSound(Sound sound) {
int resource = sound.getResourceId();
if (counter == 5) {
if (mInterstitialAd.isLoaded()) {
mInterstitialAd.show();
} else {
Log.d("TAG", "The interstitial wasn't loaded yet.");
}
} else {
counter++;
}
if (mPlayer != null) {
if (mPlayer.isPlaying())
mPlayer.stop();
mPlayer.reset();
../
The error
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean com.google.android.gms.ads.InterstitialAd.isLoaded()' on a null object reference
at my.app.SoundPlayer.playSound(SoundPlayer.java:38)
at my.app.reactionsounds.SoundPlayer.onEvent(SoundPlayer.java:32)
at java.lang.reflect.Method.invoke(Native Method)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:507)
at org.greenrobot.eventbus.EventBus.invokeSubscriber(EventBus.java:501)
at org.greenrobot.eventbus.AsyncPoster.run(AsyncPoster.java:46)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
You have not initialised interstiial Ad in your sound player class.Your error shows clearly that Interstitial ad is null.
interstitialAd = new InterstitialAd(ReadingPage.this);
interstitialAd.setAdUnitId(getResources().getString(R.string.interstitial1));
interstitialAd.loadAd(new AdRequest.Builder().build());
im trying to make a splash screen, the codes showing no errors, build succesfully, but when it started,it shows this message at the apps
and when i check the log on android monitor, it show these messages
08-07 05:41:23.709 16344-16344/com.android.andika.soundsmart E/WindowManager: android.view.WindowLeaked: Activity com.android.andika.soundsmart.SplashS has leaked window DecorView#e044f4c[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at android.app.Activity.performStart(Activity.java:6723)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2662)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
this is the code from my splashscreen class
public class SplashS extends AppCompatActivity {
ProgressBar progressBar;
int status = 0;
int proses = 0;
Handler handle = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_s);
getSupportActionBar().setTitle("SPLASHSREEN");
ActionBar ab = getSupportActionBar();
ab.hide();
progressBar = (ProgressBar) findViewById(R.id.tunggu);
new Thread(new Runnable() {
#Override
public void run() {
while(status<100){
status = loading();
handle.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(status);
}
});
}
handle.post(new Runnable() {
#Override
public void run() {
Intent pindah = new Intent(SplashS.this,MenuS.class);
startActivity(pindah);
finish();
}
});
}
private int loading() {
try{
Thread.sleep(45);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
return ++proses;
}
}).start();
}
}
i debug the app via an android phone with android N 7.1 OS.
i'll appreciate any answer, advice, or response. thanks :)
i think that error related to showing dialog where the activity is dismissed , but your code does not showing any dialogs so check if you are using 3rd party libraries which can do that
I'm using two activities, the main one, and the camera one. In the mainActivity i call startActivity(new Intent(this, CameraActivity));
Now, when camera activity starts, the onCreate() is:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera_preview);
View myView= (View) findViewById(R.id.camera_previeww);
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
cameraID= Camera.CameraInfo.CAMERA_FACING_FRONT;
mCamera=openCamera(cameraID);
mCamera.startPreview();
IntentFilter filter = new IntentFilter();
filter.addAction(Tabbed.BROADCAST_ACTION_TABBED);
LocalBroadcastManager bm = LocalBroadcastManager.getInstance(this);
bm.registerReceiver(mBroadcastReceiver, filter);
// Create our Preview view and set it as the content of our activity.
mPreview = new CameraPreview(this, mCamera);
FrameLayout preview = (FrameLayout) this.findViewById(R.id.camera_previeww);
preview.addView(mPreview);
}
The openCamera(int cameraID) method is:
public Camera openCamera(int cameraIDD){
Camera c=null;
try{
c=Camera.open(cameraIDD);
}catch (Exception e){
Log.d("Camera Activity", e.getMessage());
}
return c;
}
Also I'm using a BroadcastReceiver like:
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
}
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
// kill activity
}
};
And some other methods:
#Override
protected void onPause() {
super.onPause();
//releaseCamera(); // release the camera immediately on pause event
}
private void releaseCamera(){
if (mCamera != null){
mCamera.release(); // release the camera for other applications
mCamera = null;
}
}
void kill_activity()
{
mCamera.stopPreview();
mCamera.setPreviewCallback(null);
releaseCamera();
finish();
}
Here is the crash:
FATAL EXCEPTION: main
Process: com.etu.goglove, PID: 6008
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.hardware.Camera.takePicture(android.hardware.Camera$ShutterCallback, android.hardware.Camera$PictureCallback, android.hardware.Camera$PictureCallback)' on a null object reference
at com.etu.goglove.CameraActivity$2.onReceive(CameraActivity.java:155)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6119)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
With all this, I'm trying to take a photo when I receive broadcast intents. So, after my activity has started, I open mCamera and when I receive an intent I make the photo or I get back. At the first time, i can take the photo and then I finish my activity. If i try to restart cameraActivity from the mainActivity, calling startActivity(intent),in the onCreate() camera is open and it is not null (checked with the debugger), but this time, when I get in the onReceive() method, mCamera is always null, so I get a null object reference on mCamera!(when I'm trying to do mCamera.takePicture()) don't know how ...
Thanks!
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
byte [] data=new byte[3];
if (intent!=null && intent.getAction().equals(Tabbed.BROADCAST_ACTION_TABBED)) {
data = intent.getByteArrayExtra(Tabbed.EXTRA_PARAM_BYTE);
if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==SINGLE_TAP){
//switchCamera();
//releaseCamera();
//mCamera=Camera.open();
}
else if (data[FINGER]==MIDDLE_FINGER && data[TYPE]==DOUBLE_TAP){
// HAVE TO GO BACK
kill_activity();
}
else if (data[FINGER]==INDEX_FINGER && data[TYPE]==SINGLE_TAP){
mCamera.takePicture(null, null, mPicture);
}
}
// kill activity
}
};
could anyone help my with my app code. I tryied to make an application that could send data (number or letter) to arduino through bluetooth. This is how my JAVA code look:
package com.example.btprojektas;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends Activity{
private static final String TAG = "btprojektas";
Button btnON, btnOFF;
BluetoothAdapter bluetoothAdapter = null;
BluetoothDevice device = null;
OutputStream outputStream = null;
BluetoothSocket socket = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
btnON = (Button) findViewById(R.id.btnON);
btnOFF = (Button) findViewById(R.id.btnOFF);
if(!bluetoothAdapter.isEnabled()){
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 0);
}
loadPairedDevice();
connectBT();
btnON.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
btnOFF.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
}
private void connectBT() {
if (device != null) {
UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb"); //Standard SerialPortService ID
try {
socket = device.createRfcommSocketToServiceRecord(uuid);
socket.connect();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void disconnect() {
try {
if (outputStream != null) outputStream.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadPairedDevice() {
Set<BluetoothDevice> pairedDevices = bluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
Log.d(TAG, "Device found");
for (BluetoothDevice device : pairedDevices)
if (device.getName().equals("HC-06")) {
this.device = device;
break;
}
}
}
#Override
protected void onPause() {
super.onPause();
disconnect();
}
#Override
protected void onResume() {
super.onResume();
loadPairedDevice();
connectBT();
}
private void sendData(String message) {
byte[] buffer = message.getBytes();
Log.d(TAG,"Send data:"+ message);
try{
outputStream.write (buffer);
} catch (IOException e) {}
}
}
in XML I have two buttons. When the program starts I push one of those buttons and the "Applications ... stopped unexpectedly" appears with fatal exeption fault code:
01-08 15:55:15.439 15354-15354/com.example.btprojektas E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.btprojektas.MainActivity.sendData(MainActivity.java:122)
at com.example.btprojektas.MainActivity.access$000(MainActivity.java:22)
at com.example.btprojektas.MainActivity$1.onClick(MainActivity.java:55)
at android.view.View.performClick(View.java:2485)
at android.view.View$PerformClick.run(View.java:9080)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
P.S. Sorry for this question I know that it is quite common but I am new at programming especially JAVA.
It's either the socket or the outputStream. In ConnectBT, you don't check if socket is not null. You directly call socket.connect() assuming socket is valid. The same applies to outputStream. You use it before making sure it's not null.
Also you call
startActivityForResult(enableBluetooth, 0);
but you don't check for the result which is whether bluetooth got enabled or not. This makes your device also suspicious.
Calling
loadPairedDevice();
connectBT();
makes sense only when bluetooth is enabled. Enabling bluetooth can take couple of seconds, but you call them right away.
A couple of tips:
you're calling loadPairedDevice() and connectBT() twice: in onCreate() and in onResume() - do it only once
before using outputStream, check if it's not null (as advised by others)
in sendData(), catch AND print your exception:
try {
if (outputStream != null) {
outputStream.write(buffer);
}
else {
Log.d("TAG", "sendData() - outputStream is null!");
}
}
catch (IOException e) {
e.printStackTrace();
}
in loadPairedDevice(), if you don't find the device "HC-06", your variable device will be null...
enabling bluetooth takes few seconds, so register and listen to ACTION_STATE_CHANGED broadcast Intent. It will contain extra field EXTRA_STATE; look for STATE_ON, and then call your loadPairedDevices() and connectBT() there:
create receiver (inside your MainActivity class):
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
//this is the action you are observing
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.ERROR);
switch(state) {
//and the state we were looking for
//which means that bluetooth has switched on
//so now you can call your functions
//and set the flag to true, which then use in your
//onClick listeners
case BluetoothAdapter.STATE_ON:
loadPairedDevice();
connectBT();
isBluetoothOn = true;
break;
}
}
}
}
in onCreate(), create IntentFilter and register receiver with it
IntentFilter btFilter = new IntentFilter();
btFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btFilter);
remember to unregister receiver in onPause():
unregisterReceiver(mReceiver);
disable your buttons and enable them in the above listener, when you know BT is switched on; alternatively, keep a flag and use it in your click listeners, eg.:
boolean isBluetoothOn = false;
then later in listener when you get STATE_ON
isBluetooth = true;
And in your button click listener:
//for btnON
public void onClick(View v) {
if (isBluetoothOn) {
sendData("0");
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
}
Do the same for btnOFF.