Android Intent Always Crashes - java

I am trying to switch activities in android using intent. However no matter what I do, this always crashes. I read countless topics on the same question, none of which have helped. So I Am Forced to ask my own question.
When I Run This, the app simply crashes after the 4 seconds are up
Here Is My First Activity (Splash):
package com.redflamedeveloper.torch;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Splash extends Activity {
/** Called when the activity is first created. */
MediaPlayer mpSplash;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
mpSplash = MediaPlayer.create(this, R.raw.fire); //Splash Screen sound
mpSplash.start();
Thread logoTimer = new Thread(){ //4 Second Timer
public void run() {
try {
//Waits for 4 seconds
int logoTimer = 0;
while(logoTimer <4000){
sleep(100);
logoTimer = logoTimer + 100;
}
Intent intentMain = new Intent(Splash.this, Main.class);
startActivity(intentMain);
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
finish();
}
}
};
logoTimer.start(); //Starts the thread logoTimer
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mpSplash.release(); //ends sound
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
mpSplash.pause(); //pauses sound
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
mpSplash.start(); //Resumes sound
}
}
My Second Activity (Main):
package com.redflamedeveloper.torch;
import android.app.Activity;
import android.hardware.Camera.Parameters;
import android.hardware.Camera;
import android.os.Bundle;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.os.Handler;
/**
* Created by Sasha on 8/12/13.
*/
public class Main extends Activity implements OnClickListener{
private Camera mCamera;
boolean torch = false;
boolean flash = false;
private Handler mHander = new Handler();
private final Runnable mRunnable = new Runnable() {
public void run() {
while(flash) {
if (torch==false) {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
torch=true;
}
} else {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
torch=false;
}
}
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.main);
Button bTorch = (Button) findViewById(R.id.bTorch);
Button bFlash = (Button) findViewById(R.id.bFlash);
Button bHelp = (Button) findViewById(R.id.bHelp);
Button bMorse = (Button) findViewById(R.id.bMorse);
bTorch.setOnClickListener(this);
bFlash.setOnClickListener(this);
bHelp.setOnClickListener(this);
bMorse.setOnClickListener(this);
}
private void startStrobe() {
mHander.post(mRunnable);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.bTorch:
if (torch==false) {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
torch=true;
}
} else {
if( mCamera != null ){
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
torch=false;
}
}
break;
case R.id.bFlash:
flash=!flash;
startStrobe();
break;
case R.id.bHelp:
Parameters params = mCamera.getParameters();
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_TORCH );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
params.setFlashMode( Parameters.FLASH_MODE_OFF );
mCamera.setParameters( params );
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
break;
case R.id.bMorse:
Intent intentMorse = new Intent(Main.this, Morse.class);
Main.this.startActivity(intentMorse);
break;
}
}
}
And My Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.redflamedeveloper.torch"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="13"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.redflamedeveloper.torch.Splash"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main"
android:label="#string/app_name" >
</activity>
<activity
android:name=".Morse"
android:label="#string/app_name" >
</activity>
</application>
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
</manifest>
And Finally LogCat:
12-09 23:28:35.682 2110-2110/com.redflamedeveloper.torch W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40c47a68)
12-09 23:28:35.692 637-674/? E/android.os.Debug﹕ !#Dumpstate > dumpstate -k -t -n -z -d -o /data/log/dumpstate_app_error
12-09 23:28:35.692 2110-2110/com.redflamedeveloper.torch E/AndroidRuntime﹕ FATAL EXCEPTION: main
android.app.SuperNotCalledException: Activity {com.redflamedeveloper.torch/com.redflamedeveloper.torch.Main} did not call through to super.onCreate()
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1936)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
at dalvik.system.NativeStart.main(Native Method)
12-09 23:28:35.692 637-647/? W/ActivityManager﹕ Force finishing activity com.redflamedeveloper.torch/.Main
12-09 23:28:35.702 2144-2144/? I/dumpstate﹕ Check if stand-alone
12-09 23:28:35.712 2144-2144/? I/dumpstate﹕ begin
12-09 23:28:36.523 1268-1281/? E/MP-Decision﹕ DOWN Ld:54 Ns:1.100000 Ts:190 rq:0.000000 seq:196.000000
12-09 23:28:37.023 637-25450/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 637-25450/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getGsmLevel=4
12-09 23:28:37.023 771-771/? W/SignalStrength﹕ getLevel=4 (SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4)
12-09 23:28:37.023 771-771/? D/STATUSBAR-NetworkController﹕ onSignalStrengthsChanged signalStrength=SignalStrength: 14 0 -120 -160 -120 -1 -1 99 2147483647 2147483647 2147483647 2147483647 gsm|lte 0x4 level=4
12-09 23:28:37.023 637-884/? W/AlarmManager﹕ FACTORY_ON= 0
12-09 23:28:37.774 1268-1281/? E/MP-Decision﹕ UP Ld:61 Nw:1.990000 Tw:140 rq:2.300000 seq:147.000000
12-09 23:28:38.164 329-329/? E/SMD﹕ DCD ON
12-09 23:28:38.665 336-582/? D/AudioStreamOutALSA﹕ standby
12-09 23:28:38.665 336-582/? D/ALSAModule﹕ s_standby: handle 0x10454c0 h 0x0
12-09 23:28:38.665 336-582/? E/ALSAModule﹕ s_standby handle h 0x10e2180
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _verb value Inactive
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ set_use_case_ident_for_all_devices(): HiFi
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for HiFi enable 0
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for HiFiSpeaker enable 0
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _disdev value Main Mic
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ disdev: device Main Mic not enabled or not active, no need to disable
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ snd_use_case_set(): uc_mgr 0xfe8968 identifier _disdev value Speaker
12-09 23:28:38.865 336-582/? E/alsa_ucm﹕ Empty list
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ set current output is none
12-09 23:28:38.865 336-582/? D/alsa_ucm﹕ Set mixer controls for Speaker enable 0
12-09 23:28:39.075 1268-1281/? E/MP-Decision﹕ DOWN Ld:18 Ns:1.100000 Ts:190 rq:0.000000 seq:196.000000
12-09 23:28:40.557 319-542/? D/VoldCmdListener﹕ asec list
12-09 23:28:40.557 319-542/? D/VoldCmdListener﹕ CommandListener::AsecCmd::runCommand -> --
12-09 23:28:40.707 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.707 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.707 637-698/? D/DEFERED_APP_VISIBILITY﹕ tweaking closing app
12-09 23:28:40.707 637-698/? D/DEFERED_APP_VISIBILITY﹕ tweaking closing app
12-09 23:28:40.717 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.737 637-698/? D/KeyguardViewMediator﹕ setHidden false
12-09 23:28:40.747 637-698/? D/KeyguardViewMediator﹕ setHidden false
I am At my wits end. All help will be greatly appreciated
Sasha

