Bluetooth Messenger application crashing at start up itself - java

I have tried to learn to write an application which is basically a bluetooth messenger. Things had been fine unless I tried to install and run it. It gets installed successfully but crashes down at start up itself. Can you please tell me what is wrong ?
This is the code for the main activity. There are three more activities apart from this.
import java.io.IOException;
import java.util.ArrayList;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends ListActivity {
public final static String UUID = "3606f360-e4df-11e0-9572-0800200c9a66";
BluetoothAdapter bluetoothAdapter;
BroadcastReceiver discoverDevicesReceiver;
BroadcastReceiver discoveryFinishedReceiver;
//---store all the discovered devices---
ArrayList<BluetoothDevice> discoveredDevices;
ArrayList<String> discoveredDevicesNames;
//---store all the paired devices---
ArrayList<BluetoothDevice> pairedDevices;
static TextView txtData;
EditText txtMessage;
//---thread for running the server socket---
ServerThread serverThread;
//---thread for connecting to the client socket---
ConnectToServerThread connectToServerThread;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//---init the ArrayList objects and bluetooth adapter---
discoveredDevices = new ArrayList<BluetoothDevice>();
discoveredDevicesNames = new ArrayList<String>();
pairedDevices = new ArrayList<BluetoothDevice>();
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
//---for displaying the messages received---
txtData = (TextView) findViewById(R.id.txtData);
txtMessage = (EditText) findViewById(R.id.txtMessage);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
//---make yourself discoverable---
public void MakeDiscoverable(View view)
{
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(
BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(i);
}
/*
//---find all the previously paired devices---
private void QueryPairedDevices(){
Set<BluetoothDevice> allPairedDevices =
bluetoothAdapter.getBondedDevices();
//---if there are paired devices---
if (allPairedDevices.size() > 0) {
//---loop through paired devices---
for (BluetoothDevice device : allPairedDevices) {
//---add the name and address to an array adapter
// to show in a ListView---
Log.d("UsingBluetooth", device.getName() + "\n" +
device.getAddress());
pairedDevices.add(device);
}
}
}
*/
//---used to discover other bluetooth devices---
private void DiscoveringDevices() {
if (discoverDevicesReceiver == null) {
discoverDevicesReceiver = new BroadcastReceiver() {
//---fired when a new device is discovered---
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//---a device is discovered---
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
//---get the BluetoothDevice object from
// the Intent---
BluetoothDevice device =
intent.getParcelableExtra(
BluetoothDevice.EXTRA_DEVICE);
//---add the name and address to an array
// adapter to show in a ListView---
//---only add if the device is not already
// in the list---
if (!discoveredDevices.contains(device)) {
//---add the device---
discoveredDevices.add(device);
//---add the name of the device; used for
// ListView---
discoveredDevicesNames.add(device.getName());
//---display the items in the ListView---
setListAdapter(new
ArrayAdapter<String>(getBaseContext(),
android.R.layout.simple_list_item_1,
discoveredDevicesNames));
}
}
}
};
}
if (discoveryFinishedReceiver==null) {
discoveryFinishedReceiver = new BroadcastReceiver() {
//---fired when the discovery is done---
#Override
public void onReceive(Context context, Intent intent) {
//---enable the listview when discovery is over; about 12 seconds---
getListView().setEnabled(true);
Toast.makeText(getBaseContext(),
"Discovery completed. Select a device to start chatting.",
Toast.LENGTH_LONG).show();
unregisterReceiver(discoveryFinishedReceiver);
}
};
}
//---register the broadcast receivers---
IntentFilter filter1 = new
IntentFilter(BluetoothDevice.ACTION_FOUND);
IntentFilter filter2 = new
IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(discoverDevicesReceiver, filter1);
registerReceiver(discoveryFinishedReceiver, filter2);
//---disable the listview when discover is in progress---
getListView().setEnabled(false);
Toast.makeText(getBaseContext(),
"Discovery in progress...please wait...",
Toast.LENGTH_LONG).show();
bluetoothAdapter.startDiscovery();
}
//---discover other bluetooth devices---
public void DiscoverDevices(View view)
{
//---query for all paired devices---
//QueryPairedDevices();
//---discover other devices---
DiscoveringDevices();
}
#Override
public void onPause() {
super.onPause();
//---cancel discovery of other bluetooth devices
bluetoothAdapter.cancelDiscovery();
//---unregister the broadcast receiver for
// discovering devices---
if (discoverDevicesReceiver != null) {
try {
unregisterReceiver(discoverDevicesReceiver);
} catch(Exception e) {
}
}
//---if you are currently connected to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---stop the thread running---
if (serverThread!=null) serverThread.cancel();
}
//---used for updating the UI on the main activity---
static Handler UIupdater = new Handler() {
#Override
public void handleMessage(Message msg) {
int numOfBytesReceived = msg.arg1;
byte[] buffer = (byte[]) msg.obj;
//---convert the entire byte array to string---
String strReceived = new String(buffer);
//---extract only the actual string received---
strReceived = strReceived.substring(
0, numOfBytesReceived);
//---display the text received on the TextView---
txtData.setText(txtData.getText().toString() +
strReceived);
}
};
#Override
public void onResume() {
super.onResume();
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
//---when a client is tapped in the ListView---
public void onListItemClick(ListView parent, View v,
int position, long id) {
//---if you are already talking to someone...---
if (connectToServerThread!=null) {
try {
//---close the connection first---
connectToServerThread.bluetoothSocket.close();
} catch (IOException e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
}
//---connect to the selected Bluetooth device---
BluetoothDevice deviceSelected =
discoveredDevices.get(position);
connectToServerThread = new
ConnectToServerThread(deviceSelected, bluetoothAdapter);
connectToServerThread.start();
//---tell the user that he is connected to who---
Toast.makeText(this, "You have connected to " +
discoveredDevices.get(position).getName(),
Toast.LENGTH_SHORT).show();
}
private class WriteTask extends AsyncTask<String, Void, Void> {
protected Void doInBackground(String... args) {
try {
connectToServerThread.commsThread.write(args[0]);
} catch (Exception e) {
Log.d("MainActivity", e.getLocalizedMessage());
}
return null;
}
}
//---send a message to the connected socket client---
public void SendMessage(View view)
{
if (connectToServerThread!=null) {
///=========
//connectToServerThread.commsThread.write(
// txtMessage.getText().toString());
new WriteTask().execute(txtMessage.getText().toString());
///=========
} else {
Toast.makeText(this, "Select a client first",
Toast.LENGTH_SHORT).show();
}
}
}
ServerThread class :
import java.io.IOException;
import java.util.UUID;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
public class ServerThread extends Thread {
//---the server socket---
private final BluetoothServerSocket bluetoothServerSocket;
public ServerThread(BluetoothAdapter bluetoothAdapter) {
BluetoothServerSocket tmp = null;
try {
//---UUID must be the same for both the client and
// the server---
tmp =
bluetoothAdapter.listenUsingRfcommWithServiceRecord(
"BluetoothApp", UUID.fromString(MainActivity.UUID));
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
bluetoothServerSocket = tmp;
}
public void run() {
BluetoothSocket socket = null;
//---keep listening until exception occurs
// or a socket is returned---
while (true) {
try {
socket = bluetoothServerSocket.accept();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
break;
}
//---if a connection was accepted---
if (socket != null) {
//---create a separate thread to listen for
// incoming data---
CommsThread commsThread = new CommsThread(socket);
commsThread.run();
}
}
}
public void cancel() {
try {
bluetoothServerSocket.close();
} catch (IOException e) {
Log.d("ServerThread", e.getLocalizedMessage());
}
}
}
LogCat
04-13 18:25:06.684: D/AndroidRuntime(397): Shutting down VM
04-13 18:25:06.684: W/dalvikvm(397): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:06.704: E/AndroidRuntime(397): FATAL EXCEPTION: main
04-13 18:25:06.704: E/AndroidRuntime(397): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:06.704: E/AndroidRuntime(397): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:06.704: E/AndroidRuntime(397): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:06.704: E/AndroidRuntime(397): Caused by: java.lang.NullPointerException
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:06.704: E/AndroidRuntime(397): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:06.704: E/AndroidRuntime(397): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:06.704: E/AndroidRuntime(397): ... 12 more
04-13 18:25:08.764: I/Process(397): Sending signal. PID: 397 SIG: 9
04-13 18:25:10.354: D/AndroidRuntime(415): Shutting down VM
04-13 18:25:10.354: W/dalvikvm(415): threadid=1: thread exiting with uncaught exception (group=0x40015560)
04-13 18:25:10.364: E/AndroidRuntime(415): FATAL EXCEPTION: main
04-13 18:25:10.364: E/AndroidRuntime(415): java.lang.RuntimeException: Unable to resume activity {net.learn2develop.usingbluetooth/net.learn2develop.usingbluetooth.MainActivity}: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2120)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2135)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1668)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.os.Looper.loop(Looper.java:123)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): at java.lang.reflect.Method.invoke(Method.java:507)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-13 18:25:10.364: E/AndroidRuntime(415): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-13 18:25:10.364: E/AndroidRuntime(415): at dalvik.system.NativeStart.main(Native Method)
04-13 18:25:10.364: E/AndroidRuntime(415): Caused by: java.lang.NullPointerException
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.ServerThread.<init>(ServerThread.java:21)
04-13 18:25:10.364: E/AndroidRuntime(415): at net.learn2develop.usingbluetooth.MainActivity.onResume(MainActivity.java:235)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Instrumentation.callActivityOnResume(Instrumentation.java:1150)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.Activity.performResume(Activity.java:3832)
04-13 18:25:10.364: E/AndroidRuntime(415): at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2110)
04-13 18:25:10.364: E/AndroidRuntime(415): ... 12 more
04-13 18:25:13.304: I/Process(415): Sending signal. PID: 415 SIG: 9

