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
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.
I m learning android please help me. It gives me following errors in logcat.
02-27 14:14:42.455: D/dalvikvm(1655): GC_FOR_ALLOC freed 46K, 5% free 2891K/3020K, paused 152ms, total 156ms
02-27 14:14:42.465: I/dalvikvm-heap(1655): Grow heap (frag case) to 3.668MB for 810016-byte allocation
02-27 14:14:42.545: D/dalvikvm(1655): GC_FOR_ALLOC freed 2K, 4% free 3680K/3812K, paused 76ms, total 77ms
02-27 14:14:43.425: I/Choreographer(1655): Skipped 35 frames! The application may be doing too much work on its main thread.
02-27 14:14:43.645: D/gralloc_goldfish(1655): Emulator without GPU emulation detected.
02-27 14:14:48.395: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:49.725: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:52.355: I/Choreographer(1655): Skipped 61 frames! The application may be doing too much work on its main thread.
02-27 14:14:55.195: D/AndroidRuntime(1655): Shutting down VM
02-27 14:14:55.195: W/dalvikvm(1655): threadid=1: thread exiting with uncaught exception (group=0xb3aaaba8)
02-27 14:14:55.275: E/AndroidRuntime(1655): FATAL EXCEPTION: main
02-27 14:14:55.275: E/AndroidRuntime(1655): Process: com.example.dreamhome, PID: 1655
02-27 14:14:55.275: E/AndroidRuntime(1655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dreamhome/com.example.dreamhome.LoginFormActivity}: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Looper.loop(Looper.java:136)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-27 14:14:55.275: E/AndroidRuntime(1655): at dalvik.system.NativeStart.main(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): Caused by: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.example.dreamhome.LoginFormActivity.onCreate(LoginFormActivity.java:45)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Activity.performCreate(Activity.java:5231)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-27 14:14:55.275: E/AndroidRuntime(1655): ... 11 more
02-27 14:15:03.295: I/Process(1655): Sending signal. PID: 1655 SIG: 9
HomeActivity.java
public class HomeActivity extends Activity
{
Button search_property, log_in, exit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_property=(Button)findViewById(R.id.homebutton1);
log_in=(Button)findViewById(R.id.homebutton2);
exit=(Button)findViewById(R.id.homebutton3);
search_property.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main1=new Intent(HomeActivity.this,EndUserSearchPropertyActivity.class);
startActivity(main1);
}
});
log_in.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2 = new Intent(HomeActivity.this,LoginFormActivity.class);
startActivity(main2);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
this is LoginFormActivity.java
public class LoginFormActivity extends Activity
{
private Button sign_up = null;
private Button btnSignIn = null;
LoginDataBaseAdapter loginDataBaseAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginFormActivity.this);
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.login_editText1);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.login_editText2);
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(LoginFormActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(LoginFormActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
sign_up = (Button)findViewById(R.id.login_form_button2);
sign_up.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2=new Intent(LoginFormActivity.this,SignupFormActivity.class);
startActivity(main2);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login_form, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
final Dialog dialog = new Dialog(LoginFormActivity.this);
Merely instantiating a dialog doesn't inflate/create its layout. All the subsequent dialog.findViewById() calls return null and you'll get the NPE here attempting to call a method on null reference:
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
You probably need to set a content view to your dialog with all the views you want to reference. The views are available with findViewById() after the dialog is showing.
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 8 years ago.
I make simply rss reader in android. I have the errors (I searched and tried some solutions but nothing):
Couldn't open http://pogoda.wp.pl/rss.xml
java.io.IOException: Couldn't open http://pogoda.wp.pl/rss.xml
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
at com.newsreader.RssReader.getItems(RssReader.java:23)
at com.newsreader.MainActivity$1$1.run(MainActivity.java:48)
at android.os.Handler.handleCallback(Handler.java:605)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4340)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
at java.net.InetAddress.getAllByName(InetAddress.java:220)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:273)
at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:168)
at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
and activity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(){
public void run(){
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
try{
RssReader reader = new RssReader("http://pogoda.wp.pl/rss.xml");
ListView items = (ListView) findViewById(R.id.listView1);
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(MainActivity.this, android.R.layout.simple_list_item_1, reader.getItems());
items.setAdapter(adapter);
Log.i("", ""+reader);
items.setOnItemClickListener(new ListListener(reader.getItems(), MainActivity.this));
}catch(Exception e){
Log.e("blad", e.getMessage(), e);
}
}
});
}
}.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
I don't know what am I doing wrong. Maybe someone has got the same problem so please help.
Thanks
It is because you are performing network operation on main thread of activity. Using Async task will be a better option.
Caused by: android.os.NetworkOnMainThreadException
This speaks for itself.
Don't do networking on the main Thread!
AsyncTask to the rescue. Try it out it will work.
Always use AsyncTask to solve this issue.
BUT, if you're within the movie Swordfish, someone points a gun at you and say "fix it in 30 seconds", then change your targetSdkVersion to 9 in the Android Manifest and the exception will stop. Don't worry, it will run on devices with version higher than 9 too. Even so, correct your code later using AsyncTask.
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 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();
}
}