You need to call super.onCreate(savedInstanceState); in the onCreate method of Main.class

Your second activity does not call super.onCreate(savedInstanceState). It says so in the logcat

Related

Calling MediaRecorder crashes app in AndroidStudio

I am trying to create a class that sets and starts audio recording but as soon as I click the button the app crashes. Iv isolated the problem to where I set the parameters for the MediRecorder.
private void startRec() throws IOException {
if (mrecorder!=null)
mrecorder.release();
mrecorder= new MediaRecorder();
-> mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
/*
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mrecorder.setOutputFile(MFILE);
mrecorder.prepare();
mrecorder.start();
*/
}
It crashes when the line with the arrow above the start of the notes is executed. I added the following permission to the manifest as well:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
Any help much appreciated.
UPDATED LOGCAT
[ 05-12 00:39:13.299 30086:30158 D/ ]
ro.exynos.dss isEnabled: 0
05-12 00:39:13.309 30086-30158/record66.record6 D/mali_winsys: new_window_surface returns 0x3000, [1440x2560]-format:1
05-12 00:39:13.319 30086-30086/record66.record6 W/DisplayListCanvas: DisplayListCanvas is started on unbinded RenderNode (without mOwningView)
05-12 00:39:13.319 30086-30158/record66.record6 D/libGLESv1: DTS_GLAPI : DTS is not allowed for Package : record66.record6
05-12 00:39:13.359 30086-30086/record66.record6 D/ViewRootImpl: MSG_RESIZED_REPORT: ci=Rect(0, 96 - 0, 0) vi=Rect(0, 96 - 0, 0) or=1
05-12 00:39:13.389 30086-30086/record66.record6 I/Timeline: Timeline: Activity_idle id: android.os.BinderProxy#682466c time:234401322
05-12 00:39:15.749 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 0
05-12 00:39:15.879 30086-30086/record66.record6 D/ViewRootImpl: ViewPostImeInputStage processPointer 1
05-12 00:39:15.929 30086-30086/record66.record6 D/AndroidRuntime: Shutting down VM
05-12 00:39:15.939 30086-30086/record66.record6 E/AndroidRuntime: FATAL EXCEPTION: main
Process: record66.record6, PID: 30086
java.lang.RuntimeException: setAudioSource failed.
at android.media.MediaRecorder._setAudioSource(Native Method)
at android.media.MediaRecorder.setAudioSource(MediaRecorder.java:488)
at record66.record6.MainActivity.startRec(MainActivity.java:58)
at record66.record6.MainActivity.onClick(MainActivity.java:94)
at android.view.View.performClick(View.java:5697)
at android.widget.TextView.performClick(TextView.java:10815)
at android.view.View$PerformClick.run(View.java:22526)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:158)
at android.app.ActivityThread.main(ActivityThread.java:7229)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
05-12 00:39:17.909 30086-30086/record66.record6 I/Process: Sending signal. PID: 30086 SIG: 9
Please see what logcat is.
And let us know what error you are getting. So can help.
package com.example.dhrupalpatel.test;
import android.app.Activity;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import java.io.File;
import java.io.IOException;
public class MainActivity extends Activity implements View.OnClickListener{
MediaRecorder mrecorder;
boolean mStartRecording=false;
Button start, stop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start =(Button)findViewById(R.id.start);
stop =(Button)findViewById(R.id.stop);
start.setOnClickListener(this);
stop.setOnClickListener(this);
}
private void startRec() throws IOException {
boolean mExternalStorageAvailable = false;
boolean mExternalStorageWriteable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = mExternalStorageWriteable = true;
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
mExternalStorageAvailable = true;
mExternalStorageWriteable = false;
} else {
// Something else is wrong. It may be one of many other states, but all we need
// to know is we can neither read nor write
mExternalStorageAvailable = mExternalStorageWriteable = false;
}
File sdCardDirectory= Environment
.getExternalStorageDirectory();
if(mExternalStorageAvailable && !sdCardDirectory.exists())
{
sdCardDirectory.mkdir();
}
File f= new File(sdCardDirectory.getPath()+"/"+System.currentTimeMillis()+".mp3");
if( mrecorder == null ) {
mrecorder = new MediaRecorder();
mrecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mrecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mrecorder.setOutputFile(f.getPath());
mrecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
}
if(!mStartRecording) {
try {
mrecorder.prepare();
mrecorder.start();
mStartRecording = true;
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRec() throws IOException {
if(mStartRecording) {
mStartRecording = false;
mrecorder.stop();
mrecorder.reset();
mrecorder.release();
mrecorder = null;
}
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.start:
try {
startRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stop:
try {
stopRec();
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
}

service cant be started thread exiting with uncaught exception (group=0xb2a3fba8)

Updated 13-10-2014: added togglegps.class
Hello i have a simple proyect with two buttons to start and stop a gps service.
as soon as i click the start button to start the service the aplication shuts down.
i get the following logcat
10-12 14:23:18.424: I/Choreographer(1300): Skipped 36 frames! The application may be doing too much work on its main thread.
10-12 14:23:18.504: D/gralloc_goldfish(1300): Emulator without GPU emulation detected.
10-12 14:24:07.794: E/Google(1300): Service Created
10-12 14:24:07.834: D/AndroidRuntime(1300): Shutting down VM
10-12 14:24:07.864: W/dalvikvm(1300): threadid=1: thread exiting with uncaught exception (group=0xb2a3fba8)
10-12 14:24:07.894: E/AndroidRuntime(1300): FATAL EXCEPTION: main
10-12 14:24:07.894: E/AndroidRuntime(1300): Process: com.example.newtrack, PID: 1300
10-12 14:24:07.894: E/AndroidRuntime(1300): java.lang.RuntimeException: Unable to start service com.example.newtrack.AndroidLocationServices#b2d1b4e8 with Intent { cmp=com.example.newtrack/.AndroidLocationServices }: java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=1300, uid=10052
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2719)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityThread.access$2100(ActivityThread.java:135)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1293)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.os.Handler.dispatchMessage(Handler.java:102)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.os.Looper.loop(Looper.java:136)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-12 14:24:07.894: E/AndroidRuntime(1300): at java.lang.reflect.Method.invokeNative(Native Method)
10-12 14:24:07.894: E/AndroidRuntime(1300): at java.lang.reflect.Method.invoke(Method.java:515)
10-12 14:24:07.894: E/AndroidRuntime(1300): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-12 14:24:07.894: E/AndroidRuntime(1300): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-12 14:24:07.894: E/AndroidRuntime(1300): at dalvik.system.NativeStart.main(Native Method)
10-12 14:24:07.894: E/AndroidRuntime(1300): Caused by: java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=1300, uid=10052
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.os.Parcel.readException(Parcel.java:1465)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.os.Parcel.readException(Parcel.java:1419)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityManagerProxy.broadcastIntent(ActivityManagerNative.java:2373)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ContextImpl.sendBroadcast(ContextImpl.java:1127)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.content.ContextWrapper.sendBroadcast(ContextWrapper.java:365)
10-12 14:24:07.894: E/AndroidRuntime(1300): at com.example.newtrack.ToggleGPS.turnGPSOn(ToggleGPS.java:53)
10-12 14:24:07.894: E/AndroidRuntime(1300): at com.example.newtrack.AndroidLocationServices.onStart(AndroidLocationServices.java:58)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.Service.onStartCommand(Service.java:450)
10-12 14:24:07.894: E/AndroidRuntime(1300): at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2702)
10-12 14:24:07.894: E/AndroidRuntime(1300): ... 10 more
10-12 14:24:11.544: I/Process(1300): Sending signal. PID: 1300 SIG: 9
what can be the causes that i can not start the service?
what can i add to the mainactivity?
the manifest has all the permissions and the services are registered
the following is my mainactivity
package com.example.newtrack;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//start the service
public void onClickStartServie(View V)
{
//start the service from here //MyService is your service class name
startService(new Intent(this, AndroidLocationServices.class));
}
//Stop the started service
public void onClickStopService(View V)
{
//Stop the running service from here//MyService is your service class name
//Service will only stop if it is already running.
stopService(new Intent(this, AndroidLocationServices.class));
}
}
as stated above it has only two onclicks for start and stop service
the main service that is called is the following
package com.example.newtrack;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
public class AndroidLocationServices extends Service {
WakeLock wakeLock;
private LocationManager locationManager;
public AndroidLocationServices() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
PowerManager pm = (PowerManager) getSystemService(this.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
// Toast.makeText(getApplicationContext(), "Service Created",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Created");
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
new ToggleGPS(getApplicationContext()).turnGPSOn();
// Toast.makeText(getApplicationContext(), "Service Started",
// Toast.LENGTH_SHORT).show();
Log.e("Google", "Service Started");
locationManager = (LocationManager) getApplicationContext()
.getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, listener);
}
private LocationListener listener = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
Log.e("Google", "Location Changed");
if (location == null)
return;
if (isConnectingToInternet(getApplicationContext())) {
JSONArray jsonArray = new JSONArray();
JSONObject jsonObject = new JSONObject();
try {
Log.e("latitude", location.getLatitude() + "");
Log.e("longitude", location.getLongitude() + "");
jsonObject.put("latitude", location.getLatitude());
jsonObject.put("longitude", location.getLongitude());
jsonArray.put(jsonObject);
Log.e("request", jsonArray.toString());
new LocationWebService().execute(new String[] {
Constants.TRACK_URL, jsonArray.toString() });
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
};
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
new ToggleGPS(getApplicationContext()).turnGPSOff();
wakeLock.release();
}
public static boolean isConnectingToInternet(Context _context) {
ConnectivityManager connectivity = (ConnectivityManager) _context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
return false;
}
}
i also post my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.newtrack"
android:versionCode="1"
android:versionName="1.0" >
<!-- Permissions to record locations -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.newtrack.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.newtrack.AndroidLocationServices" />
<receiver android:name="AlarmReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
the class i use to turn on gps is the following
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.provider.Settings;
/**
*
* #author Atish Agrawal
*
*/
public class ToggleGPS {
Context context;
public ToggleGPS(Context context) {
this.context = context;
}
public boolean canToggleGPS() {
PackageManager pacman = context.getPackageManager();
PackageInfo pacInfo = null;
try {
pacInfo = pacman.getPackageInfo("com.android.settings",
PackageManager.GET_RECEIVERS);
} catch (NameNotFoundException e) {
return false; // package not found
}
if (pacInfo != null) {
for (ActivityInfo actInfo : pacInfo.receivers) {
// test if recevier is exported. if so, we can toggle GPS.
if (actInfo.name
.equals("com.android.settings.widget.SettingsAppWidgetProvider")
&& actInfo.exported) {
return true;
}
}
}
return false; // default
}
public void turnGPSOn() {
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
this.context.sendBroadcast(intent);
String provider = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (!provider.contains("gps")) {
// if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.context.sendBroadcast(poke);
}
}
public void turnGPSOff() {
String provider = Settings.Secure.getString(
context.getContentResolver(),
Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if (provider.contains("gps")) { // if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings",
"com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse("3"));
this.context.sendBroadcast(poke);
}
}
}
if possible please indicate what i should change - following comments made by #neo
any comments are apreciated
thank you very much.
You can see that the exception line below in the trace:
10-12 14:24:07.894: E/AndroidRuntime(1300): at com.example.newtrack.ToggleGPS.turnGPSOn(ToggleGPS.java:53)
This was a bug before that let you enable the settings by sending the broadcast(that is fixed now). So you will need to ask the User to manually enable the GPS settings using the Intent given below.
startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

Unable to instantiate application java.lang.RuntimeException:...BackupDB cannot be cast to android.app.Application

MANIFEST:(partial view)
MainActivity, program immediately terminates and issues the messages in the Log.
It should have started showing the buttons to select options to continue execution.
After days of researching this forum, I found postings that suggest to place the BackupDb inside the application in the Manifest.
After doing that, I ended up with the message in the log.
Having exhausted my research venues, I'd like to know what could be the problem and how to solve it.
MANIFEST:(partial view)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.peter.databasetest"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<supports-screens
android:xlargeScreens="true"
android:largeScreens="true"
android:normalScreens="true"
android:smallScreens="false"
/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
**android:name="com.peter.databasetest.BackupDB">**
<activity
android:name="com.peter.databasetest.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".CheckDatabase"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKDATABASE" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".CheckSDcard"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.CHECKSDCARD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.peter.databasetest.Insert"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.INSERT" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity: Calls checkSDcard and CheckDatabase. Checks if there is SDCard present and the database in main, exists.
public class MainActivity extends Activity implements OnClickListener {
DBAdapter db;
Button insertButton; //ADD A NEW RECORD
Button listAllButton; //LIST ALL
Button cancelButton; //CANCEL PGM
Button backupDbButton; //REQUEST BACKUP DB TO SDCARD
Button restoreButton; //RESTORE DB FROM SDCARD TO MAIN
Button memsizeButton; //SHOW MEMORY SIZES ON DEVICE
int retcode;
int chk;
String message;
public Context context;
public static final String NO_DB ="Database does not exist. Backup is not possible";
public static final String DB_PB ="ERROR- Check log";
public static final String UNWR_SDCARD ="Your SDCard must be set to writable. Check the card lock";
public static final String NO_SDCARD ="No SDcard detected. No backup is possible";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
static final int SD_CHECK = 1;
static final int DB_CHECK = 2;
static final int BK_CHECK = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insertButton = (Button) findViewById(R.id.insertButton);
listAllButton = (Button) findViewById(R.id.listAllButton);
cancelButton = (Button) findViewById(R.id.cancelButton);
backupDbButton = (Button) findViewById(R.id.backupDbButton);
restoreButton = (Button) findViewById(R.id.restoreButton);
memsizeButton = (Button) findViewById(R.id. memsizeButton);
insertButton.setOnClickListener(this); //insert record into DB
listAllButton.setOnClickListener(this); //list ALL records from DB
cancelButton.setOnClickListener(this); //cancel the program
backupDbButton.setOnClickListener(this); //request backup to sdcard
restoreButton.setOnClickListener(this); //request restore from sdcard
memsizeButton.setOnClickListener(this); //Get Meory sizes
public void onClick(View v ) {
if (v == insertButton) {
startActivity(new Intent(getApplicationContext(), Insert.class));
}else if (v == listAllButton){
startActivity (new Intent(MainActivity.this, ListDr.class));
}else if (v == backupDbButton){
**Intent checksd = new Intent(this,CheckSDcard.class);**
**startActivityForResult(checksd, SD_CHECK);**
}else if (v == restoreButton) {
startActivity (new Intent(MainActivity.this,RestoreDB.class));
}else if (v == memsizeButton) {
startActivity (new Intent(MainActivity.this,GetMemorySizes.class));
}else if (v == cancelButton){
finish();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == SD_CHECK && resultCode == RESULT_OK) {
Intent checkdb = new Intent(MainActivity.this,CheckDatabase.class);
startActivityForResult(checkdb, DB_CHECK);
}else if (requestCode == DB_CHECK && resultCode == RESULT_OK){
**Intent backup = new Intent(MainActivity.this,BackupDB.class);**
**startActivityForResult(backup, BK_CHECK);**
}else if (requestCode == BK_CHECK && resultCode == RESULT_OK){
message = BKP_OK;
SendMessageDialog(message);
finish();
}
if(resultCode == RESULT_CANCELED && resultCode == -1){
message = NO_DB;
SendMessageDialog(message);
finish();
}else if(resultCode == RESULT_CANCELED && resultCode == -2) {
message = DB_PB;
SendMessageDialog(message);
finish();
}
}
BackupDb: Copies the database to the SDCARD.
package com.peter.databasetest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import com.peter.databasetest.DBAdapter;
public class BackupDB extends AsyncTask<Void, Void, Integer> {
DBAdapter db;
intrc= -10;
intretcode;
intchk;
Stringmessage;
String mypackage;
public Context context;
public static String FOLDER_NAME = "DBfolder";
public static final String DATABASE_NAME = "UserDB.db";
public static final String DATABASE_BACKUP= "UserDB.db";
public static final String BKP_OK = "Backup was SUCCESSFUL.";
public static final String BKP_NOK = "Backup FAILED. ";
#Override
protected void onPreExecute() {
// GET PACKAGE NAME
mypackage = context.getApplicationContext().getPackageName() ;
}
// START BACKUP TO SDCARD
#Override
protected Integer doInBackground(Void... params) {
// DOING BACKUP
Log.i("00000" , "STARTING BACKUP...BACKUP ");
File sd = Environment.getExternalStorageDirectory();
File data = Environment.getDataDirectory();
CREATE A FOLDER /mnt/sdcard<packagename>FOLDER_NAME if it does not exist
File folder = new File(Environment.getExternalStorageDirectory()
+ "/"
+ mypackage
+ "/"
+ FOLDER_NAME);
if(!folder.exists()) {
if (folder.mkdirs()) ;
}
// GET THE PATH OF THE BACKUP ON THE SDCARD
FilefileBackupDir = new File(Environment.getExternalStorageDirectory()
+ "/"
+mypackage
+ "/"
+ FOLDER_NAME
+"/"
+ DATABASE_BACKUP) ;
// IF WE HAVE A BACKUP ON SDCARD, DELETE IT TO MAKE ROOM FOR THE NEW BACKUP
if (fileBackupDir.exists()) {
fileBackupDir.delete();
}else {
* DO NOTHING */
}
// GET CURRENT DB PATH FOR THE COPY
String currentDBPath = "/data/" + mypackage + "/databases/"+ DATABASE_NAME;
// GET CURRENT DB PATH FOR THE BACKUP
String backupDBPath = "/" + mypackage + "/" +FOLDER_NAME + "/" + DATABASE_BACKUP;
FilecurrDB = new File(data, currentDBPath) ;
FilebkpDB = new File(sd, backupDBPath);
FileChannel from = null;
try {
from = new FileInputStream(currDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
FileChannel to = null;
try {
to = new FileOutputStream(bkpDB).getChannel();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
to.transferFrom(from, 0, from.size());
} catch (IOException e) {
e.printStackTrace();
}
try {
from.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
to.close();
} catch (IOException e) {
e.printStackTrace();
}
retcode = 0;
returnretcode;
// end DoInBackgroung
protectedvoid onPostExecute(Integer retcode, String message) {
if(retcode == 0) {
message = BKP_OK;
SendMessageDialog(message);
}else {
message = BKP_NOK;
SendMessageDialog(message);
}
}
public void SendMessageDialog(String message) {
if (message == BKP_OK ) {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.ecg)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}else {
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("My Database")
.setMessage(message) // Title of the dialog
.setCancelable(true) // Does allow the use of Back Button on the hardware
.setIcon(R.drawable.bad)// da picture
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
}
}
}
Logcat:
02-12 07:36:06.015: E/AndroidRuntime(987): FATAL EXCEPTION: main
02-12 07:36:06.015: E/AndroidRuntime(987): java.lang.RuntimeException: Unable to instantiate application com.peter.databasetest.BackupDB:
: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:501)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4124)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.access$1300(ActivityThread.java:130)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1255)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.os.Looper.loop(Looper.java:137)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 07:36:06.015: E/AndroidRuntime(987): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 07:36:06.015: E/AndroidRuntime(987): at dalvik.system.NativeStart.main(Native Method)
02-12 07:36:06.015: E/AndroidRuntime(987): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Application
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:982)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.Instrumentation.newApplication(Instrumentation.java:967)
02-12 07:36:06.015: E/AndroidRuntime(987): at android.app.LoadedApk.makeApplication(LoadedApk.java:496)
02-12 07:36:06.015: E/AndroidRuntime(987): ... 11 more
Comment:
I removed the BackupDb from the application and reinstated it as activity.
<activity
android:name=".BackupDB"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.peter.databasetest.BACKUPDB" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
The program now brings up the buttons as expected, but when trying the backup I still get the same message as in the earlier log. (Catch-22?)
Most current log:
02-12 13:00:16.569: W/dalvikvm(30656): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
02-12 13:00:16.650: E/AndroidRuntime(30656): FATAL EXCEPTION: main
02-12 13:00:16.650: E/AndroidRuntime(30656): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.peter.databasetest/com.peter.databasetest.BackupDB}: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.access$600(ActivityThread.java:130)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Handler.dispatchMessage(Handler.java:99)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.os.Looper.loop(Looper.java:137)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.main(ActivityThread.java:4745)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invokeNative(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): at java.lang.reflect.Method.invoke(Method.java:511)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
02-12 13:00:16.650: E/AndroidRuntime(30656): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-12 13:00:16.650: E/AndroidRuntime(30656): at dalvik.system.NativeStart.main(Native Method)
02-12 13:00:16.650: E/AndroidRuntime(30656): Caused by: java.lang.ClassCastException: com.peter.databasetest.BackupDB cannot be cast to android.app.Activity
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
02-12 13:00:16.650: E/AndroidRuntime(30656): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
02-12 13:00:16.650: E/AndroidRuntime(30656): ... 11 more
>Question:
>Is there any known limitation calling an AsyncTask by way of startActivityForResult?
>Could this be a factor?
The problem is in the Manifest file, you are setting your application:name to be te BackupDB class and this class is only an AsyncTask not an Application.
As can be seen on the explanation of "android:name":
An optional name of a class implementing the overall
android.app.Application for this package. [string]

