I am creating an android app involving text messaging with one feature being that each letter is read out when entered. I am using TextToSpeech.
I have it working in a test project however when integrating it into my own i receive an unknown exception.
can anyone see what could be causing this and suggest a remedy? I have created a class called speech which is instantiated in another class and has a method which calls speak out (Similar to second example below.) Also can anyone explain why I need to extend Activity on the first example? The same problematic line says that "new TextToSpeech is not defined".
Snippet where will not work. error is on tts = new TextToSpeech(this, this);
public class Speech extends Activity implements TextToSpeech.OnInitListener {
private TextToSpeech tts;
private String toRead;
public Speech(String toRead){
this.toRead = toRead;
tts = new TextToSpeech(this, this);
}
Here is the code for where it does work
public class MainActivity extends Activity implements
TextToSpeech.OnInitListener {
/** Called when the activity is first created. */
private TextToSpeech tts;
private Button btnSpeak;
private EditText txtText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
btnSpeak = (Button) findViewById(R.id.btnSendSMS);
txtText = (EditText) findViewById(R.id.txtMessage);
// button on click event
btnSpeak.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
speakOut();
}
});
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
btnSpeak.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut() {
String text = txtText.getText().toString();
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
Logcat info
02-13 20:00:54.974: D/AndroidRuntime(11127): Shutting down VM
02-13 20:00:54.974: W/dalvikvm(11127): threadid=1: thread exiting with uncaught exception (group=0x411cd300)
02-13 20:00:54.979: E/AndroidRuntime(11127): FATAL EXCEPTION: main
02-13 20:00:54.979: E/AndroidRuntime(11127): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{org.BT/org.BT.Text_entry}: java.lang.NullPointerException
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2024)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2125)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread.access$600(ActivityThread.java:140)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1227)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.os.Handler.dispatchMessage(Handler.java:99)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.os.Looper.loop(Looper.java:137)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread.main(ActivityThread.java:4898)
02-13 20:00:54.979: E/AndroidRuntime(11127): at java.lang.reflect.Method.invokeNative(Native Method)
02-13 20:00:54.979: E/AndroidRuntime(11127): at java.lang.reflect.Method.invoke(Method.java:511)
02-13 20:00:54.979: E/AndroidRuntime(11127): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
02-13 20:00:54.979: E/AndroidRuntime(11127): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
02-13 20:00:54.979: E/AndroidRuntime(11127): at dalvik.system.NativeStart.main(Native Method)
02-13 20:00:54.979: E/AndroidRuntime(11127): Caused by: java.lang.NullPointerException
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.content.ContextWrapper.getContentResolver(ContextWrapper.java:91)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TtsEngines.getDefaultEngine(TtsEngines.java:75)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TextToSpeech.getDefaultEngine(TextToSpeech.java:1235)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TextToSpeech.initTts(TextToSpeech.java:595)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:553)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:527)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.speech.tts.TextToSpeech.<init>(TextToSpeech.java:512)
02-13 20:00:54.979: E/AndroidRuntime(11127): at org.BT.Speech.<init>(Speech.java:17)
02-13 20:00:54.979: E/AndroidRuntime(11127): at org.BT.Text_entry.<init>(Text_entry.java:48)
02-13 20:00:54.979: E/AndroidRuntime(11127): at java.lang.Class.newInstanceImpl(Native Method)
02-13 20:00:54.979: E/AndroidRuntime(11127): at java.lang.Class.newInstance(Class.java:1319)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.Instrumentation.newActivity(Instrumentation.java:1057)
02-13 20:00:54.979: E/AndroidRuntime(11127): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2015)
02-13 20:00:54.979: E/AndroidRuntime(11127): ... 11 more
-----------------------------------------edit-------------------------------------------------------
further research has suggested that it may be because I am trying Android framework outside of an android context? Could this be true - because I am using a class and not an activity? If so how would i get around this?
This looks to me as the standard example of TextToSpeech (TTS) that can be found on the internet everywhere and it should work as such without any problem. (However, this doesn't mean that there is no any design problem with this example of code.)
Maybe the version of Android that you are using is too old or that the TTS has not been set up correctly on your phone? Did you check the setting for TTS on your phone? (Normally, if the TTS has not been set up correctly on your phone, this code should call the proper installation page to do it but I remember seeing one message that this part can sometimes bomb out.)
You should also check that txtText is not null after its initialisation with findViewById().
That is how i do it..
public class TextToSpeechActivity extends Activity implements TextToSpeech.OnInitListener
{
private TextToSpeech mTts;
// This code can be any value you want, its just a checksum.
private static final int MY_DATA_CHECK_CODE = 1234;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Fire off an intent to check if a TTS engine is installed
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
}
public void speakClicked(View v)
{
// grab the contents of the text box.
EditText editText = (EditText) findViewById(R.id.inputText);
mTts.speak(editText.getText().toString(),TextToSpeech.QUEUE_FLUSH, null);
}
public void onInit(int i)
{
}
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == MY_DATA_CHECK_CODE)
{
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
{
// success, create the TTS instance
mTts = new TextToSpeech(this, this);
}
else
{
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(
TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
#Override
public void onDestroy()
{
if (mTts != null)
{
mTts.stop();
mTts.shutdown();
}
super.onDestroy();
}
}
Related
If wifi or mobile data is not enabled, it should ask the user, if he clicks yes in the AlertDialog, it will go to the settings.
This is inside main, on create, when the update button clicked:
btnUpdate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.v(TAG,"ButtonUpdate clicked");
connectIfNecessary();
currentDate = Calendar.getInstance();
formatter= new SimpleDateFormat("yyyy-MM-dd");
new UpdateDB(MainActivity.this);
txtLastUpdateShow.setText(formatter.format(currentDate.getTime()));
});
This is connectifnecessary:
public void connectIfNecessary(){
Log.v(TAG, "main connectIfNecessary");
if(!isConnected()){
final Context ctx = this;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage("need internet");
builder.setTitle("do you want to enable it now?");
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton("no", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
}
this is isConnected:
public boolean isConnected(){
Log.v(TAG, "mainisconnected");
ConnectivityManager conectivtyManager = (ConnectivityManager)
getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
if (conectivtyManager.getActiveNetworkInfo() != null
&& conectivtyManager.getActiveNetworkInfo().isAvailable()
&& conectivtyManager.getActiveNetworkInfo().isConnected()) {
Log.v(TAG, "mainisconnected true");
return true;
} else {
Log.v(TAG, "mainisconnected false");
return false;
}
}
in updatedb constructor, it will call asynctask to connect websites.
When i run this, and click update button, it crashes because it goes into updatedb withpout asking me in builder. The errors:
FATAL EXCEPTION: AsyncTask #1
Process: com.cursedchico.IstanbulEventPool, PID: 13068
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:303)
at com.cursedchico.IstanbulEventPool.EventRetriever.doInBackground(UpdateDB.java:109)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e17480 V.E..... R.....I. 0,0-488,216} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.support.v7.app.AlertDialog$Builder.show(AlertDialog.java:902)
at com.cursedchico.IstanbulEventPool.MainActivity.connectIfNecessary(MainActivity.java:106)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:276)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
01-01 18:48:00.299 13068-13068/com.cursedchico.IstanbulEventPool E/WindowManager: android.view.WindowLeaked: Activity com.cursedchico.IstanbulEventPool.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{41e36258 V.E..... R......D 0,0-488,165} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:388)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:248)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:286)
at android.app.ProgressDialog.show(ProgressDialog.java:117)
at android.app.ProgressDialog.show(ProgressDialog.java:100)
at com.cursedchico.IstanbulEventPool.EventRetriever.onPreExecute(UpdateDB.java:269)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.cursedchico.IstanbulEventPool.UpdateDB.<init>(UpdateDB.java:56)
at com.cursedchico.IstanbulEventPool.MainActivity$6.onClick(MainActivity.java:280)
at android.view.View.performClick(View.java:4508)
at android.view.View$PerformClick.run(View.java:18675)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5584)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java:106) is builder.show()
MainActivity.java:276) connectIfNecessary();
I am getting errors for hours, at first about appcompat, then manifest then layout now this.
I use real tablet device.
When device is not connected , following would be execution flow
Get inside connectIfNecessary()
Create Alert to ask user to enable internet. Please note that only Alter object is created at this moment, it will be displayed on screen only after stack of main thread unwinds.
Return from connectIfNecessary() create instance of updateDB(). Inside this application is crashing
Few simple changes would fix your code.
add isConnected() if check before creating instance of updateDB(). This will cover the CONNECTED case
if the device is NOT CONNECTED, user will shown the alter and take to settings screen. If user enables WIFI from settings and comes back, onResume() of your activity will be called. Check connectivity and add updateDB() here.
So I'm trying to implement a AlertDialog which should open up on pressing the the 'activate' button, but on pressing the button, the app crashes.
Here's my code.
MainActivity-
public class MainActivity extends Activity {
Button activateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activateButton = (Button)findViewById(R.id.activate);
activateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Speed s = new Speed();
}
});
}
And here's another class called Speed which contains the code for AlertDialog
public class Speed extends Activity {
LocationManager mManager;
final LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
AlertDialog.Builder box = new AlertDialog.Builder(this);
Speed(){
Status();
}
private void Status(){
if(!mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
DialogBox();
}
}
protected void DialogBox(){
AlertDialog.Builder box = new AlertDialog.Builder(this);
box.setTitle("The GPS needs to be enabled. Would you like to enable the GPS?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
final AlertDialog alert = box.create();
alert.show();
}
}
Also, here's the log with error in the context
10-01 21:27:00.439: E/AndroidRuntime(5503): FATAL EXCEPTION: main
10-01 21:27:00.439: E/AndroidRuntime(5503): java.lang.IllegalStateException: System services not available to Activities before onCreate()
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.app.Activity.getSystemService(Activity.java:3989)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.scimet.admin.driveon.Speed.<init>(Speed.java:12)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.scimet.admin.driveon.MainActivity$1.onClick(MainActivity.java:25)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.view.View.performClick(View.java:3534)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.view.View$PerformClick.run(View.java:14263)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Handler.handleCallback(Handler.java:605)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Handler.dispatchMessage(Handler.java:92)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.os.Looper.loop(Looper.java:137)
10-01 21:27:00.439: E/AndroidRuntime(5503): at android.app.ActivityThread.main(ActivityThread.java:4441)
10-01 21:27:00.439: E/AndroidRuntime(5503): at java.lang.reflect.Method.invokeNative(Native Method)
10-01 21:27:00.439: E/AndroidRuntime(5503): at java.lang.reflect.Method.invoke(Method.java:511)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-01 21:27:00.439: E/AndroidRuntime(5503): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-01 21:27:00.439: E/AndroidRuntime(5503): at dalvik.system.NativeStart.main(Native Method)
This is my first Android project. and on searching for multiple hours to try and resolve this issue, I've ended up with no solution. Please point out the mistake.
Thank you!
You should put this code inside onCreate method, because it will run when the activity is created.
For example
in your class remove constructor.
Then on onCreate method of the activity you do:
public class MainActivity extends Activity {
LocationManager manager;
AlertDialog.Builder box;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
box = new AlertDialog.Builder(this);
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
Status();
}
}
An activity should be used for presenting a different user flow and shouldn't be instantiated using 'new'.
If you replace the Speed instantiation line in MainActivity with this:
Speed s = new Speed(MainActivity.this);
and instead treat Speed as a standard class and pass in the MainActivity as a Context object.
public class Speed{
LocationManager mManager;
final LocationManager manager;
AlertDialog.Builder box;
final Context context;
Speed(Context context){
this.context = context;
mManager = context.getSystemService(Context.LOCATION_SERVICE );
Status();
}
private void Status(){
if(!mManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
DialogBox();
}
}
protected void DialogBox(){
AlertDialog.Builder box = new AlertDialog.Builder(this.context);
box.setTitle("The GPS needs to be enabled. Would you like to enable the GPS?").setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
}).setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int id){
dialog.cancel();
}
});
final AlertDialog alert = box.create();
alert.show();
}
}
You will only need to do this if you want to keep the separation between the Speed handling stuff and the activity itself.
hi this is my java file ......i m developing a nfc writer application.....here down is my java code file
package com.example.nfc_tag_writer;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcAdapter.OnNdefPushCompleteCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.Toast;
import java.nio.charset.Charset;
public class SendTextViaNFCActivity extends Activity implements CreateNdefMessageCallback, OnNdefPushCompleteCallback {
private static final int MESSAGE_SENT = 1;
String CURSOR_HERE;
String SAVED_TEXT;
String beamText;
private final Handler mHandler;
NfcAdapter mNfcAdapter;
EditText myText;
class AnonymousClass_1 extends Handler {
final /* synthetic */ SendTextViaNFCActivity this$0;
AnonymousClass_1(SendTextViaNFCActivity r1_SendTextViaNFCActivity) {
super();
this$0 = r1_SendTextViaNFCActivity;
}
public void handleMessage(Message msg) {
switch(msg.what) {
case MESSAGE_SENT:
Toast.makeText(this$0.getApplicationContext(), "Message sent!", MESSAGE_SENT).show();
}
}
}
public SendTextViaNFCActivity() {
super();
SAVED_TEXT = "SAVED_TEXT";
CURSOR_HERE = "###CURSOR_HERE###";
beamText = "";
mHandler = new AnonymousClass_1(this);
}
public NdefRecord createMimeRecord(String mimeType, byte[] payload) {
return new NdefRecord((short) 2, mimeType.getBytes(Charset.forName("US-ASCII")), new byte[0], payload);
}
public NdefMessage createNdefMessage(NfcEvent event) {
NdefRecord[] r2_NdefRecord_A = new NdefRecord[2];
r2_NdefRecord_A[0] = createMimeRecord("application/com.example.android.beam", myText.getText().toString().getBytes());
r2_NdefRecord_A[1] = NdefRecord.createApplicationRecord("diewland.nfc.text");
return new NdefMessage(r2_NdefRecord_A);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.send_text_via_nfc);
myText = (EditText) findViewById(R.id.my_text);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
}
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}
public boolean onCreateOptionsMenu(Menu menu) {
if (mNfcAdapter == null) {
return super.onCreateOptionsMenu(menu);
} else {
getMenuInflater().inflate(R.menu.options, menu);
return true;
}
}
public void onNdefPushComplete(NfcEvent arg0) {
mHandler.obtainMessage(MESSAGE_SENT).sendToTarget();
}
public void onNewIntent(Intent intent) {
setIntent(intent);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.menu_settings:
startActivity(new Intent("android.settings.NFCSHARING_SETTINGS"));
return true;
case R.id.menu_reset:
myText.setText("");
return true;
case R.id.menu_share:
if (!"".equals(myText.getText().toString())) {
Intent sendIntent = new Intent();
sendIntent.setAction("android.intent.action.SEND");
sendIntent.putExtra("android.intent.extra.TEXT", myText.getText().toString());
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent, "Share via"));
return true;
} else {
return true;
}
}
return super.onOptionsItemSelected(item);
}
protected void onPause() {
super.onPause();
myText.getText().insert(myText.getSelectionStart(), CURSOR_HERE);
Editor editor = getPreferences(0).edit();
editor.putString(SAVED_TEXT, myText.getText().toString());
editor.commit();
}
public void onResume() {
super.onResume();
Intent intent = getIntent();
String type = intent.getType();
if (!"android.intent.action.SEND".equals(intent.getAction()) || type == null) {
if ("android.nfc.action.NDEF_DISCOVERED".equals(getIntent().getAction())) {
processIntent(getIntent());
}
String restoredText = getPreferences(0).getString(SAVED_TEXT, null);
if (restoredText != null) {
myText.setText(restoredText.replaceAll(CURSOR_HERE, beamText));
}
} else if ("text/plain".equals(type)) {
myText.setText(intent.getStringExtra("android.intent.extra.TEXT"));
}
myText.setSelection(myText.getText().length());
}
void processIntent(Intent intent) {
beamText = new String(((NdefMessage) intent.getParcelableArrayExtra("android.nfc.extra.NDEF_MESSAGES")[0]).getRecords()[0].getPayload());
}
}
i m getting followings errorss
03-19 08:09:56.989: V/NFC(767): this device does not have NFC support
03-19 08:09:56.999: D/AndroidRuntime(767): Shutting down VM
03-19 08:09:56.999: W/dalvikvm(767): threadid=1: thread exiting with uncaught exception (group=0x414c4700)
03-19 08:09:57.029: E/AndroidRuntime(767): FATAL EXCEPTION: main
03-19 08:09:57.029: E/AndroidRuntime(767): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.nfc_tag_writer/com.example.nfc_tag_writer.SendTextViaNFCActivity}: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Handler.dispatchMessage(Handler.java:99)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.os.Looper.loop(Looper.java:137)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invokeNative(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): at java.lang.reflect.Method.invoke(Method.java:525)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-19 08:09:57.029: E/AndroidRuntime(767): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-19 08:09:57.029: E/AndroidRuntime(767): at dalvik.system.NativeStart.main(Native Method)
03-19 08:09:57.029: E/AndroidRuntime(767): Caused by: java.lang.NullPointerException
03-19 08:09:57.029: E/AndroidRuntime(767): at com.example.nfc_tag_writer.SendTextViaNFCActivity.onCreate(SendTextViaNFCActivity.java:75)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Activity.performCreate(Activity.java:5133)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-19 08:09:57.029: E/AndroidRuntime(767): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-19 08:09:57.029: E/AndroidRuntime(767): ... 11 more
please can anyone help me
i m getting the my errors in logcat...i m unable to fix them.....the app is unfornatelly stopping r crashing
Your checking that the mNfcAdapter is not null, yet still try to access it afterward even if it is. Try moving these lines
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
into an else to the previous if:
if (mNfcAdapter == null) {
myText.setText("NFC is not available on this device.");
myText.setEnabled(false);
} else {
mNfcAdapter.setNdefPushMessageCallback(this, this, new Activity[0]);
mNfcAdapter.setOnNdefPushCompleteCallback(this, this, new Activity[0]);
}
I created an overlay "always on top button", which is a service HUD, and I can't start an activity screen from there, it gives the error: "Unfortunately App has stopped". In the beginning, all I used to know if there was any TouchEventwas a toast, and that toast was created, but it was created several times, so I don't know if it gives that error because this code, which is on TouchEvent body , is repeated several times too.
here is my code:
public class HUD extends Service implements OnClickListener, OnTouchListener, OnLongClickListener {
Button mButton;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//mView = new HUDView(this);
mButton = new Button(this);
mButton.setId(1);
mButton.setText("Button");
mButton.setClickable(true);
mButton.setOnTouchListener(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.OPAQUE);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getX()<mButton.getWidth() & event.getY()>0)
{
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show(); //this my toast
Intent i = new Intent(); //this is my new acivity (intent)
i.setClass(HUD.this, screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
HUD.this.stopSelf();
}
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(this,"Click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
System.exit(1);
return false;
}
}
So my question is, is this code on TouchEvent body being repeated several times? If it is, is that the cause of the error?
log cat:
07-20 22:11:06.962: I/Choreographer(1620): Skipped 52 frames! The application may be doing too much work on its main thread.
07-20 22:11:08.062: D/AndroidRuntime(1620): Shutting down VM
07-20 22:11:08.062: W/dalvikvm(1620): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-20 22:11:08.132: E/AndroidRuntime(1620): FATAL EXCEPTION: main
07-20 22:11:08.132: E/AndroidRuntime(1620): android.app.SuperNotCalledException: Activity {com.example.screenshot/com.example.screenshot.screen} did not call through to super.onCreate()
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Looper.loop(Looper.java:137)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-20 22:11:08.132: E/AndroidRuntime(1620): at dalvik.system.NativeStart.main(Native Method)
screen.java:
public class screen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Toast.makeText(getApplicationContext(), "Made it", 0).show();
finish();
}
}
See android start activity from service
Intent i= new Intent(getBaseContext(), screen.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
You error seems to be inside screen activity. There are many thread which might help to figure out the error that you are getting for the activity:
Error in Android "SuperNotCalledException:Activity did not call through to super.OnCreate()"
android.app.SuperNotCalledException: Activity did not call through to super.onStop()
Update
The error is because you haven't called: super.onCreate(savedInstanceState); in your screen activity's onCreate(). That should be the first thing to be called in onCreate(). Do something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... other stuff
}
Hope this helps.
I am trying to avoid using onDestroy and want to keep this as simple as possible, but when I exit the program, I get a Force Close error. Not sure why. Here is the code for the main part of the application. Any suggestions?
Main Application Code
public class Quotes extends Activity implements OnClickListener {
ProgressDialog dialog;
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
WebView adsview = (WebView) findViewById(R.id.ads);
adsview.getSettings().setJavaScriptEnabled(true);
adsview.loadUrl("http://www.dgdevelco.com/quotes/androidad.html");
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String q = SP.getString("appViewType","http://www.dgdevelco.com/quotes/quotesandroidtxt.html");
String c = SP.getString("appRefreshRate","20");
webview = (WebView) findViewById(R.id.scroll);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new QuotesWebView(this));
webview.loadUrl(q);
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
webview.reload();
}
}, 10, Long.parseLong(c),TimeUnit.SECONDS);
findViewById(R.id.refresh).setOnClickListener(this);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onResume(){
super.onResume();
}
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
webview.reload();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem about = menu.getItem(0);
about.setIntent(new Intent(this, About.class));
MenuItem preferences = menu.getItem(1);
preferences.setIntent(new Intent(this, Preferences.class));
return true;
}
}
LogCat
07-04 13:34:55.011: INFO/DevicePushListener(1415): Connection State Changed: NetworkInfo: type: WIFI[], state: CONNECTED/CONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: true
07-04 13:34:55.011: WARN/WindowManager(1314): Attempted to add application window with unknown token HistoryRecord{40c40f50 com.dge.quotes/.Quotes}. Aborting.
07-04 13:34:55.034: DEBUG/AndroidRuntime(24137): Shutting down VM
07-04 13:34:55.034: WARN/dalvikvm(24137): threadid=1: thread exiting with uncaught exception (group=0x40018560)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): FATAL EXCEPTION: main
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#40517fb0 is not valid; is your activity running?
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.view.ViewRoot.setView(ViewRoot.java:527)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.view.Window$LocalWindowManager.addView(Window.java:424)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.app.Dialog.show(Dialog.java:241)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.app.ProgressDialog.show(ProgressDialog.java:107)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.app.ProgressDialog.show(ProgressDialog.java:90)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at com.dge.quotes.QuotesWebView.onPageStarted(QuotesWebView.java:22)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.webkit.CallbackProxy.handleMessage(CallbackProxy.java:271)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.os.Handler.dispatchMessage(Handler.java:99)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.os.Looper.loop(Looper.java:123)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at android.app.ActivityThread.main(ActivityThread.java:3806)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at java.lang.reflect.Method.invokeNative(Native Method)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at java.lang.reflect.Method.invoke(Method.java:507)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-04 13:34:55.058: ERROR/AndroidRuntime(24137): at dalvik.system.NativeStart.main(Native Method)
07-04 13:34:55.089: WARN/ActivityManager(1314): Force finishing activity com.dge.quotes/.Quotes
Its written in your stacktrace
Unable to add window -- token android.os.BinderProxy#40517fb0 is not valid; is your activity running
You start a thread that does a reload
You then press back
Your activity finished
The thread returns and tries to draw on your activity
Oops its already finished
Take a look at the example code provided on the ScheduledExecutorService documentation page:
import static java.util.concurrent.TimeUnit.*;
class BeeperControl {
private final ScheduledExecutorService scheduler =
Executors.newScheduledThreadPool(1);
public void beepForAnHour() {
final Runnable beeper = new Runnable() {
public void run() { System.out.println("beep");
};
final ScheduledFuture beeperHandle =
scheduler.scheduleAtFixedRate(beeper, 10, 10, SECONDS);
scheduler.schedule(new Runnable() {
public void run() { beeperHandle.cancel(true); }
}, 60 * 60, SECONDS);
}
}}
(http://developer.android.com/reference/java/util/concurrent/ScheduledExecutorService.html)
As others have said, the problem is that the ScheduledExecutorService keeps running and reloading the page even after the user closes that activity. To fix this, you can stop the ScheduledExecutorService in onPause.
Calling scheduleAtFixedFate() returns a ScheduledFuture object. Store this object and then call cancel(true) on it in your onPause() method.
Your activity is already stopped when it reaches that line of code. Refer to the exchange in this "bug" report in the Android forum: http://code.google.com/p/android/issues/detail?id=3953