I am trying to make an application that passes through the audio samples obtained at the microphone to the speaker. This is the source code:
public class MainActivity extends Activity {
AudioManager am = null;
AudioRecord record =null;
AudioTrack track =null;
final int SAMPLE_FREQUENCY = 44100;
final int SIZE_OF_RECORD_ARRAY = 1024;
boolean isPlaying = false;
class MyThread extends Thread{
#Override
public void run(){
recordAndPlay();
}
}
MyThread newThread;
private void init() {
int min = AudioRecord.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT);
record = new AudioRecord(MediaRecorder.AudioSource.VOICE_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_IN_MONO,
AudioFormat.ENCODING_PCM_16BIT, min);
int maxJitter = AudioTrack.getMinBufferSize(SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
track = new AudioTrack(AudioManager.MODE_IN_COMMUNICATION, SAMPLE_FREQUENCY, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, maxJitter, AudioTrack.MODE_STREAM);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
init();
newThread.start();
}
#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;
}
private void recordAndPlay() {
short[] lin = new short[SIZE_OF_RECORD_ARRAY];
int num = 0;
am = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
am.setMode(AudioManager.MODE_IN_COMMUNICATION);
record.startRecording();
track.play();
while (true) {
num = record.read(lin, 0, SIZE_OF_RECORD_ARRAY);
track.write(lin, 0, num);
}
}
public void passStop(View view){
Button playBtn = (Button) findViewById(R.id.playBtn);
// /*
if(!isPlaying){
record.startRecording();
track.play();
isPlaying = true;
playBtn.setText("Pause");
}
if(isPlaying){
record.stop();
track.pause();
isPlaying=false;
playBtn.setText("Pass through");
}
// */
}
#SuppressWarnings("deprecation")
#Override
public void onDestroy(){
newThread.stop();
}
}
Unfortunately, this program stops as soon as I try to run it through eclipse. This is wht I get in the logcat but I am not sure what it all means:
08-19 18:58:43.365: D/AndroidRuntime(27915): Shutting down VM
08-19 18:58:43.365: W/dalvikvm(27915): threadid=1: thread exiting with uncaught exception (group=0x4161f700)
08-19 18:58:43.365: E/AndroidRuntime(27915): FATAL EXCEPTION: main
08-19 18:58:43.365: E/AndroidRuntime(27915): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mypassthrough/com.example.mypassthrough.MainActivity}: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.access$600(ActivityThread.java:141)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Handler.dispatchMessage(Handler.java:99)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.os.Looper.loop(Looper.java:137)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.main(ActivityThread.java:5103)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invokeNative(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): at java.lang.reflect.Method.invoke(Method.java:525)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
08-19 18:58:43.365: E/AndroidRuntime(27915): at dalvik.system.NativeStart.main(Native Method)
08-19 18:58:43.365: E/AndroidRuntime(27915): Caused by: java.lang.NullPointerException
08-19 18:58:43.365: E/AndroidRuntime(27915): at com.example.mypassthrough.MainActivity.onCreate(MainActivity.java:46)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Activity.performCreate(Activity.java:5133)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
08-19 18:58:43.365: E/AndroidRuntime(27915): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
08-19 18:58:43.365: E/AndroidRuntime(27915): ... 11 more
What could be the reason for this code crashing, and how can it be debugged? I am pretty sure it has something to do with Thread, because my other versions of this code where I have not included Thread at all do not crash on startup.
Variable newThread is not initialized in oncreate() method that's why it is giving nullpointer exception
add this in your init() method it will work
newThread=new Thread();
You are getting a null pointer exception because newThread has not been initialized yet and it is null when you try to start it. The thread doesn't have anything to do also. You should look at implementing a runnable, handler, and timer into your activity instead of a thread.
Use sub class with extending AsyncTask Class
class TestActivity extends AsyncTask <String, Void, String > {
protected String doInBackground(String... urls) {
// execution
}
protected void onPostExecute(String result) {
// post execution
}
protected void onPreExecute() {
super.onPreExecute();
// initial activities
}
}
Related
I have 2 animations, slide[1] and slide[3], and when I try to cancel them when the animation repeats itself, it causes a crash. here is some relevant code:
slide[1].setDuration(500); slide[1].setStartDelay(500);
slide[3].setDuration(500); slide[3].setStartDelay(500);
slide[1].addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
if (!start) {
table[2][2].setBackgroundResource(R.drawable.black);
slide[1].setDuration(1000);
slide[1].setStartDelay(0);
slide[3].setDuration(1000);
slide[3].setStartDelay(0);
slide[1].removeAllListeners();
slide[3].cancel();
slide[1].cancel();
}
}
#Override
public void onAnimationEnd(Animator animation) {
}
}); slide[1].start(); slide[3].start();
The line which causes the crash is "slide[1].cancel();", and I don't know why.
Apparently the crash is being caused when the phone is running on JellyBean, but not Marshmallow for example.
How can I solve this problem?
Thanks!
UPDATE: here is the logcat:
03-13 16:18:01.943 1623-1623/com.example.ohad.squerz E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:251)
at java.util.ArrayList.get(ArrayList.java:304)
at android.animation.ValueAnimator$AnimationHandler.doAnimationFrame(ValueAnimator.java:603)
at android.animation.ValueAnimator$AnimationHandler.run(ValueAnimator.java:639)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
at android.view.Choreographer.doCallbacks(Choreographer.java:555)
at android.view.Choreographer.doFrame(Choreographer.java:524)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:711)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
This crash has been fixed in AOSP in this commit.
If you want to support API 16, you need to cancel your animations somewhere else than in onAnimationUpdate/onAnimationRepeat.
In your case (if it matters, because this answer comes a long time after your question), you probably want to avoid the repeat on your first animator, using setRepeatCount(0).
I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
I'm new in android programming. I'm writing simple application that should execute sql file, in first run. But it seems that this process take couple of seconds so I figure that application should show progressDialog while it will be executing sql file. But when I try to run application, dialog is showing with message "app has stopped ...". Please help me.
#Override
public void onCreate(SQLiteDatabase database)
{
String CREATE_BIBLE_TABLE = "CREATE TABLE bible (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"book INTEGER, " +
"chapter INTEGER NOT NULL, " +
"verse INTEGER NOT NULL, " +
"content TEXT" +
")";
database.execSQL(CREATE_BIBLE_TABLE);
new FirstLoadAsyncTask(database).execute();
}
public class FirstLoadAsyncTask extends AsyncTask<Void, Void, Void>
{
private SQLiteDatabase database;
private ProgressDialog progressDialog;
public FirstLoadAsyncTask(SQLiteDatabase database)
{
this.database = database;
}
#Override
protected void onPreExecute()
{
((Activity) context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressDialog = ProgressDialog.show(context, "Loading...", "");
}
});
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream inputStream = context.getAssets().open("bible.sql");
execSqlFile(database, inputStream);
} catch(IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Class extends SQLiteOpenHelper.
Edit:
Logcat:
01-06 18:27:53.221 14118-14118/pl.several27.Biblia_Warszawska E/Trace﹕ error opening trace file: No such file or directory (2)
01-06 18:27:53.891 14118-14118/pl.several27.Biblia_Warszawska I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081_msm7627a_JB_REL_2.0.3_CL2820657_release_AU (CL2820657)
Build Date: 01/22/13 Tue
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081 + NOTHING
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska W/Adreno200-EGLSUB﹕ <updater_create_surface_state:342>: updater_create_surface_state failed to open copybit, error: -13
01-06 18:27:54.011 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x53be8000 size:1536000 offset:0 fd:61
01-06 18:27:54.021 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x5083a000 size:4096 offset:0 fd:63
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x541fb000 size:1536000 offset:0 fd:66
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50a50000 size:4096 offset:0 fd:68
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x54472000 size:1536000 offset:0 fd:70
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50c75000 size:4096 offset:0 fd:72
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x545e9000 size:1536000 offset:0 fd:74
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50d4c000 size:4096 offset:0 fd:76
01-06 18:27:57.231 14118-14118/pl.several27.Biblia_Warszawska D/book choosen﹕ 1
01-06 18:27:57.581 14118-14118/pl.several27.Biblia_Warszawska W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca4540)
01-06 18:27:57.601 14118-14118/pl.several27.Biblia_Warszawska E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.several27.Biblia_Warszawska/pl.several27.Biblia_Warszawska.ChapterActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at pl.several27.Biblia_Warszawska.Database$FirstLoadAsyncTask.onPreExecute(Database.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at pl.several27.Biblia_Warszawska.Database.onCreate(Database.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at pl.several27.Biblia_Warszawska.Database.countChapters(Database.java:148)
at pl.several27.Biblia_Warszawska.ChapterActivity.onCreate(ChapterActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
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:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
01-06 18:27:59.511 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ killProcess, pid=14118
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ android.os.Process.killProcess(Process.java:956)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.NativeStart.main(Native Method)
Also I tried this way display progressdialog in non-activity class but it won't work too.
And here is whole application source code but without dialog: https://github.com/several27/BibliaWarszawska_Android
Please can anyone help me?
I do something like that on my application but I prefer to do that on background, so the user just don't have access to the screens that depend on my database...
You can try something like that:
public class BackgroundSyncService extends IntentService {
public static final String NOTIFICATION = "com.example.sync.service";
public static final String RESULT = "result";
public BackgroundSyncService() {
super("BackgroundSyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do here what you want with your database
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
Create a receiver (I use a inner class on my project)
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
//Do what you want here , like enable a section of your app
}
}
};
Then you need to register the service to your activity adding :
registerReceiver(receiver, new IntentFilter(BackgroundSyncService.NOTIFICATION));
Don't forget to unregister the receiver:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Also don't forget to register your IntentService on the AndroidManifest.xml
<service android:name="com.example.service.BackgroundSyncService" />
EDIT
Also you need to include the call to start your service where you want, I start mine on App instance:
Intent intent = new Intent(this, BackgroundSyncService.class);
startService(intent);
EXPLANATION
First you are creating a service to do what you want, the service can do whatever you want, in your case you will fill a database...
After you have created this service, you will set when you want to start this service (the edit part)...
After that you will register your activity to listen the service thats why we have created the BroadcastReceiver, the BroadcastReceiver will be called when your Service execute the line:
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
I guess the better way when the app starts you present the user with a message/ an activity that is not database related or just use the splash screen at the time that it is loading and estimate the time it normally finish loading to be the timer of the splash screen
I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.
I have implemented media player. I have only one Activity. When I'm starting the activity, my music starts to play and when I press the back button the music clip is in pause state, and again when I resume my activity, the music resumes properly. But there is error after I try to resume my Application after song got over. The app crashed, and I'm getting exception for IllegalStateException in back-press method( mp.pause();).
Please have a look at below code and suggest if I am doing something wrong.
public class Audio_Activity extends Activity
{
private MediaPlayer mp;
Button btnStartStop ;
int length;
SharedPreferences prefs;
ImageView imgVw;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
Log.e("Current ","Position -> " + length);
mp.setLooping(false);
mp.start();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
mp.release();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPause()
{
super.onStop();
SharedPreferences. Editor prefsEdit = prefs.edit();
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
if(mp!= null)
{
f(mp.isPlaying())
{
mp.pause();
}
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Here is my Log Cat
07-09 11:52:01.057: I/System.out(6854): Music is over and Button is enable !!!!!!
07-09 11:52:03.297: D/AndroidRuntime(6854): Shutting down VM
07-09 11:52:03.297: W/dalvikvm(6854): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-09 11:52:03.339: E/AndroidRuntime(6854): FATAL EXCEPTION: main
07-09 11:52:03.339: E/AndroidRuntime(6854): java.lang.IllegalStateException
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.media.MediaPlayer.isPlaying(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.audio_demo.Audio_Activity.onKeyDown(Audio_Activity.java:203)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.KeyEvent.dispatch(KeyEvent.java:2609)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.app.Activity.dispatchKeyEvent(Activity.java:2375)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1847)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl.deliverKeyEventPostIme(ViewRootImpl.java:3701)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl.handleImeFinishedEvent(ViewRootImpl.java:3651)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.view.ViewRootImpl$ViewRootHandler.handleMessage(ViewRootImpl.java:2818)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.os.Handler.dispatchMessage(Handler.java:99)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.os.Looper.loop(Looper.java:137)
07-09 11:52:03.339: E/AndroidRuntime(6854): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-09 11:52:03.339: E/AndroidRuntime(6854): at java.lang.reflect.Method.invokeNative(Native Method)
07-09 11:52:03.339: E/AndroidRuntime(6854): at java.lang.reflect.Method.invoke(Method.java:511)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-09 11:52:03.339: E/AndroidRuntime(6854): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-09 11:52:03.339: E/AndroidRuntime(6854): at dalvik.system.NativeStart.main(Native Method)
07-09 11:52:28.787: I/Process(6854): Sending signal. PID: 6854 SIG: 9
As I Understand the problem is about mp.seekTo(posiotion) in onResume() or mp.getCurrentPosition in onPause() method. That exception can because of not initializing the media player. According to the listener when the song finished you make your player stop and released and in onResume on line mp.seekTo(position) caused that exception. Remove mp.release() line in OnCompletion() method and in onResume and onpPause methods.
There's another thing you need to do. use a boolean value in your code to understand whether your mediaplayer finished playing or not. Change your onCreat like below:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.audio);
init();
imgVw.setImageResource(R.raw.teddy_two);
prefs = PreferenceManager.getDefaultSharedPreferences(this);
mp=MediaPlayer.create(Audio_Activity.this,R.raw.ennamo_yadho);
Log.e("Song is playing","in Mediya Player ");
Log.e("Current ","Position -> " + length);
mp.setLooping(false);
mp.start();
prefsEdit.putInt("mediaplaying", true);
prefsEdit.commit();
btnChapter.setEnabled(false);
mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
#Override
public void onCompletion(MediaPlayer mp)
{
// TODO Auto-generated method stub
mp.stop();
prefsEdit.putInt("mediaplaying", false);
prefsEdit.commit();
btnChapter.setEnabled(true);
System.out.println("Music is over and Button is enable !!!!!!");
}
});
#Override
public void onPause()
{
super.onStop();
SharedPreferences. Editor prefsEdit = prefs.edit();
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying){
int position = mp.getCurrentPosition();
prefsEdit.putInt("mediaPosition", position);
prefsEdit.commit();
}
}
#Override
protected void onResume()
{
super.onResume();
System.out.println("Activity is Resume !!!");
boolean isPlaying=prefs.getBoolean("mediaplaying",false);
if(isPlaying){
int position = prefs.getInt("mediaPosition", 0);
mp.seekTo(position);
}
}