"Unfortunately <myApp> has Stopeed" after running for 45sec on Nexus4

I'm a beginner in Android App Development. Using eclipse to develop a simple Bluetooth shaker app. Tried it on my phone and runs perfectly fine for about 30 seconds. And then it closes saying "Unfortunately TheApp has stopped".
This app is supposed to switch on Bluetooth with a shake and play a beep sound(pop.mp3)
Please Help.
main.java>
public class BlueActivity extends Activity implements SensorListener, OnCompletionListener {
Button a, b,d;
EditText e;
TextView f;
protected final int id=1;
BluetoothAdapter bt;
public MediaPlayer m;
private SensorManager sensorMgr;
private long lastUpdate = -1;
private float x, y, z;
private float last_x, last_y, last_z;
private static final int SHAKE_THRESHOLD = 3000;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_blue);
a=(Button)findViewById(R.id.button1);
b=(Button)findViewById(R.id.button2);
d=(Button)findViewById(R.id.button3);
f=(TextView)findViewById(R.id.textView1);
e=(EditText)findViewById(R.id.editText1);
e.setFocusable(false);
b.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = bt.getAddress();
e.setText(s);
}
});
a.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i, id);
}
});
d.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Uri uri = Uri.parse("http://www.gamerspitch.com");
Intent in = new Intent(Intent.ACTION_VIEW, uri);
startActivity(in);
}
});
sensorMgr = (SensorManager) getSystemService(SENSOR_SERVICE);
boolean accelSupported sensorMgr.registerListener(this,SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
bt= BluetoothAdapter.getDefaultAdapter();
if (!accelSupported) {
// on accelerometer on this device
sensorMgr.unregisterListener(this,SensorManager.SENSOR_ACCELEROMETER);
}
}
protected void onPause() {
m = MediaPlayer.create(this, R.raw.pop);
m.setOnCompletionListener(this);
if (sensorMgr != null) {
sensorMgr.registerListener(this,SensorManager.SENSOR_ACCELEROMETER);
sensorMgr = null;
}
if(bt.isEnabled())
m.start();
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.blue, menu);
return true;
}
#Override
public void onAccuracyChanged(int sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(int sensor, float[] values) {
// TODO Auto-generated method stub
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
long curTime = System.currentTimeMillis();
// only allow one update every 100ms.
if ((curTime - lastUpdate)> 100) {
long diffTime = (curTime - lastUpdate);
lastUpdate = curTime;
m = MediaPlayer.create(this, R.raw.pop);
m.setOnCompletionListener(this);
x = values[SensorManager.DATA_X];
y = values[SensorManager.DATA_Y];
z = values[SensorManager.DATA_Z];
float speed=Math.abs(x+y+z - last_x - last_y - last_z)/ diffTime*10000;
if (speed > SHAKE_THRESHOLD) {
// yes, this is a shake action! Do something about it!
//Toast.makeText(this, "Shaking", Toast.LENGTH_SHORT).show();
if(!bt.isEnabled())
{
bt.enable();
f.setText("ON");
m.start();
}
else
{
bt.disable();
f.setText("OFF");
}
}
last_x = x;
last_y = y;
last_z = z;
}
}
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
}
}
Does it have something to do with Exception Handling? because I'm very bad at that.
Manifext.xml >
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gamerspitch.easybluetooth"
android:anyDensity="false"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<application
android:allowBackup="true"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.gamerspitch.easybluetooth.SplashScreen"
android:label="#string/title_activity_splash_screen"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.gamerspitch.easybluetooth.BlueActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
The logcat >
`08-08 16:03:33.112: E/SensorManager(4428): Exception dispatching input event.
08-08 16:03:33.112: E/AndroidRuntime(4428): FATAL EXCEPTION: main
08-08 16:03:33.112: E/AndroidRuntime(4428): java.lang.NullPointerException
08-08 16:03:33.112: E/AndroidRuntime(4428): at com.gamerspitch.easybluetooth.BlueActivity.onSensorChanged(BlueActivity.java:163)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.hardware.LegacySensorManager$LegacyListener.onSensorChanged(LegacySensorManager.jav a:274)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:371)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.os.MessageQueue.nativePollOnce(Native Method)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.os.MessageQueue.next(MessageQueue.java:132)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.os.Looper.loop(Looper.java:124)
08-08 16:03:33.112: E/AndroidRuntime(4428): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-08 16:03:33.112: E/AndroidRuntime(4428): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 16:03:33.112: E/AndroidRuntime(4428): at java.lang.reflect.Method.invoke(Method.java:525)
08-08 16:03:33.112: E/AndroidRuntime(4428): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-08 16:03:33.112: E/AndroidRuntime(4428): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-08 16:03:33.112: E/AndroidRuntime(4428): at dalvik.system.NativeStart.main(Native Method)
`
Thank you in Advance.
It's hard to say what exactly is null without knowing which line is 163, but a guess would be that there has been an issue while creating the MediaPlayer object here:
m = MediaPlayer.create(this, R.raw.pop);
m.setOnCompletionListener(this);
As the documentation for create states: a MediaPlayer object, or null if creation failed