Possible changes you can try which might help you.
In ServerThread.java
public void run() {
....
while(!Thread.currentThread().isInterrupted()){
//do something
}
}
If this works fine, otherwise try:
In MainActivity.java
#Override
public void onCreate() {
....
//Start your thread here
//---start the socket server---
serverThread = new ServerThread(bluetoothAdapter);
serverThread.start();
}
#Override
public void onResume() {
super.onResume();
//handle your thread here - the following maynot be helpful, but logiaclly speaking, //you must handle your threads here
if(serverThread.isAlive())
serverThread.resume();
else
serverThread.interrupt();
}

Related

NullPointerException in onCreateOptionsMenu in Android FragmentActivity

Here, this is detailActivity.java which gathers data from openWeatherAPI and populates the data into a listView. When I click on the item on listView there is NPE in OnCreateOptionsMenu.
package com.example.sunshine2;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager.LoaderCallbacks;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.sunshine2.data.WeatherContract.WeatherEntry;
public class DetailActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new DetailFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class DetailFragment extends Fragment implements
LoaderCallbacks<Cursor> {
private static final String LOG_TAG = DetailFragment.class
.getSimpleName();
private static final String FORECAST_SHARE_HASHTAG = " #SunshineApp";
private ShareActionProvider mShareActionProvider;
private String mForecast;
private static final int DETAIL_LOADER = 0;
private static final String[] FORECAST_COLUMNS = {
WeatherEntry.TABLE_NAME + "." + WeatherEntry._ID,
WeatherEntry.COLUMN_DATE, WeatherEntry.COLUMN_SHORT_DESC,
WeatherEntry.COLUMN_MAX_TEMP, WeatherEntry.COLUMN_MIN_TEMP, };
// these constants correspond to the projection defined above, and must
// change if the
// projection changes
private static final int COL_WEATHER_ID = 0;
private static final int COL_WEATHER_DATE = 1;
private static final int COL_WEATHER_DESC = 2;
private static final int COL_WEATHER_MAX_TEMP = 3;
private static final int COL_WEATHER_MIN_TEMP = 4;
public DetailFragment() {
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_detail, container, false);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is
// present.
inflater.inflate(R.menu.detail_fragment, menu);
// Retrieve the share menu item
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat
.getActionProvider(menuItem);
// If onLoadFinished happens before this, we can go ahead and set
// the share intent now.
if (mForecast != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
private Intent createShareForecastIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, mForecast
+ FORECAST_SHARE_HASHTAG);
return shareIntent;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
getLoaderManager().initLoader(DETAIL_LOADER, null, this);
super.onActivityCreated(savedInstanceState);
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
Log.v(LOG_TAG, "In onCreateLoader");
Intent intent = getActivity().getIntent();
if (intent == null) {
return null;
}
// Now create and return a CursorLoader that will take care of
// creating a Cursor for the data being displayed.
return new CursorLoader(getActivity(), intent.getData(),
FORECAST_COLUMNS, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
Log.v(LOG_TAG, "In onLoadFinished");
if (!data.moveToFirst()) {
return;
}
String dateString = Utility.formatDate(data
.getLong(COL_WEATHER_DATE));
String weatherDescription = data.getString(COL_WEATHER_DESC);
boolean isMetric = Utility.isMetric(getActivity());
String high = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MAX_TEMP), isMetric);
String low = Utility.formatTemperature(
data.getDouble(COL_WEATHER_MIN_TEMP), isMetric);
mForecast = String.format("%s - %s - %s/%s", dateString,
weatherDescription, high, low);
TextView detailTextView = (TextView) getView().findViewById(
R.id.detail_text);
detailTextView.setText(mForecast);
// If onCreateOptionsMenu has already happened, we need to update
// the share intent now.
if (mShareActionProvider != null) {
mShareActionProvider
.setShareIntent(createShareForecastIntent());
}
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
}
And Here is the LogCat
04-13 01:22:51.916: E/AndroidRuntime(20197): FATAL EXCEPTION: main
04-13 01:22:51.916: E/AndroidRuntime(20197): Process: com.example.sunshine2, PID: 20197
04-13 01:22:51.916: E/AndroidRuntime(20197): java.lang.NullPointerException
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.example.sunshine2.DetailActivity$DetailFragment.onCreateOptionsMenu(DetailAc tivity.java:117)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.Fragment.performCreateOptionsMenu(Fragment.java:1582)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentManagerImpl.dispatchCreateOptionsMenu(FragmentManager.java:1967)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:225)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.superOnCreatePanelMenu(ActionBarActivity.java:232)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS.onCreatePanelMenu(ActionBarActivityDelegateICS.java:146)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivity.onCreatePanelMenu(ActionBarActivity.java:199)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.support.v7.app.ActionBarActivityDelegateICS$WindowCallbackWrapper.onCreatePanelMenu(ActionBarActivityDelegateICS.java:293)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.preparePanel(PhoneWindow.java:436)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow.doInvalidatePanelMenu(PhoneWindow.java:803)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.policy.impl.PhoneWindow$1.run(PhoneWindow.java:221)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.handleCallback(Handler.java:733)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Handler.dispatchMessage(Handler.java:95)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.os.Looper.loop(Looper.java:149)
04-13 01:22:51.916: E/AndroidRuntime(20197): at android.app.ActivityThread.main(ActivityThread.java:5077)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 01:22:51.916: E/AndroidRuntime(20197): at java.lang.reflect.Method.invoke(Method.java:515)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-13 01:22:51.916: E/AndroidRuntime(20197): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:609)
04-13 01:22:51.916: E/AndroidRuntime(20197): at dalvik.system.NativeStart.main(Native Method)
I've tried debugging the code, but the
- mShareActionProvider gives me null, which I can't figure out how
I think the problem is you have a onClick function declared in your XML menu layout file but no corresponding function in your code.

