EDIT: Added an additional error and the revision to the code i made.
I am new to java/android. I am trying to create an AlertDialog inside my SmartApp class when an event is fired in my DataRobot class. I am getting an error when doing this. The event is firing and calling the function successfully in SmartApp, but when it gets to AlertDialog alert = new AlertDialog.Builder(this).create(); the following error is printed to logcat. Does anyone know what i am doing wrong or a better way to implement what i am wanting?
Logcat error:
02-05 22:39:27.081: VERBOSE/SmartApp(281): data alert event caught
02-05 22:39:27.081: VERBOSE/SmartApp(281): inside sendalert
02-05 22:39:27.090: WARN/System.err(281): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-05 22:39:27.122: WARN/System.err(281): at android.os.Handler.<init>(Handler.java:121)
02-05 22:39:27.122: WARN/System.err(281): at android.app.Dialog.<init>(Dialog.java:101)
02-05 22:39:27.141: WARN/System.err(281): at android.app.AlertDialog.<init>(AlertDialog.java:63)
02-05 22:39:27.141: WARN/System.err(281): at android.app.AlertDialog.<init>(AlertDialog.java:59)
02-05 22:39:27.161: WARN/System.err(281): at android.app.AlertDialog$Builder.create(AlertDialog.java:786)
02-05 22:39:27.161: WARN/System.err(281): at cpe495.smartapp.SmartApp.sendAlert(SmartApp.java:169)
02-05 22:39:27.171: WARN/System.err(281): at cpe495.smartapp.SmartApp$3.dataAlertReceived(SmartApp.java:59)
02-05 22:39:27.201: WARN/System.err(281): at cpe495.smartapp.DataRobot.fireDataAlertEvent(DataRobot.java:96)
02-05 22:39:27.201: WARN/System.err(281): at cpe495.smartapp.DataRobot.analyzeData(DataRobot.java:32)
02-05 22:39:27.211: WARN/System.err(281): at cpe495.smartapp.SmartApp$1.dataReceivedReceived(SmartApp.java:45)
02-05 22:39:27.222: WARN/System.err(281): at cpe495.smartapp.ConnectDevice.fireDataReceivedEvent(ConnectDevice.java:71)
02-05 22:39:27.222: WARN/System.err(281): at cpe495.smartapp.ConnectDevice.run(ConnectDevice.java:42)
02-05 22:39:27.242: WARN/System.err(281): at java.lang.Thread.run(Thread.java:1096)
//my smartapp class main ui
public class SmartApp extends Activity implements OnSharedPreferenceChangeListener {
TextView smartConnectionStatus;
TextView testOutputView;
Thread cThread;
private ConnectDevice cD = new ConnectDevice();
private DataRobot dR = new DataRobot();
private DataBuilder dB = new DataBuilder();
private DataSender dS = new DataSender();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
cD.addDataReceivedListener(new DataReceivedListener() {
#Override
public void dataReceivedReceived(DataReceivedEvent event) {
// TODO Auto-generated method stub
dR.analyzeData(event.getData());
}
});
dR.addDataAlertListener(new DataAlertListener() {
#Override
public void dataAlertReceived(DataAlertEvent event) {
Log.v("SmartApp", "data alert event caught");
sendAlert();
}
});
}
/* Function for sending alerts that the user has exceeded a stress index */
public void sendAlert() {
Log.v("SmartApp", "inside sendalert");
AlertDialog alert = new AlertDialog.Builder(this).create();
Log.v("SmartApp", "after builder1");
//Vibrator vibrator;
//vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//vibrator.vibrate(500);
alert.setMessage("Testing alert dialog...");
alert.setCancelable(false);
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
Log.v("SmartApp", "after builder2");
//AlertDialog alert = builder.create();
alert.setTitle("Title");
Log.v("SmartApp", "after builder3");
alert.show();
Log.v("SmartApp", "after builder4");
}
}
// datarobot class
public class DataRobot extends Activity {
/* This class is for analyzing the data */
private List _listeners = new ArrayList();
private List<DataAlertListener> _listeners2 = new ArrayList<DataAlertListener>();
private SmartDataObject data;
private int sI1;
private int sI2;
private float w1;
private float w2;
private float w3;
private int hRB;
private int hRVMin;
private int hRVMax;
public boolean analyzeData(SmartDataObject temp) {
/* Analyze the data
* Returns true if data was successfully analyzed
* Returns false if an error occurred
*/
data = temp;
if(data.getHeartRate()>290) {
fireDataAlertEvent();
}
fireDataAnalyzedEvent(data);
return true; //for now this will always return true
}
public synchronized void addDataAnalyzedListener(DataAnalyzedListener listener) {
_listeners.add(listener);
}
public synchronized void removeDataAnalyzedListener(DataAnalyzedListener listener) {
_listeners.remove(listener);
}
private synchronized void fireDataAnalyzedEvent(SmartDataObject temp) {
DataAnalyzedEvent dRE = new DataAnalyzedEvent(this, temp);
Iterator listeners = _listeners.iterator();
while(listeners.hasNext()) {
((DataAnalyzedListener)listeners.next()).dataAnalyzedReceived(dRE);
}
}
public interface DataAnalyzedListener {
public void dataAnalyzedReceived(DataAnalyzedEvent event);
}
public synchronized void addDataAlertListener(DataAlertListener listener) {
_listeners2.add(listener);
}
public synchronized void removeDataAlertListener(DataAlertListener listener) {
_listeners2.remove(listener);
}
private synchronized void fireDataAlertEvent() {
DataAlertEvent dAE = new DataAlertEvent(this);
Iterator listeners = _listeners2.iterator();
while(listeners.hasNext()) {
((DataAlertListener)listeners.next()).dataAlertReceived(dAE);
}
}
public interface DataAlertListener {
public void dataAlertReceived(DataAlertEvent event);
}
}
public class DataAlertEvent extends EventObject {
public DataAlertEvent(Object source) {
super(source);
// TODO Auto-generated constructor stub
}
}
Below is the added code after trying to fix
02-06 10:27:30.673: VERBOSE/SmartApp(276): data alert event caught
02-06 10:27:31.013: WARN/System.err(276): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
02-06 10:27:31.042: WARN/System.err(276): at android.os.Handler.<init>(Handler.java:121)
02-06 10:27:31.052: WARN/System.err(276): at android.view.ViewRoot.<init>(ViewRoot.java:231)
02-06 10:27:31.052: WARN/System.err(276): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
02-06 10:27:31.062: WARN/System.err(276): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
02-06 10:27:31.082: WARN/System.err(276): at android.view.Window$LocalWindowManager.addView(Window.java:424)
02-06 10:27:31.082: WARN/System.err(276): at android.app.Dialog.show(Dialog.java:241)
02-06 10:27:31.102: WARN/System.err(276): at cpe495.smartapp.SmartApp$4.dataAlertReceived(SmartApp.java:80)
02-06 10:27:31.102: WARN/System.err(276): at cpe495.smartapp.DataRobot.fireDataAlertEvent(DataRobot.java:96)
02-06 10:27:31.122: WARN/System.err(276): at cpe495.smartapp.DataRobot.analyzeData(DataRobot.java:32)
02-06 10:27:31.122: WARN/System.err(276): at cpe495.smartapp.SmartApp$2.dataReceivedReceived(SmartApp.java:66)
02-06 10:27:31.133: WARN/System.err(276): at cpe495.smartapp.ConnectDevice.fireDataReceivedEvent(ConnectDevice.java:71)
02-06 10:27:31.133: WARN/System.err(276): at cpe495.smartapp.ConnectDevice.run(ConnectDevice.java:42)
02-06 10:27:31.153: WARN/System.err(276): at java.lang.Thread.run(Thread.java:1096)
public class SmartApp extends Activity implements OnSharedPreferenceChangeListener {
TextView smartConnectionStatus;
TextView testOutputView;
Thread cThread;
private ConnectDevice cD = new ConnectDevice();
private DataRobot dR = new DataRobot();
private DataBuilder dB = new DataBuilder();
private DataSender dS = new DataSender();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.intro);
final AlertDialog alert = new AlertDialog.Builder(this).create();
Log.v("SmartApp", "inside sendalert");
//AlertDialog alert = new AlertDialog.Builder(this).create();
Log.v("SmartApp", "after builder1");
//Vibrator vibrator;
//vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
//vibrator.vibrate(500);
alert.setMessage("Testing alert dialog...");
alert.setCancelable(false);
alert.setButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
Log.v("SmartApp", "after builder2");
//AlertDialog alert = builder.create();
alert.setTitle("Title");
cD.addDataReceivedListener(new DataReceivedListener() {
#Override
public void dataReceivedReceived(DataReceivedEvent event) {
// TODO Auto-generated method stub
dR.analyzeData(event.getData());
}
});
dR.addDataAlertListener(new DataAlertListener() {
#Override
public void dataAlertReceived(DataAlertEvent event) {
Log.v("SmartApp", "data alert event caught");
sendAlert();
alert.show();
}
});
}
}
You must create and show alert dialog in UI thread or:
Create a Handler in UI thread.
Handler mHandler = new Handler();
Create a thread
class A implements Runnable {
public void run() {
// create and show alert here
}
}
When event is fired, call:
A a = new A();
mHandler.post(a);
AlertDialog.Builder(this).create(); should be called from a UI Thread.Try moving the create() method to UI Thread.
This was the same error I was getting so thank yo for suggesting to put it on the UI thread. I'm working in Xamarin though and the solution for me was actually to put it on the main thread like this:
Xamarin.Forms.Device.BeginInvokeOnMainThread(() =>
{
page.DisplayAlert("Alert", message, null, "Cancel");
});
Related
I want to display a simple DialogFragment within a Fragment, but it crashes every time the show() method is called.
It either crashes back to the MainActivity or it throws me a NullPointer Exception that does not seem to be related to the crash directly. I think Logcat swallows the actual problem somehow.
Here is the call and the DialogFragment subclass:
private void showCheatingDialog() {
DialogFragment newFragment = new CheatingDialogFragment();
newFragment.show(getChildFragmentManager(), "CheatingDialogFragment");
}
#Override
public void onCheatingPositiveClick(DialogFragment dialog) {
try {
client.puzzleDone(BLUFF);
} catch(IOException ex) {
Log.e("tiles", ex.toString());
Toast.makeText(getActivity(), "Connection to the server failed", Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
#Override
public void onCheatingCancelClick(DialogFragment dialog) {
// do nothing
}
public class CheatingDialogFragment extends DialogFragment {
public interface CheatingDialogListener {
public void onCheatingPositiveClick(DialogFragment dialog);
public void onCheatingCancelClick(DialogFragment dialog);
}
CheatingDialogListener listener;
// Override the Fragment.onAttach() method to instantiate the CheatingDialogListener
#Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the CheatingDialogListener so we can send events to the host
listener = (CheatingDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(getActivity().toString()
+ " must implement CheatingDialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Build the dialog and set up the button click handlers
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.cheating_dialog_fragment)
.setPositiveButton(R.string.cheating_dialog_positive, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the positive button event back to the host activity
listener.onCheatingPositiveClick(CheatingDialogFragment.this);
}
})
.setNegativeButton(R.string.cheating_dialog_cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Send the negative button event back to the host activity
listener.onCheatingCancelClick(CheatingDialogFragment.this);
}
});
return builder.create();
}
}
Here's the exception Logcat shows:
2021-06-17 08:45:04.952 7095-7095/com.example.se2_gruppenphase_ss21 E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.se2_gruppenphase_ss21, PID: 7095
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.example.se2_gruppenphase_ss21.networking.AvailableRoom.getName()' on a null object reference
at com.example.se2_gruppenphase_ss21.menu.RoomFragment.onCreateView(RoomFragment.java:86)
at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
at androidx.fragment.app.FragmentManager.dispatchStateChange(FragmentManager.java:2625)
at androidx.fragment.app.FragmentManager.dispatchActivityCreated(FragmentManager.java:2577)
at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:247)
at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:541)
at androidx.appcompat.app.AppCompatActivity.onStart(AppCompatActivity.java:210)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1435)
at android.app.Activity.performStart(Activity.java:8024)
at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3475)
at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:221)
at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:201)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:173)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2066)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:223)
at android.app.ActivityThread.main(ActivityThread.java:7656)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
I have a Android app that shows a dialog when a value is '1' and shows the dialog repeatedly till the value is set to '0'. A Runnable calls a Handler which starts the dialog, and the Runnable loops with a delay.
Problem is that when I go to another activity with the same function and go back, the dialog is already open. This causes my app to crash. I already try to use removeMessage and removeCallback but still have the problem.
Handler
Handler myHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
/* Dialog */
final AlertDialog.Builder AlertAlarm_Build;
LayoutInflater inflater = (LayoutInflater) Settings_Activity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
AlertAlarm_Build = new AlertDialog.Builder(Settings_Activity.this);
final View Disengaged_View;
Disengaged_View = inflater.inflate(R.layout.disengage_dialog,null);
final AlertDialog PasswordDialog = AlertAlarm_Build.create();
PasswordDialog.show();
final String[] given_password = new String[1];
final boolean[] Password_Pass = {false};
//respose
final RequestQueue requestHander;
requestHander = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
...//Ask for password
//New
PasswordDialog.setOnDismissListener(new DialogInterface.OnDismissListener()
{
#Override
public void onDismiss(DialogInterface dialogInterface)
{
recreate();
}
});
}
};
Runnable
//Runnable
final Runnable aMyRunnable = new Runnable()
{
#Override
public void run()
{
RequestQueue requestRun;
requestRun = (RequestQueue) Volley.newRequestQueue(getApplicationContext());
if(New_engaged[0].equals("1") && New_alarm[0].equals("1"))
{
set_engaged[0] = "1";
myHandler.sendEmptyMessage(0);
}
else
{
requestRun.add(JOR_SystemCheck);
myHandler.postDelayed(this,5000);
}
}
};
onStop
protected void onStop() {
super.onStop();
myHandler.removeCallbacksAndMessages(aMyRunnable);
myHandler.removeMessages(0);
}
Error
/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.djwiz.eclipse5, PID: 17705
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#f8866f3 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:765)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:356)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:92)
at android.app.Dialog.show(Dialog.java:330)
at com.example.djwiz.eclipse5.Settings_Activity$1.handleMessage(Settings_Activity.java:68)
at android.os.Handler.dispatchMessage(Handler.java:105)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6541)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
Based on the documentation for removeCallbacksAndMessages
Remove any pending posts of callbacks and sent messages whose obj is token. If token is null, all callbacks and messages will be removed
Your code won't match any token:
myHandler.removeCallbacksAndMessages(aMyRunnable);
So the solution would be to use:
myHandler.removeCallbacksAndMessages(null);
I have an activity that is displayed in portrait only and in my tablet it causes the following:
android.view.WindowLeaked: Activity com.spicycurryman.getdisciplined10.app.InstalledAppActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{53210b88 V.E..... R.....ID 0,0-1520,192} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:354)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:216)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:281)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity$LoadApplications.onPreExecute(InstalledAppActivity.java:306)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at com.spicycurryman.getdisciplined10.app.InstalledAppActivity.onCreate(InstalledAppActivity.java:105)
at android.app.Activity.performCreate(Activity.java:5104)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
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:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
I am using an AsyncTask to load a listview of installed apps on the phone and using a progressdialog.
I have researched this problem:
Progress dialog and AsyncTask error
android.view.WindowLeaked exception
Android Error: Window Leaked in AsyncTask
I was able to produce this code so that the whole app doesn't crash and burn, but the exception is still thrown and the activity screen is kind of shaky after the button click and the whole transition is not really smooth.
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
Dismissing the progress dialog or calling finish() doesn't really solve the problem either...
How would I fix this?
Here is most of the AsyncTask code:
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
List<PackageInfo> packageList2 = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
boolean d = isSystemPackage2(pi);
if ((!b || !c ) && d ){
packageList1.add(pi);
}
}
//here you got email and message apps in the
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage3(pi);
boolean c = isSystemPackage4(pi);
if (b || c){
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this);
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
//Inefficient patch to prevent Window Manager error
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(InstalledAppActivity.this, packageList1, packageManager));
try {
if ((this.pDialog != null) && this.pDialog.isShowing()) {
this.pDialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.pDialog = null;
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
try this :
#Override
public Object onRetainNonConfigurationInstance() {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog = null;
}
if (asynTask!= null) {
asynTask.detach();
}
return ayncTask;
}
Declaring a non-static inner AsyncTask in your activity is not a good idea because it holds a reference to the activity and this could be a couse of the leak. However, various configuration changes could cause the OS to destroy and recreate the activity. There are a number of solutions and Rustam's anser is an example.
However, I prefer to user either AsyncTaskLoader or use some sort of asynchronous callback, like a broadcast. The asynchronous callback decouples your AsyncTask from the Activity.
Hi friends i am having some problems with my code. I am very new to android programming, actually i am an electronics student. i have searched the forum for an answer to this problem but nothing says precisely what i have to do.i have given the log cat which explains my problem.One more thing When i add a empty constructor it shows an error "The blank final field context may not have been initialized" Please help me.
public class TrackService extends IntentService implements LocationListener,
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener {
//boolean uploaded = false;
private Context context= getApplicationContext();
String Lat, Long;
// A request to connect to Location Services
private LocationRequest mLocationRequest;
//List<?> pkgAppsList;
//ArrayList<ArrayList<String>> list;
//Context context;
//ArrayList<String> iteminserted = new ArrayList<String>();
private LocationClient mLocationClient;
// ArrayList<ArrayList<String>> UnUploadedData = new
// ArrayList<ArrayList<String>>();
//#Override
//public IBinder onBind(Intent intent) {
//return null;
//}
//public TrackService() {
//super("TrackService");
//}
public TrackService(Context context) {
super("Trackservice");
this.context = context;
}
#Override
public void onCreate() {
super.onCreate();
// Create a new global location parameters object
mLocationRequest = LocationRequest.create();
/*
* Set the update interval
*/
// mLocationRequest
// .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setInterval(1000 * 60 * 2);// Every 2 minute
// Use high accuracy
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
// Set the interval ceiling to one minute
mLocationRequest
.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
mLocationClient = new LocationClient(this, this, this);
}
/*
* Called by Location Services when the request to connect the client
* finishes successfully. At this point, you can request the current
* location or start periodic updates
*/
#Override
public void onConnected(Bundle bundle) {
startPeriodicUpdates();
}
/**
* Report location updates to the UI.
*
* #param location
* The updated location.
*/
#Override
public void onLocationChanged(Location location) {
System.out.println(location.getLatitude() + " "+ location.getLongitude());
Lat = location.getLatitude() + "";
Long = location.getLongitude() + "";
//if (isConnectingToInternet())
new UploadLocationInfo().execute();
// if (uploaded)
// this.stopSelf();
}
/**
* In response to a request to start updates, send a request to Location
* Services
*/
private void startPeriodicUpdates() {
mLocationClient.requestLocationUpdates(mLocationRequest, this);
}
/**
* In response to a request to stop updates, send a request to Location
* Services
*/
private void stopPeriodicUpdates() {
mLocationClient.removeLocationUpdates(this);
}
//public boolean isConnectingToInternet() {
//ConnectivityManager connectivity = (ConnectivityManager) this
// .getSystemService(Context.CONNECTIVITY_SERVICE);
//if (connectivity != null) {
//NetworkInfo[] info = connectivity.getAllNetworkInfo();
//if (info != null)
//for (int i = 0; i < info.length; i++)
//if (info[i].getState() == NetworkInfo.State.CONNECTED) {
//return true;
//}
//}
//return false;
//}
public class UploadLocationInfo extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Uploading Application List
//ArrayList<NameValuePair> LOCATION = new ArrayList<NameValuePair>();
//LOCATION.add(new BasicNameValuePair("LAT", Lat));
//LOCATION.add(new BasicNameValuePair("LONG", Long));
//TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext()
// .getSystemService(getApplicationContext().TELEPHONY_SERVICE);
//IMEI = telephonyManager.getDeviceId();
//LOCATION.add(new BasicNameValuePair("IMEI", IMEI));
double x = Double.parseDouble(Long);
double y = Double.parseDouble(Lat);
EditText text1 = (EditText) ((Activity)context).findViewById(R.id.text1);
text1.setText("lat"+y+"Log"+x);
double a = 48.6800000;
double b = 2.2100000;
float[] results = new float[1];
Location.distanceBetween(y, x, b, a, results);
float distanceInMeters = results[0];
boolean isWithin10m = false;
if( distanceInMeters < 20)
{
isWithin10m = true;
}
System.out.println("Uploading New Location");
if(isWithin10m){
try {
//open a web page
} catch (Exception e) {
e.printStackTrace();
}
}else{
text1.setText("nothing to display");
}
return null;
}
}
#Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
}
#Override
public void onDisconnected() {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
// If the client is connected
System.out.println("Destroy");
if (mLocationClient.isConnected()) {
stopPeriodicUpdates();
}
// After disconnect() is called, the client is considered "dead".
mLocationClient.disconnect();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
}
}
The Logcat details ae given below
07-22 11:49:37.419: D/dalvikvm(5525): Late-enabling CheckJNI
07-22 11:49:37.490: D/dalvikvm(5525): newInstance failed: no <init>()
07-22 11:49:37.490: D/AndroidRuntime(5525): Shutting down VM
07-22 11:49:37.490: W/dalvikvm(5525): threadid=1: thread exiting with uncaught exception (group=0x40d1a930)
07-22 11:49:37.490: E/AndroidRuntime(5525): FATAL EXCEPTION: main
07-22 11:49:37.490: E/AndroidRuntime(5525): java.lang.RuntimeException: Unable to instantiate service com.example.mobiletrackerslave.TrackService: java.lang.InstantiationException: can't instantiate class com.example.mobiletrackerslave.TrackService; no empty constructor
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2513)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.access$1600(ActivityThread.java:141)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1316)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.os.Handler.dispatchMessage(Handler.java:99)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.os.Looper.loop(Looper.java:137)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.reflect.Method.invokeNative(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.reflect.Method.invoke(Method.java:511)
07-22 11:49:37.490: E/AndroidRuntime(5525): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-22 11:49:37.490: E/AndroidRuntime(5525): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-22 11:49:37.490: E/AndroidRuntime(5525): at dalvik.system.NativeStart.main(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): Caused by: java.lang.InstantiationException: can't instantiate class com.example.mobiletrackerslave.TrackService; no empty constructor
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.Class.newInstanceImpl(Native Method)
07-22 11:49:37.490: E/AndroidRuntime(5525): at java.lang.Class.newInstance(Class.java:1319)
07-22 11:49:37.490: E/AndroidRuntime(5525): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2510)
07-22 11:49:37.490: E/AndroidRuntime(5525): ... 10 more
07-22 11:49:39.892: D/dalvikvm(5525): Debugger has detached; object registry had 1 entries
use
private Context context= getApplicationContext();
in OnCreate method of your Intent service.as
context= getApplicationContext();
and change
private Context context= getApplicationContext();
to
private Context context;
And the Exception is telling you that you need to implement the default public constructor.
public TrackService() {
super("TrackService");
}
The default public constructor is a constructor with no parameters.
Here you call super() and pass a String that will be used to name the IntentService
You need to add an empty constructor to your class i.e. one that takes no arguments:
Define this constructor in your class
public TrackService() {
super("Trackservice");
}
see here No empty constructor when create a service
android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy#406a6678 is not valid; is your activity running?
at android.view.ViewRoot.setView(ViewRoot.java:528)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.view.Window$LocalWindowManager.addView(Window.java:424)
at android.app.Dialog.show(Dialog.java:241)
at android.app.Activity.showDialog(Activity.java:2569)
at android.app.Activity.showDialog(Activity.java:2527)
at MyCode$8$4.run(MyCode.java:557)
at android.os.Handler.handleCallback(Handler.java:587)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3683)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
at dalvik.system.NativeStart.main(Native Method)
I am getting above exception when following code is executed. This file dialog will shown once the processing is done and progressbar reaches 100%. FileSaveDialog extends Dialog and implements OnCompletionListener
runOnUiThread(new Runnable() {
#Override
public void run() {
showDialog(error.Code());//Line 557
}
});
#Override
protected Dialog onCreateDialog(int id) {
Dialog dialog;
AlertDialog.Builder builder;
final ScrollView scrollView = new ScrollView(this);
final TextView textView = new TextView(this);
switch (id) {
// Other cases are here
case 4:
File playFile = new File(mediaPath, TEMP_WAV_FILE_NAME);
dialog = new FileSaveDialog(this, getResources(),
playFile.getAbsolutePath(), saveDiscardHandler);
dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// do whatever you want the back key to do
cleanUp();
}
});
break;
// Other cases are here
default:
dialog = null;
}
return dialog;
}
You must check activity isFinishing() If the activity is finishing, returns true; else returns false.