Application code used to work but now crashes

Thing is my application used to run PERFECTLY but then i wanted to change packages names and classes names so i created another project and copy pasted my code and did the changes there. no error in eclipse but app crashes now !! here's whats my app is about:
public class LocationMobileUser implements LocationListener {
Context gContext;
boolean gps_enabled=false;
boolean network_enabled=false;
public LocationMobileUser(Context gContext){
this.gContext = gContext;
}
public static final String URL =
"http://www.ip2phrase.com/ip2phrase.asp?template=%20%3CISP%3E";
public void XML (View view) {
GetXMLTask task = new GetXMLTask();
task.execute(new String[] { URL });
}
public class GetXMLTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String output = null;
for (String url : urls) {
output = getOutputFromUrl(url);
}
return output;
}
public String getOutputFromUrl(String url) {
StringBuffer output = new StringBuffer("");
int x =1;
try {
InputStream stream = getHttpConnection(url);
LineNumberReader lnr = new LineNumberReader(new InputStreamReader(stream));
String line = "";
int lineNo;
for (lineNo = 1; lineNo < 90; lineNo++) {
if (lineNo == x) {
line = lnr.readLine();
//output.append(line);
Pattern p = Pattern.compile(">(.*?)<");
Matcher m = p.matcher(line);
if (m.find()) {
output.append(m.group(1)); // => "isp"
}
} else
lnr.readLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return output.toString();
}
// Makes HttpURLConnection and returns InputStream
public InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
public String getSimOperator() {
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
String operator = telephonyManager.getSimOperatorName();
return operator;
}
public GsmCellLocation getCellLocation() {
//String Context=Context.Telephony_SERVICE;
TelephonyManager telephonyManager = (TelephonyManager)gContext.getSystemService(Context.TELEPHONY_SERVICE);
GsmCellLocation CellLocation = (GsmCellLocation)telephonyManager.getCellLocation();
return CellLocation;
}
public Location getLocation(){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 1, this);
return location;
}
public String getProvider(Location location){
String provider = null;
LocationManager locationManager;
Location gps_loc=null;
String context = Context.LOCATION_SERVICE;
locationManager = (LocationManager)gContext.getSystemService(context);
gps_loc=locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
try{gps_enabled=locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
try{network_enabled=locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
if(gps_enabled && gps_loc != null ){
provider = LocationManager.GPS_PROVIDER;
}
else{
provider = LocationManager.NETWORK_PROVIDER;
}
return provider;
}
public String CellLacLocation(GsmCellLocation CellLocation){
String cidlacString;
if (CellLocation != null) {
int cid = CellLocation.getCid();
int lac = CellLocation.getLac();
cidlacString = "CellID:" + cid + "\nLAC:" + lac;}
else {
cidlacString="No Cell Location Available";
}
return cidlacString;
}
public String updateWithNewLocation(Location location) {
String latLongString;
if (location != null){
double lat = location.getLatitude();
double lng = location.getLongitude();
latLongString = "Latitude:" + lat + "\nLongitude:" + lng;
}else{
latLongString = "No Location available";
}
return latLongString;
}
#Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
}
this app will be exported into a JAR file and then included into another app as a library using build path; and here's what i wrote in this new app:
public class LocationTheApp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LocationMobileUser LMU = new LocationMobileUser (this);
Location location = LMU.getLocation();
GsmCellLocation CellLocation = LMU.getCellLocation();
String URL = LocationMobileUser.URL;
LocationMobileUser.GetXMLTask xmlp = LMU.new GetXMLTask();
String Provider = LMU.getProvider(location);
String isp = xmlp.getOutputFromUrl(URL);
String latLongString = LMU.updateWithNewLocation(location);
String cidlacString = LMU.CellLacLocation(CellLocation);
String operator = LMU.getSimOperator();
TextView myLocationText = (TextView)findViewById(R.id.myLocationText);
myLocationText.setText("Your current GPS position is:\n" + latLongString);
TextView myprovider = (TextView)findViewById(R.id.myprovider);
myprovider.setText("\nYour GPS position is provided by:\n" + Provider);
TextView myCellLocation = (TextView)findViewById(R.id.mycelllocation);
myCellLocation.setText("\nYour current Cell position is:\n" + cidlacString);
TextView myOperator = (TextView)findViewById(R.id.myoperator);
myOperator.setText("\nYour GSM operator is:\n" + operator);
TextView myispText = (TextView)findViewById(R.id.myispText);
myispText.setText("\nYour current ISP is:\n" + isp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Code contains no errors !!
if its any use here's my Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.locationmobileuser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Tried to toggle the package name in the Manifest between locationmobileuser and locationtheapp but still app crashes !!
As i said used to work like a charm in my previous projects !!
LOG:
06-18 05:36:54.502: E/Trace(992): error opening trace file: No such file or directory (2)
06-18 05:36:54.852: D/dalvikvm(992): newInstance failed: no <init>()
06-18 05:36:54.862: D/AndroidRuntime(992): Shutting down VM
06-18 05:36:54.862: W/dalvikvm(992): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
06-18 05:36:55.002: E/AndroidRuntime(992): FATAL EXCEPTION: main
06-18 05:36:55.002: E/AndroidRuntime(992): java.lang.RuntimeException: Unable toinstantiate activity ComponentInfo{com.example.locationmobileuser/com.example.locationmobileuser.LocationMobileUser}: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2106)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Handler.dispatchMessage(Handler.java:99)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.os.Looper.loop(Looper.java:137)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invokeNative(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.reflect.Method.invoke(Method.java:511)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-18 05:36:55.002: E/AndroidRuntime(992): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-18 05:36:55.002: E/AndroidRuntime(992): at dalvik.system.NativeStart.main(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): Caused by: java.lang.InstantiationException: can't instantiate class com.example.locationmobileuser.LocationMobileUser; no empty constructor
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstanceImpl(Native Method)
06-18 05:36:55.002: E/AndroidRuntime(992): at java.lang.Class.newInstance(Class.java:1319)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.Instrumentation.newActivity(Instrumentation.java:1054)
06-18 05:36:55.002: E/AndroidRuntime(992): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2097)
06-18 05:36:55.002: E/AndroidRuntime(992): ... 11 more
Any help would be really appreciated !!
see the package name of menifest
package="com.example.locationmobileuser
and activity package name both should be same change this package
<activity
android:name="com.example.locationtheapp.LocationTheApp"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
you need to add empty constructor in your locationmobileuser class.
public LocationMobileUser(){
}
don't need to do all these things , just go to old project and right click on the project ->> refactor to rename project name or package name

Categories