Android music player prepare method failed - java

I have been trying to play an MP3 file. It just won't work.
I did manage to play it and add all sorts of functionalities to it with the very same/similar code a few days ago. Just tried to make it all over again and now these errors...
Can someone point out the error also why does this happen.
Just to clarify I used different formats of URI, none of them work. Thought maybe its the prepare method.
package com.player.phoneagent.gui;
import java.io.IOException;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class AndroidClientActivity extends Activity {
/** Called when the activity is first created. */
private MediaPlayer mp;
String path = "android.resource://com.player.phoneagent/raw/test";
ImageButton btn_prev;
ImageButton btn_play;
ImageButton btn_pause;
ImageButton btn_next;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn_prev = (ImageButton) findViewById(R.id.ImageButton01);
btn_pause = (ImageButton) findViewById(R.id.ImageButton02);
btn_play = (ImageButton) findViewById(R.id.ImageButton03);
btn_next = (ImageButton) findViewById(R.id.ImageButton04);
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
mp.setDataSource(path);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
});
}
}
08-01 07:06:00.142: W/KeyCharacterMap(407): No keyboard for id 0
08-01 07:06:00.142: W/KeyCharacterMap(407): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
08-01 07:06:05.821: D/dalvikvm(407): GC_EXPLICIT freed 21K, 53% free 2568K/5379K, external 3207K/3962K, paused 55ms
08-01 07:06:20.311: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 52K, 53% free 2552K/5379K, external 1969K/2137K, paused 58ms
08-01 07:06:43.171: E/MediaPlayer(444): error (1, -2147483648)
08-01 07:06:43.171: W/System.err(444): java.io.IOException: Prepare failed.: status=0x1
08-01 07:06:43.171: W/System.err(444): at android.media.MediaPlayer.prepare(Native Method)
08-01 07:06:43.171: W/System.err(444): at com.player.phoneagent.gui.AndroidClientActivity$1.onClick(AndroidClientActivity.java:60)
08-01 07:06:43.171: W/System.err(444): at android.view.View.performClick(View.java:2485)
08-01 07:06:43.171: W/System.err(444): at android.view.View$PerformClick.run(View.java:9080)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.handleCallback(Handler.java:587)
08-01 07:06:43.181: W/System.err(444): at android.os.Handler.dispatchMessage(Handler.java:92)
08-01 07:06:43.181: W/System.err(444): at android.os.Looper.loop(Looper.java:123)
08-01 07:06:43.181: W/System.err(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 07:06:43.181: W/System.err(444): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 07:06:43.181: W/System.err(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 07:06:43.181: W/System.err(444): at dalvik.system.NativeStart.main(Native Method)
08-01 07:06:43.181: E/MediaPlayer(444): start called in state 0
08-01 07:06:43.181: E/MediaPlayer(444): error (-38, 0)
08-01 07:06:43.181: E/MediaPlayer(444): Error (-38,0)

I always had problems trying to use "raw" folder... I suggest putting the sound file in "assets" and using the methods here to set / prepare / and play:
http://droidapp.co.uk/2011/06/08/android-dev-playing-a-mp3-from-assets/

Just do something like:
MediaPlayer mp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
btn_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mp.stop();
mp.release();
mp = null;
mp = MediaPlayer.create(this, R.raw.yourSongFileName);
mp.start();
//Other stuff below.
See if that works.

Related

Bluetooth Messenger application crashing at start up itself

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();
}

GoogleMap Android API V2 Capture Error

I try #Tarsem answer already but have fatal error occur can I know why?
#Tarsem answer:
https://stackoverflow.com/a/18308611/2398886
<--- these are my error codes in eclipse: --->
08-21 18:52:23.399: W/dalvikvm(29376): threadid=1: thread exiting with uncaught exception (group=0x40018578)
08-21 18:52:23.409: E/AndroidRuntime(29376): FATAL EXCEPTION: main
08-21 18:52:23.409: E/AndroidRuntime(29376): java.lang.NoClassDefFoundError: com.example.testing01.MainActivity2$6
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2.CaptureMapScreen(MainActivity2.java:410)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.example.testing01.MainActivity2$3.onClick(MainActivity2.java:182)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View.performClick(View.java:2485)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.view.View$PerformClick.run(View.java:9080)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.handleCallback(Handler.java:587)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Handler.dispatchMessage(Handler.java:92)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.os.Looper.loop(Looper.java:130)
08-21 18:52:23.409: E/AndroidRuntime(29376): at android.app.ActivityThread.main(ActivityThread.java:3687)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invokeNative(Native Method)
08-21 18:52:23.409: E/AndroidRuntime(29376): at java.lang.reflect.Method.invoke(Method.java:507)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:867)
08-21 18:52:23.409: E/AndroidRuntime(29376): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
08-21 18:52:23.409: E/AndroidRuntime(29376): at dalvik.system.NativeStart.main(Native Method)
<--- these are my error codes in eclipse: --->
and these are my coding, is it my coding any bug?
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
map.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
my Stop Button function:
//End Button Function
Button timerStopButton = (Button) findViewById(R.id.btnTimerStop);
timerStopButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
String latitude3=Double.toString(latitude1);
String latitude4=Double.toString(latitude2);
String longitude3=Double.toString(longitude1);
String longitude4=Double.toString(longitude2);
String Kcalories=String.format("%.2f", calories);
Intent intent = new Intent(view.getContext(),NewDataActivity.class);
intent.putExtra("lat1", latitude3);
intent.putExtra("lat2", latitude4);
intent.putExtra("long1", longitude3);
intent.putExtra("long2", longitude4);
intent.putExtra("timer", timerStop1);
intent.putExtra("distance", distance2 + " m");
intent.putExtra("Ccalories", Kcalories + " kcal");
Toast.makeText(getApplicationContext(), "Calories (kcal):" + Kcalories, Toast.LENGTH_LONG).show();
startActivity(intent);
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
//kill task timer and other
int pid = android.os.Process.myPid();
android.os.Process.killProcess(pid);
}
});
Is it my coding have any bug or my logic any probelm?
can anyone help me? thanks :)
Note Your code to Capture Map Screen is Correct and if still you have confusion than
Please Make sure Each Step Below:-
Below are the steps to capture screen shot of Google Map V2 with example
Step 1. open Android Sdk Manager (Window > Android Sdk Manager) then Expand Extras now update/install Google Play Services to Revision 10 ignore this step if already installed
Read Notes here https://developers.google.com/maps/documentation/android/releases#august_2013
Step 2. Restart Eclipse
Step 3. import com.google.android.gms.maps.GoogleMap.SnapshotReadyCallback;
Step 4. Make Method to Capture/Store Screen/image of Map like below
public void CaptureMapScreen()
{
SnapshotReadyCallback callback = new SnapshotReadyCallback() {
Bitmap bitmap;
#Override
public void onSnapshotReady(Bitmap snapshot) {
// TODO Auto-generated method stub
bitmap = snapshot;
try {
FileOutputStream out = new FileOutputStream("/mnt/sdcard/"
+ "MyMapScreen" + System.currentTimeMillis()
+ ".png");
// above "/mnt ..... png" => is a storage path (where image will be stored) + name of image you can customize as per your Requirement
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
myMap.snapshot(callback);
// myMap is object of GoogleMap +> GoogleMap myMap;
// which is initialized in onCreate() =>
// myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_pass_home_call)).getMap();
}
Step 5. Now call this CaptureMapScreen() method where you want to capture the image
in my case i am calling this method on Button click in my onCreate() which is working fine
like:
Button btnCap = (Button) findViewById(R.id.btnTakeScreenshot);
btnCap.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
CaptureMapScreen();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
});
Check Doc here and here

When emulator begins and try to connect to database, application stops unexpectedly

Hello i'm new to android development and this is my first app. I try to connect to a database but when the emulator starts the application stops unexpectedly. Everything in eclipse is fine but when i run the emulator it stops. Here is the code:
public class Antallaktika extends Activity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<String> al = new ArrayList<String>();
ArrayList<String> al1 = new ArrayList<String>();
ArrayList<String> al2 = new ArrayList<String>();
String targetname;
String targetsku;
String targetprice;
int responseCode;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.antallaktika);
setTitle("Ανταλλακτικά");
try {
URL url = new URL("http://machina.gr/antallaktika.php");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
HttpURLConnection httpConnection = (HttpURLConnection) connection;
responseCode = httpConnection.getResponseCode();
}
catch (Exception e) {}
try{
if(isNetworkAvailable()==true && responseCode == HttpURLConnection.HTTP_OK){
new LoadData().execute();
}
else{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("No Internet Connection available!!!");
ad.show();
}
}
catch(Exception e){
}
}
public class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
this.progressDialog = ProgressDialog.show(Antallaktika.this, ""," Loading...");
}
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
try{
ListView listview = (ListView) findViewById(R.id.listView1);
this.progressDialog.dismiss();
listview.setAdapter(new DataAdapter(Antallaktika.this,al.toArray(new String[al.size()]),al1.toArray(new String[al1.size()]),al2.toArray(new String[al2.size()])));
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
try {
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
try{
HttpPost httppost = new HttpPost("http://machina.gr/antallaktika.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
//buffered reader
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
}
catch(Exception e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
try{
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
targetname=json_data.getString("targetname");
targetsku=json_data.getString("targetsku");
targetprice = json_data.getString("targetprice");
al.add(targetname);
al1.add(targetsku);
al2.add(targetprice);
}
}
catch(JSONException e){
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
} catch (ParseException e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
catch (Exception e) {
// Log.e("log_tag", "Error in http connection" + e.toString());
Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
}
return null;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
// if no network is available networkInfo will be null, otherwise check
// if we are connected
if (networkInfo != null && networkInfo.isConnected()) {
// Log.i("net status:", "Online...!!!");
return true;
}
// Log.i("net status:", "offline...!!!");
return false;
}
}
and the logcat is:
08-01 20:51:36.042: E/AndroidRuntime(375): FATAL EXCEPTION: AsyncTask #1
08-01 20:51:36.042: E/AndroidRuntime(375): java.lang.RuntimeException: An error occured while executing doInBackground()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$3.done(AsyncTask.java:200)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.lang.Thread.run(Thread.java:1019)
08-01 20:51:36.042: E/AndroidRuntime(375): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.Handler.<init>(Handler.java:121)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.<init>(Toast.java:68)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.widget.Toast.makeText(Toast.java:231)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:161)
08-01 20:51:36.042: E/AndroidRuntime(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.doInBackground(Antallaktika.java:1)
08-01 20:51:36.042: E/AndroidRuntime(375): at android.os.AsyncTask$2.call(AsyncTask.java:185)
08-01 20:51:36.042: E/AndroidRuntime(375): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
08-01 20:51:36.042: E/AndroidRuntime(375): ... 4 more
08-01 20:51:37.142: E/WindowManager(375): Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): android.view.WindowLeaked: Activity com.pythagoras.machina.gr.Antallaktika has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#405312b8 that was originally added here
08-01 20:51:37.142: E/WindowManager(375): at android.view.ViewRoot.<init>(ViewRoot.java:258)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
08-01 20:51:37.142: E/WindowManager(375): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
08-01 20:51:37.142: E/WindowManager(375): at android.view.Window$LocalWindowManager.addView(Window.java:424)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Dialog.show(Dialog.java:241)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:107)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:90)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ProgressDialog.show(ProgressDialog.java:85)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika$LoadData.onPreExecute(Antallaktika.java:85)
08-01 20:51:37.142: E/WindowManager(375): at android.os.AsyncTask.execute(AsyncTask.java:391)
08-01 20:51:37.142: E/WindowManager(375): at com.pythagoras.machina.gr.Antallaktika.onCreate(Antallaktika.java:67)
08-01 20:51:37.142: E/WindowManager(375): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Handler.dispatchMessage(Handler.java:99)
08-01 20:51:37.142: E/WindowManager(375): at android.os.Looper.loop(Looper.java:130)
08-01 20:51:37.142: E/WindowManager(375): at android.app.ActivityThread.main(ActivityThread.java:3683)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invokeNative(Native Method)
08-01 20:51:37.142: E/WindowManager(375): at java.lang.reflect.Method.invoke(Method.java:507)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
08-01 20:51:37.142: E/WindowManager(375): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
08-01 20:51:37.142: E/WindowManager(375): at dalvik.system.NativeStart.main(Native Method)
you are trying to access UI functionality from a thread other than the UI thread (i guess it is the Toast). that is not possible. see here for info on how to run code on the UI thread.