mediaMetadataRetriever.setDataSource(getBaseContext(),uri) throws illegal argument exception

Hello developers I have a piece of that grabs the frames of a video...It seems it will work fine except a part of it where I am getting illegal argument exception...As I set the path of the video it crashes..Here is my code it crashes at the line
mediaMetadataRetriever.setDataSource(getBaseContext(),uri)
Here is the full code:
import java.io.IOException;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.Toast;
import android.widget.VideoView;
public class MainActivity extends Activity {
MediaMetadataRetriever mediaMetadataRetriever;
MediaController myMediaController;
VideoView myVideoView;
String viewSource = "/storage/test.mp4";
// String viewSource = "/storage/test.mp4";
Uri uri = null;
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
AssetFileDescriptor afd = getAssets().openFd("test.mp4");
Log.v("MA", "Before setdatasource");
uri = Uri.parse("E:/test.mp4");
mediaMetadataRetriever = new MediaMetadataRetriever();
**mediaMetadataRetriever.setDataSource(getBaseContext(),uri);**
// mediaMetadataRetriever.setDataSource(afd.getFileDescriptor(),
// afd.getStartOffset(), afd.getLength());
Log.v("MA", "After setdatasource" + afd.getStartOffset());
myVideoView = (VideoView) findViewById(R.id.videoview);
Log.v("MA", "VIdeoview found");
myVideoView.setVideoURI(Uri.parse(viewSource));
Log.v("MA", "After setdatasource");
myMediaController = new MediaController(this);
Log.v("MA", "After setdatasource");
myVideoView.setMediaController(myMediaController);
Log.v("MA", "myMediaController initialised");
myVideoView.setOnCompletionListener(myVideoViewCompletionListener);
Log.v("MA", "setOnCompletionListener");
myVideoView.setOnPreparedListener(MyVideoViewPreparedListener);
Log.v("MA", "setOnPreparedListener");
myVideoView.setOnErrorListener(myVideoViewErrorListener);
Log.v("MA", "setOnErrorListener");
myVideoView.requestFocus();
Log.v("MA", "focus set");
myVideoView.start();
Log.v("MA", "video started");
Button buttonCapture = (Button) findViewById(R.id.capture);
buttonCapture.setOnClickListener(new OnClickListener() {
#TargetApi(Build.VERSION_CODES.GINGERBREAD_MR1)
#Override
public void onClick(View arg0) {
int currentPosition = myVideoView.getCurrentPosition(); // in
// millisecond
Toast.makeText(MainActivity.this,
"Current Position: " + currentPosition + " (ms)",
Toast.LENGTH_LONG).show();
Bitmap bmFrame = mediaMetadataRetriever
.getFrameAtTime(currentPosition * 1000); // unit in
// microsecond
if (bmFrame == null) {
Toast.makeText(MainActivity.this, "bmFrame == null!",
Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder myCaptureDialog = new AlertDialog.Builder(
MainActivity.this);
ImageView capturedImageView = new ImageView(
MainActivity.this);
capturedImageView.setImageBitmap(bmFrame);
LayoutParams capturedImageViewLayoutParams = new LayoutParams(
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
capturedImageView
.setLayoutParams(capturedImageViewLayoutParams);
myCaptureDialog.setView(capturedImageView);
myCaptureDialog.show();
}
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
MediaPlayer.OnCompletionListener myVideoViewCompletionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
Toast.makeText(MainActivity.this, "End of Video", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnPreparedListener MyVideoViewPreparedListener = new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
long duration = myVideoView.getDuration(); // in millisecond
Toast.makeText(MainActivity.this,
"Duration: " + duration + " (ms)", Toast.LENGTH_LONG)
.show();
}
};
MediaPlayer.OnErrorListener myVideoViewErrorListener = new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(MainActivity.this, "Error!!!", Toast.LENGTH_LONG)
.show();
return true;
}
};
}
Trace:
E/AndroidRuntime( 4317): FATAL EXCEPTION: main
E/AndroidRuntime( 4317): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.captureframe/com.example.captureframe.MainActivity}: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
E/AndroidRuntime( 4317): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
E/AndroidRuntime( 4317): at android.app.ActivityThread.access$600(ActivityThread.java:141)
E/AndroidRuntime( 4317): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
E/AndroidRuntime( 4317): at android.os.Handler.dispatchMessage(Handler.java:99)
E/AndroidRuntime( 4317): at android.os.Looper.loop(Looper.java:137)
E/AndroidRuntime( 4317): at android.app.ActivityThread.main(ActivityThread.java:5103)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invokeNative(Native Method)
E/AndroidRuntime( 4317): at java.lang.reflect.Method.invoke(Method.java:525)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
E/AndroidRuntime( 4317): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
E/AndroidRuntime( 4317): at dalvik.system.NativeStart.main(Native Method)
E/AndroidRuntime( 4317): Caused by: java.lang.IllegalArgumentException
E/AndroidRuntime( 4317): at android.media.MediaMetadataRetriever.setDataSource(MediaMetadataRetriever.java:165)
E/AndroidRuntime( 4317): at com.example.captureframe.MainActivity.onCreate(MainActivity.java:46)
E/AndroidRuntime( 4317): at android.app.Activity.performCreate(Activity.java:5133)
E/AndroidRuntime( 4317): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
E/AndroidRuntime( 4317): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
Any ideas will be really appreciated.
Use this method.
public static Bitmap retriveVideoFrameFromVideo(String videoPath)
throws Throwable
{
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try
{
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime();
}
catch (Exception e)
{
e.printStackTrace();
throw new Throwable(
"Exception in retriveVideoFrameFromVideo(String videoPath)"
+ e.getMessage());
}
finally
{
if (mediaMetadataRetriever != null)
{
mediaMetadataRetriever.release();
}
}
return bitmap;
}

Open2.4.5 Android Crashes when I call Mat

This issue is been driving me crazy for days now. I'm trying to use opencv android the latest package. Everything is inserted and I don't have any errors, until I run the project on android and that's when it crashes. When I call a simple code like, Mat m = new Mat(); the app crashes, I saw some other people has the same problem but somehow they managed to fix it, here is my code, maybe it's something stupid I can't see! All I really need is Matrix library, I tried Jama and jblas but they work to some point but then they crash too, and they're very slow.
package com.ece.facerecog;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;'
import java.util.Arrays;
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Mat;
import com.ece.facerecog.utils.UIHelper;
//import org.jblas.DoubleMatrix;
//import Jama.Matrix;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
//import android.graphics.Matrix;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
public class Face extends Activity {
private Bitmap bitmap;
private int f = Crop.k;
private ImageView tv;
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
// #Override
// public void onResume()
// {
// super.onResume();
// OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, k mLoaderCallback);
// }
private Bitmap ReadImage1(String fBitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/preprocessed");
File file = new File(myDir , fBitmap); //or any other format supported
UIHelper.displayText(this, R.id.textView1, file.toString());
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = `BitmapFactory.decodeFile(file.getAbsolutePath(),options); //This gets the image `
return bitmap;
} catch (Exception e) {
e.printStackTrace();
UIHelper.displayText(this, R.id.textView1, "Doesn't exist");
}
return bitmap;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.face);
Log.i(TAG, "Trying to load OpenCV library");
if (!OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_5, this, mLoaderCallback))
{
Log.e(TAG, "Cannot connect to OpenCV Manager");
}
ImageView tv = (ImageView) findViewById(R.id.imageView1);
Bitmap bmp = ReadImage1("/Image-" + f+ ".jpg");
tv.setImageBitmap(bmp);
Mat m = new Mat();
}
}
`
Here's the log error,
04-13 23:14:17.412: E/AndroidRuntime(12111): FATAL EXCEPTION: main
04-13 23:14:17.412: E/AndroidRuntime(12111): java.lang.UnsatisfiedLinkError: Native method not found: org.opencv.core.Mat.n_Mat:()J
04-13 23:14:17.412: E/AndroidRuntime(12111): at org.opencv.core.Mat.n_Mat(Native Method)
04-13 23:14:17.412: E/AndroidRuntime(12111): at org.opencv.core.Mat.<init>(Mat.java:441)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.ece.facerecog.Face.onCreate(Face.java:147)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.Activity.performCreate(Activity.java:5104)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.access$600(ActivityThread.java:141)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.os.Handler.dispatchMessage(Handler.java:99)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.os.Looper.loop(Looper.java:137)
04-13 23:14:17.412: E/AndroidRuntime(12111): at android.app.ActivityThread.main(ActivityThread.java:5039)
04-13 23:14:17.412: E/AndroidRuntime(12111): at java.lang.reflect.Method.invokeNative(Native Method)
04-13 23:14:17.412: E/AndroidRuntime(12111): at java.lang.reflect.Method.invoke(Method.java:511)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-13 23:14:17.412: E/AndroidRuntime(12111): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-13 23:14:17.412: E/AndroidRuntime(12111): at dalvik.system.NativeStart.main(Native Method)
Thanks for helping me out!
OpenCV functions such as Mat have to be invoked in either a thread or AsyncTask, I think. I faced the SAME issue for AGES without help.
For you to avoid crashes, you could declare Mat m as a global variable and initialize it in the AsyncInitialization block of OpenCV.
Something like this :
public class Face extends Activity {
private Bitmap bitmap;
private int f = Crop.k;
private ImageView tv;
Mat m;
private static final String TAG = "OCVSample::Activity";
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
#Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
m=new Mat();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
If it still crashes, I would suggest you execute whatever function you're trying in an AsyncTask like in my project. Mat functions however can be declared without the risk of the UnsatisfiedLinkError exception in OpenCV functions. Functions called in the UI however experience this. At least this is what I've seen.
I just faced the same problem and found another solution:
You can use another activity to call your activity ("Face"), like some introduction screen with a button that starts your activity. If you initialize OpenCV in this introduction activity (same way you did in your activity) you can use OpenCV functions in the next activity without any problem...
This way you don't have to declare OpenCV variables as a global variables and initialize them in the AsyncInitialization block of OpenCV.

NPE when trying connect and send telnet commands

I'm hoping you can all help me out here.
Basically I have been having a few problems with my app. My previous questions on Stack have now all been solved so thanks to everyone who helped me out.
I am now getting a NPE but no idea why.
Basically my code is:
Connecting to a device (IP address from an intent and fixed port of 32)
Once connected send the command "root/r/n" twice. (This is the login for the device not the actual connection, the connection is not protected.
Once there is return of "SNX_COM>" or "SCX_COM>" await commands.
I then want to be able to send them commands from a button click.
The problem I have is that I cannot get the initial connection active. It would be grateful if someone could help me.
Java class:
package com.smarte.smartipcontrol;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
public class IPControl extends Activity {
private Socket socket;
private static final int REDIRECTED_SERVERPORT = 32;
public PrintWriter out;
public BufferedReader in;
public String data;
public Object pd;
//get the message from intent
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
public void getModel(View view) {
try {
out.println("[m\r\n");
//System.out.print("root\r\n");
while(!in.ready());
String textStatus = readBuffer();
} catch(IOException e) {
e.printStackTrace();
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_ipcontrol);
try {
new AsyncAction().execute();
} catch(Exception e) {
e.printStackTrace();
}
}
private class AsyncAction extends AsyncTask<String, Void, String> {
protected String doInBackground(String... args) {
try {
InetAddress serverAddr = InetAddress.getByName(actu_ip);
socket = new Socket(serverAddr, REDIRECTED_SERVERPORT);
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
BufferedWriter bw = new BufferedWriter(osw);
out = new PrintWriter(bw, true);
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
readBuffer();
out.println("root\r\n");
while (! in .ready());
String msg = "";
while ( in .ready()) {
msg = msg + (char) in .read();
}
out.println("[c,l#,i5,o*\r\n");
while (! in .ready());
readBuffer();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;//returns what you want to pass to the onPostExecute()
}
protected void onPostExecute(String result) {
//results the data returned from doInbackground
IPControl.this.data = result;
}
}
private String readBuffer() throws IOException {
String msg = "";
while(in.ready()) {
msg = msg + (char)in.read();
}
//System.out.print(msg);
if(msg.indexOf("SNX_COM> ") != -1) return msg.substring(0, msg.indexOf("SNX_COM> "));
else if(msg.indexOf("SCX_COM> ") != -1) return msg.substring(0, msg.indexOf("SCX_COM> "));
else return msg;
}
}
LogCat:
12-07 09:29:24.596: E/AndroidRuntime(772): FATAL EXCEPTION: main
12-07 09:29:24.596: E/AndroidRuntime(772): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.smarte.smartipcontrol/com.smarte.smartipcontrol.IPControl}: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.os.Looper.loop(Looper.java:137)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.main(ActivityThread.java:5039)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invokeNative(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.reflect.Method.invoke(Method.java:511)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
12-07 09:29:24.596: E/AndroidRuntime(772): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
12-07 09:29:24.596: E/AndroidRuntime(772): at dalvik.system.NativeStart.main(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): Caused by: java.lang.NullPointerException
12-07 09:29:24.596: E/AndroidRuntime(772): at com.smarte.smartipcontrol.IPControl.<init>(IPControl.java:29)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstanceImpl(Native Method)
12-07 09:29:24.596: E/AndroidRuntime(772): at java.lang.Class.newInstance(Class.java:1319)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
12-07 09:29:24.596: E/AndroidRuntime(772): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
12-07 09:29:24.596: E/AndroidRuntime(772): ... 11 more
Thanks in advanced.
The problem that prevents your app to start is in these two lines:
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
I can't use getIntent() in the initialization, you should move it to the onCreate():
Intent intent;
String actu_ip;
#Override
public void onCreate(Bundle savedInstanceState) {
....
Intent intent = getIntent();
String actu_ip = intent.getStringExtra(IPEntry.ACTUALSMARTIP);
....
}
Regards.

Android radio streaming app crashes when you press pause or stop at the moment you haven't clicked play

When i start my app and press stop or pause the android app will crash. It works fine if you press play first and then stop or pause. I searched on google and stackoverflow but i couldn't find much about it. I think the problem is because of a NullPointerException but since i'm new too java it doesn't tell me much about the problem
The code:
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class myMain extends Activity implements
MediaPlayer.OnCompletionListener, MediaPlayer.OnPreparedListener,
MediaPlayer.OnErrorListener, MediaPlayer.OnBufferingUpdateListener, OnClickListener {
private String TAG = getClass().getSimpleName();
private MediaPlayer mp= null;
private Button play;
private Button pause;
private Button stop;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
play = (Button) findViewById(R.id.play);
pause = (Button) findViewById(R.id.pause);
stop = (Button) findViewById(R.id.stop);
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
play();
}
});
pause.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
pause();
}
});
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
stop();
}
});
}
private void play() {
Uri myUri = Uri.parse("url");
try {
if (mp == null) {
this.mp = new MediaPlayer();
} else {
mp.stop();
mp.reset();
}
mp.setDataSource(this, myUri); // Go to Initialized state
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setOnPreparedListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnErrorListener(this);
mp.prepareAsync();
Log.d(TAG, "LoadClip Done");
} catch (Throwable t) {
Log.d(TAG, t.toString());
}
}
public void onPrepared(MediaPlayer mp) {
Log.d(TAG, "Stream is prepared");
mp.start();
}
private void pause() {
mp.pause();
}
private void stop() {
mp.stop();
}
#Override
public void onDestroy() {
super.onDestroy();
stop();
}
public void onCompletion(MediaPlayer mp) {
stop();
}
public boolean onError(MediaPlayer mp, int what, int extra) {
StringBuilder sb = new StringBuilder();
sb.append("Media Player Error: ");
switch (what) {
case MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK:
sb.append("Not Valid for Progressive Playback");
break;
case MediaPlayer.MEDIA_ERROR_SERVER_DIED:
sb.append("Server Died");
break;
case MediaPlayer.MEDIA_ERROR_UNKNOWN:
sb.append("Unknown");
break;
default:
sb.append(" Non standard (");
sb.append(what);
sb.append(")");
}
sb.append(" (" + what + ") ");
sb.append(extra);
Log.e(TAG, sb.toString());
return true;
}
public void onBufferingUpdate(MediaPlayer mp, int percent) {
Log.d(TAG, "PlayerService onBufferingUpdate : " + percent + "%");
}
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
The errors:
02-11 20:45:43.837: D/AndroidRuntime(338): Shutting down VM
02-11 20:45:43.837: W/dalvikvm(338): threadid=1: thread exiting with uncaught exception (group=0x40015560)
02-11 20:45:43.857: E/AndroidRuntime(338): FATAL EXCEPTION: main
02-11 20:45:43.857: E/AndroidRuntime(338): java.lang.NullPointerException
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.stop(myMain.java:95)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain.access$2(myMain.java:94)
02-11 20:45:43.857: E/AndroidRuntime(338): at wadio.media.internetradio.myMain$3.onClick(myMain.java:55)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View.performClick(View.java:2485)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.view.View$PerformClick.run(View.java:9080)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.handleCallback(Handler.java:587)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Handler.dispatchMessage(Handler.java:92)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.os.Looper.loop(Looper.java:123)
02-11 20:45:43.857: E/AndroidRuntime(338): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invokeNative(Native Method)
02-11 20:45:43.857: E/AndroidRuntime(338): at java.lang.reflect.Method.invoke(Method.java:507)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-11 20:45:43.857: E/AndroidRuntime(338): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-11 20:45:43.857: E/AndroidRuntime(338): at dalvik.system.NativeStart.main(Native Method)
In your stop() method you access the mp variable. However, the mp variable is null until you press play (and the play() method is called). So when you try to access the null variable a NullPointerException is thrown.
A very simple way to stop the NullPointerException is to do something like this:
private void pause() {
if(mp!=null) mp.pause();
}
private void stop() {
if(mp!=null) mp.stop();
}
Of course this solution doesn't account for cases where pause or stop is called twice. Take a look at the MediaPlayer documentation for more info on state management.

Categories