Android using jaudiotagger

I try to use jaudiotagger like this
but it crashes
Main app.java :
import java.io.File;
import java.io.IOException;
import org.jaudiotagger.audio.AudioFile;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.AudioHeader;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.tag.FieldDataInvalidException;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.KeyNotFoundException;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;
public class App extends Activity {
/** Called when the activity is first created. */
private TextView txt1;
private TextView txt2;
private TextView txt3;
private TextView txt4;
private TextView txt5;
private TextView txt6;
private TextView txt7;
private TextView txt8;
private TextView txt9;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// try
//{
File mp3 = new File("/sdcard/test.mp3");
AudioFile f = null;
try {
f = AudioFileIO.read(mp3);
} catch (CannotReadException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (TagException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (ReadOnlyFileException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (InvalidAudioFrameException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
}
Tag tag = f.getTag();
AudioHeader AudioHeader = f.getAudioHeader();
txt1.setText(tag.getFirst(FieldKey.ARTIST));
txt2.setText(tag.getFirst(FieldKey.ALBUM));
txt3.setText(tag.getFirst(FieldKey.TITLE));
txt4.setText(tag.getFirst(FieldKey.COMMENT));
txt5.setText(tag.getFirst(FieldKey.YEAR));
txt6.setText(tag.getFirst(FieldKey.TRACK));
txt7.setText(tag.getFirst(FieldKey.DISC_NO));
txt8.setText(tag.getFirst(FieldKey.COMPOSER));
txt9.setText(tag.getFirst(FieldKey.ARTIST_SORT));
try {
tag.setField(FieldKey.ARTIST,"Kings of Leon");
} catch (KeyNotFoundException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
} catch (FieldDataInvalidException e) {
// TODO Auto-generated catch block
txt1.setText(e.toString());
}
try {
AudioFileIO.write(f);
} catch (CannotWriteException e) {
txt1.setText(e.toString());
}
/* }
catch(Exception x)
{
txt1.setText(x.toString());
}
*/
}
}
Logcat :
02-22 21:12:22.546: E/AndroidRuntime(19738): FATAL EXCEPTION: main
02-22 21:12:22.546: E/AndroidRuntime(19738):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.mp3.tag.editor.alexander.fuchs/com.mp3.tag.editor.alexander.fuchs.App}:
java.lang.NullPointerException 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.access$1500(ActivityThread.java:117) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.os.Handler.dispatchMessage(Handler.java:99) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.os.Looper.loop(Looper.java:130) 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
android.app.ActivityThread.main(ActivityThread.java:3691) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
java.lang.reflect.Method.invokeNative(Native Method) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
java.lang.reflect.Method.invoke(Method.java:507) 02-22 21:12:22.546:
E/AndroidRuntime(19738): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
dalvik.system.NativeStart.main(Native Method) 02-22 21:12:22.546:
E/AndroidRuntime(19738): Caused by: java.lang.NullPointerException
02-22 21:12:22.546: E/AndroidRuntime(19738): at
com.mp3.tag.editor.alexander.fuchs.App.onCreate(App.java:72) 02-22
21:12:22.546: E/AndroidRuntime(19738): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-22 21:12:22.546: E/AndroidRuntime(19738): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
02-22 21:12:22.546: E/AndroidRuntime(19738): ... 11 more
There two blockers
to using jaudiotagger on Android:
1 - javax.swing
2 - javax.imageio
these two Classes isn't supported by android and jaudiotagger uses them
To solve your problem:
Fix the sources so they don't depend no more on these two JAVAX Classes
Seems like this line causes the crash, because f is null:
Tag tag = f.getTag();
You shouldn't ignore the exception in the way you do, as if you got an exception, you just print something and continue with a bad state (in this case - f is still null)
You still need to check that f != null before you get the tag.
Tag r_tag = null;
File testFile = new File(filename);
MP3File f = null;
try {
f = (MP3File)AudioFileIO.read(testFile);
} catch (CannotReadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (TagException e) {
e.printStackTrace();
} catch (ReadOnlyFileException e) {
e.printStackTrace();
} catch (InvalidAudioFrameException e) {
e.printStackTrace();
}
if(f != null) {
f.getTagOrCreateAndSetDefault();
r_tag = f.getID3v2TagAsv24();
}
return r_tag;

FileInputStream in Another class?

I'm loading a file that has been saved by another class via the FileOutputstream method. Anyway, I want to load that file in another class, but it either gives me syntax errors or crashes my App.
The only tutorials I could find where they saved and loaded the file in the same class, but I want to load it up in another class and couldn't find how to solve the problem of loading into another class.
Thanks
My Code:
public class LogIn extends Activity implements OnClickListener {
EditText eTuser;
EditText eTpassword;
CheckBox StaySignedIn;
Button bSubmit;
String user;
String pass;
FileOutputStream fos;
FileInputStream fis = null;
String FILENAME = "userandpass";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
eTuser = (EditText) findViewById(R.id.eTuser);
eTpassword = (EditText) findViewById(R.id.eTpassword);
StaySignedIn = (CheckBox) findViewById(R.id.Cbstay);
bSubmit = (Button) findViewById(R.id.bLogIn);
bSubmit.setOnClickListener(this);
File file = getBaseContext().getFileStreamPath(FILENAME);
if (file.exists()) {
Intent i = new Intent(LogIn.this, ChatService.class);
startActivity(i);
}
// if if file exist close bracket
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch bracket
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // end of catch
} // create ends here
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.bLogIn:
String user = eTuser.getText().toString();
String pass = eTpassword.getText().toString();
Bundle userandpass = new Bundle();
userandpass.putString("user", user);
userandpass.putString("pass", pass);
Intent login = new Intent(LogIn.this, logincheck.class);
login.putExtra("pass", user);
login.putExtra("user", pass);
startActivity(login);
if (StaySignedIn.isChecked())
;
String userstaysignedin = eTuser.getText().toString();
String passstaysignedin = eTpassword.getText().toString();
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(userstaysignedin.getBytes());
fos.write(passstaysignedin.getBytes());
fos.close();
} catch (IOException e) {
// end of try bracket, before the Catch IOExceptions e.
e.printStackTrace();
} // end of catch bracket
} // switch and case ends here
}// Click ends here
}// main class ends here
Class B( Class that loads the data.)
public class ChatService extends Activity {
String collected = null;
FileInputStream fis = null;
String FILENAME;
TextView userandpass;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.chatservice);
userandpass = (TextView) findViewById(R.id.textView1);
try {
fis = openFileInput(FILENAME);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte[] dataArray = null;
try {
dataArray = new byte[fis.available()];
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (fis.read(dataArray) != -1)
;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
{
// while statement
}
userandpass.setText(collected);
}// create ends here
}// class ends here
LogCat:
03-03 21:03:34.725: E/AndroidRuntime(279): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gta5news.bananaphone/com.gta5news.bananaphone.ChatService}: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Handler.dispatchMessage(Handler.java:99)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.os.Looper.loop(Looper.java:123)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): at java.lang.reflect.Method.invoke(Method.java:521)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-03 21:03:34.725: E/AndroidRuntime(279): at dalvik.system.NativeStart.main(Native Method)
03-03 21:03:34.725: E/AndroidRuntime(279): Caused by: java.lang.NullPointerException
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.makeFilename(ContextImpl.java:1599)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ContextImpl.openFileInput(ContextImpl.java:399)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.content.ContextWrapper.openFileInput(ContextWrapper.java:152)
03-03 21:03:34.725: E/AndroidRuntime(279): at com.gta5news.bananaphone.ChatService.onCreate(ChatService.java:25)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-03 21:03:34.725: E/AndroidRuntime(279): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-03 21:03:34.725: E/AndroidRuntime(279): ... 11 more
The FILENAME string in the ChatService class is null. So you get a NullPointerException when you try to load a file using fis = openFileInput(FILENAME).
Also, your read loop throws away the data:
while (fis.read(dataArray) != -1)
;
It needs to collect the data and set the value of your collected String.
The stack trace tells you everything you need to know.
The error is a NullPointerException (meaning that you pass a null reference to a method expecting a non null reference, or that you call a method on a null reference).
The error occurs inside some android code (ContextWrapper.openFileInput()), which is called by your ChatService.onCreate() method, on line 25.
The line 25 is the following line:
fis = openFileInput(FILENAME);
So the error is clear: FILENAME is null. You haven't initialized it before this method is called.
I'm not sure about your program flow and if your two classes are running in the same thread, but it looks like you have a program flow issue. You are trying to open the file and getting a NullPointerException. Make sure the file is created and you have the correct reference to it before attempting to read.
If they are running in separate threads then you might try something like this:
try {
int waitTries=1;
fis = openFileInput(FILENAME);
while(fis.available()<EXPECTEDSIZE && waitTries++<10)
Tread.sleep(50);
}
If you know how large the file should be (EXPECTEDSIZE is some constant you will set), then this may be what you are looking for.

Categories