Error calling a new class using the onBackPressed method - android

I was trying to use the onBackPressed() method to open an activity that I need and close the existing one but the application close unexpectedly; I put a try catch if I can see the error but the variable "e" comes null, the only thing that show me something is the log, also I try to search for a solution that shows the log but it seems that those solutions do not apply to my case.
Here is my code:
#Override
public void onBackPressed() {
try {
Intent intent = new Intent(ScheduleAppointment.this, CreateAppointment.class);
ScheduleAppointment.this.startActivity(intent);
ScheduleAppointment.this.finish();
}catch (Exception e){
e.printStackTrace();
}
}
and here is the log:
02-26 12:21:44.062 2385-2385/com.saludtotal.beqs.saludtotalafiliados E/InputEventSender﹕ Exception dispatching finished signal.
02-26 12:21:44.063 2385-2385/com.saludtotal.beqs.saludtotalafiliados E/MessageQueue-JNI﹕ Exception in MessageQueue callback: handleReceiveCallback
02-26 12:21:44.114 2385-2385/com.saludtotal.beqs.saludtotalafiliados E/MessageQueue-JNI﹕ java.lang.NullPointerException
at com.saludtotal.beqs.saludtotalafiliados.ScheduleAppointment.onBackPressed(ScheduleAppointment.java:222)
at android.app.Activity.onKeyUp(Activity.java:2201)
at android.view.KeyEvent.dispatch(KeyEvent.java:2676)
at android.app.Activity.dispatchKeyEvent(Activity.java:2431)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1962)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3921)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3895)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3479)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3479)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3611)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3777)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2012)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1706)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1697)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1989)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5097)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
02-26 12:21:44.114 2385-2385/com.saludtotal.beqs.saludtotalafiliados D/AndroidRuntime﹕ Shutting down VM
02-26 12:21:44.115 2385-2385/com.saludtotal.beqs.saludtotalafiliados W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41d93d40)
02-26 12:21:44.139 2385-2385/com.saludtotal.beqs.saludtotalafiliados E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.saludtotal.beqs.saludtotalafiliados, PID: 2385
java.lang.NullPointerException
at com.saludtotal.beqs.saludtotalafiliados.ScheduleAppointment.onBackPressed(ScheduleAppointment.java:222)
at android.app.Activity.onKeyUp(Activity.java:2201)
at android.view.KeyEvent.dispatch(KeyEvent.java:2676)
at android.app.Activity.dispatchKeyEvent(Activity.java:2431)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:1962)
at android.view.ViewRootImpl$ViewPostImeInputStage.processKeyEvent(ViewRootImpl.java:3921)
at android.view.ViewRootImpl$ViewPostImeInputStage.onProcess(ViewRootImpl.java:3895)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3578)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3479)
at android.view.ViewRootImpl$AsyncInputStage.apply(ViewRootImpl.java:3635)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$InputStage.apply(ViewRootImpl.java:3479)
at android.view.ViewRootImpl$InputStage.deliver(ViewRootImpl.java:3452)
at android.view.ViewRootImpl$InputStage.onDeliverToNext(ViewRootImpl.java:3502)
at android.view.ViewRootImpl$InputStage.forward(ViewRootImpl.java:3471)
at android.view.ViewRootImpl$AsyncInputStage.forward(ViewRootImpl.java:3611)
at android.view.ViewRootImpl$ImeInputStage.onFinishedInputEvent(ViewRootImpl.java:3777)
at android.view.inputmethod.InputMethodManager$PendingEvent.run(InputMethodManager.java:2012)
at android.view.inputmethod.InputMethodManager.invokeFinishedInputEventCallback(InputMethodManager.java:1706)
at android.view.inputmethod.InputMethodManager.finishedInputEvent(InputMethodManager.java:1697)
at android.view.inputmethod.InputMethodManager$ImeInputEventSender.onInputEventFinished(InputMethodManager.java:1989)
at android.view.InputEventSender.dispatchInputEventFinished(InputEventSender.java:141)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:138)
at android.os.Looper.loop(Looper.java:123)
at android.app.ActivityThread.main(ActivityThread.java:5097)
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:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
A curious thing is if for example I change the class That I want to reopen I t works without any problem, but I need when the user press the back button to open that specific class. Any help will be appreciated.
Edit:
I am using a Motorola g 2nd generation with android version 4.4.4 and a Samsung galaxy tab 7.7 p6800 with android version 4.0.4 both show me the same error.
On thing happen when I remove the try catch clauses and I am debugging step by step, on the following line of code
ScheduleAppointment.this.startActivity(intent);
redirect to the ZygoteInit.java class and in this method is were it shows the error on the log:
/**
* Runs the zygote process's select loop. Accepts new connections as
* they happen, and reads commands from connections one spawn-request's
* worth at a time.
*
* #throws MethodAndArgsCaller in a child process when a main() should
* be executed.
*/
private static void runSelectLoop(String abiList) throws MethodAndArgsCaller {
ArrayList<FileDescriptor> fds = new ArrayList<FileDescriptor>();
ArrayList<ZygoteConnection> peers = new ArrayList<ZygoteConnection>();
FileDescriptor[] fdArray = new FileDescriptor[4];
fds.add(sServerSocket.getFileDescriptor());
peers.add(null);
int loopCount = GC_LOOP_COUNT;
while (true) {
int index;
/*
* Call gc() before we block in select().
* It's work that has to be done anyway, and it's better
* to avoid making every child do it. It will also
* madvise() any free memory as a side-effect.
*
* Don't call it every time, because walking the entire
* heap is a lot of overhead to free a few hundred bytes.
*/
if (loopCount <= 0) {
gc();
loopCount = GC_LOOP_COUNT;
} else {
loopCount--;
}
try {
fdArray = fds.toArray(fdArray);
index = selectReadable(fdArray);
} catch (IOException ex) {
throw new RuntimeException("Error in select()", ex);
}
if (index < 0) {
throw new RuntimeException("Error in select()");
} else if (index == 0) {
ZygoteConnection newPeer = acceptCommandPeer(abiList);
peers.add(newPeer);
fds.add(newPeer.getFileDescriptor());
} else {
boolean done;
done = peers.get(index).runOnce();
if (done) {
peers.remove(index);
fds.remove(index);
}
}
}
}
and more precisely in this part:
if (done) {
peers.remove(index);
fds.remove(index);
}

This worked for me, I think that an issue located in onPause, onStop or onDestroy methods
#Override
public void onBackPressed() {
try {
Intent intent = new Intent(this, CreateAppointment.class);
startActivity(intent);
finish();
}catch (Exception e){
e.printStackTrace();
}
super.onBackPressed();
}

My idea is the following, you should use a different context to create your Activity, rather than the Activity that you're currently in. For example, application context.
<application
android:name=".application.CustomApplication"
and
public class CustomApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
ApplicationHolder.INSTANCE.setCustomApplication(this);
}
}
and
public enum ApplicationHolder {
INSTANCE;
private CustomApplication customApplication = null;
public CustomApplication getCustomApplication() {
return customApplication ;
}
public void setCustomApplication(CustomApplication customApplication ) {
this.customApplication = customApplication ;
}
}
and
Intent intent = new Intent(ApplicationHolder.getCustomApplication(), CreateAppointment.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
finish();
If the bug still occurs, then start other activity with startActivityForResult, and call finish() in its callback method onActivityResult().

Related

Android/Firebase: onDataChange() for query returns null pointer exception

I'm trying to retreive an object from my firebase databse by its id. But my app crashes with a null pointer exception. Please help me out. I'm new to Firebase.
Also I'd like to know how I can find out if the search is unsuccessful.
Here's my code for data retreival. The Query class belongs to com.google.firebase and not to com.firebase.client.
#Override
public void onClick(View view) {
key = scanContent;
Query q = dbRef.child("idno").equalTo(key);
if (key != null) {
q.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
Item i = dataSnapshot.getValue(Item.class);
id.setText(scanContent);
nam.setText(i.getName());
brand.setText(i.getBrand());
cost.setText(i.getCost());
sell.setText("Add to list of sold items?");
}
#Override
public void onCancelled(DatabaseError databaseError) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(databaseError.getMessage())
.setTitle("Error!")
.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.show();
}
});
} else {
search.setError("Enter a valid value");
}
}
Here are the contents of my logcat.
09-24 13:32:26.332 9228-9228/com.strokx.user.stockmanager W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x40c03a68)
09-24 13:32:26.352 9228-9228/com.strokx.user.stockmanager E/UncaughtException: java.lang.NullPointerException
at com.strokx.user.stockmanager.SearchFragment$2$1.onDataChange(SearchFragment.java:106)
at com.google.firebase.database.Query$1.onDataChange(Unknown Source)
at com.google.android.gms.internal.zzaie.zza(Unknown Source)
at com.google.android.gms.internal.zzaje.zzcta(Unknown Source)
at com.google.android.gms.internal.zzajh$1.run(Unknown Source)
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:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
09-24 13:32:26.572 9228-9228/com.strokx.user.stockmanager D/FirebaseCrashApiImpl: throwable java.lang.NullPointerException
09-24 13:32:26.672 9228-9228/com.strokx.user.stockmanager E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.strokx.user.stockmanager.SearchFragment$2$1.onDataChange(SearchFragment.java:106)
at com.google.firebase.database.Query$1.onDataChange(Unknown Source)
at com.google.android.gms.internal.zzaie.zza(Unknown Source)
at com.google.android.gms.internal.zzaje.zzcta(Unknown Source)
at com.google.android.gms.internal.zzajh$1.run(Unknown Source)
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:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
I think you need a default empty constructor for your Item class.
When you execute a query against the Firebase Database, the result is going to be a list of items. Even when there is only a single match for your query, the result will be a list of one. So your code needs to handle the list, by looping over dataSnapshot.getChildren():
Query q = dbRef.child("idno").equalTo(key);
if (key != null) {
q.addListenerForSingleValueEvent(new com.google.firebase.database.ValueEventListener() {
#Override
public void onDataChange(com.google.firebase.database.DataSnapshot dataSnapshot) {
(for DataSnapshot itemSnapshot: dataSnapshot.getChildren()) {
Item i = dataSnapshot.getValue(Item.class);
...
We recently added an example of how to do this to the Firebase documentation on filtering data with queries.
Fixed it. My query was wrong. Although fixing the query still wouldn't make the listview display the retrieved result. I used the firebase ui list adapter to fix that. I've posted the correct code below, if it helps anyone. Thanks everyone.
dbRef= FirebaseDatabase.getInstance().getReferenceFromUrl("https://stockmanager-142503.firebaseio.com/Items");
imgbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
key = scanContent;
Query q = dbRef.orderByChild("idno").equalTo(key);
FirebaseListAdapter<Item> adapter =new FirebaseListAdapter<Item>(getActivity(),Item.class,R.layout.rowitem,q) {
#Override
protected void populateView(View v, Item item, int position) {
TextView text1=(TextView)v.findViewById(R.id.text1);
TextView text2=(TextView)v.findViewById(R.id.text2);
TextView text3=(TextView)v.findViewById(R.id.text3);
TextView text4=(TextView)v.findViewById(R.id.text4);
TextView text5=(TextView)v.findViewById(R.id.text5);
text1.setText(item.getIdno());
text2.setText(item.getName());
text3.setText(item.getBrand());
text4.setText(item.getCost());
text5.setText(item.getDate());
solditem=item;
}
};
sell.setText("Add this result to Sold Items List?");
sList.setAdapter(adapter);
}
});

Android PrintServer crashes when pressing print button while rendering preview

I try to implement my own printer (means print server) based on the Android PrintServer API. This print server provides a static single printer which tasks is to upload the print job to a web page via http upload.
I am using Marshmallow on a Sony Z2. And for testing I use the email application and "printing" from the submenu.
In principle I managed all the business logic already and it works, so at least I used the right approach. But when I press the "print" button (with the printer logo) in the Android print dialog to fast, the whole print server crashes. If I wait until the dialog rendered all the preview and then press the button, everything is fine.
I dont know if the problem is clear therefore I made a small movie (1,8MB), which you can find here:
https://c.geniusbytes.com/index.php/s/leJrSGRlxBSSCux
To reduce the problem I removed all the transfer code and arrived at the most minimal version which still causes the crash, see below.
Can somebody see what is the problem? On my mobile there is also the PDF-writer PrintServer (Sony!?). This does not crash with the same procedure. Instead the "print" behavior, which is the selection of the destination to store the PDF, waits until the preview is rendered and then pops up.
It is important to mention that one need a larger document to print. Otherwise the preview is rendered to fast for causing the crash by pressing the print button.
Here is the code for the PrintServer implementation:
public class UploadPrintService extends PrintService {
private static final String LOG_TAG = "UploadPrintService";
////////////////////////////////////////////////
//
// service methods
//
/////////////////////////////////////////////////
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
protected void onConnected() {
Log.i(LOG_TAG, "#onConnected()");
}
#Override
protected void onDisconnected() {
Log.i(LOG_TAG, "#onDisconnected()");
}
#Override
protected PrinterDiscoverySession onCreatePrinterDiscoverySession() {
Log.i(LOG_TAG, "#onCreatePrinterDiscoverySession()");
return new UploadPrintDiscoverySession(this);
}
#Override
protected void onRequestCancelPrintJob(PrintJob printJob) {
// standard cancel
if ((printJob.isStarted() && (!printJob.isCancelled()))) {
printJob.cancel();
}
}
#Override
protected void onPrintJobQueued(final PrintJob printJob) {
Log.i(LOG_TAG, "#onPrintJobQueued");
printJob.start();
}
}
And the PrinterDiscoverySession is implemented in a way, such that it always returns the same printer. See here:
public class UploadPrintDiscoverySession extends PrinterDiscoverySession {
private static final String LOG_TAG = UploadPrintDiscoverySession.class.getSimpleName();
private PrintService printService = null;
private static final String PRINTER_ID = "my.uploadprinter.id";
public UploadPrintDiscoverySession(PrintService printService) {
super();
Log.i(LOG_TAG, "new discovery session!");
this.printService = printService;
}
#Override
public void onStartPrinterDiscovery(List<PrinterId> list) {
Log.i(LOG_TAG, "#onStartPrinterDiscovery");
addUploadPrinter();
}
#Override
public void onStopPrinterDiscovery() {
Log.i(LOG_TAG, "#onStopPrinterDiscovery");
}
#Override
public void onValidatePrinters(List<PrinterId> list) {
Log.i(LOG_TAG, "#onValidatePrinters");
addUploadPrinter();
}
#Override
public void onStartPrinterStateTracking(PrinterId printerId) {
Log.i(LOG_TAG, "#onStartPrinterStateTracking");
addUploadPrinter();
}
#Override
public void onStopPrinterStateTracking(PrinterId printerId) {
Log.i(LOG_TAG, "#onStopPrinterStateTracking");
}
#Override
public void onDestroy() {
Log.i(LOG_TAG, "#onDestroy");
}
private void addUploadPrinter() {
Log.i(LOG_TAG, "#addUploadPrinter");
PrinterId uploadPrinterId = printService.generatePrinterId(PRINTER_ID);
PrinterInfo.Builder printerInfoBuilder = new PrinterInfo.Builder(uploadPrinterId,
"Mighty Printer", PrinterInfo.STATUS_IDLE);
PrinterCapabilitiesInfo.Builder capBuilder =
new PrinterCapabilitiesInfo.Builder(uploadPrinterId);
capBuilder.addMediaSize(PrintAttributes.MediaSize.ISO_A4, true);
capBuilder.addMediaSize(PrintAttributes.MediaSize.ISO_A3, false);
capBuilder.addResolution(new PrintAttributes.Resolution(
"Default", "default resolution", 600, 600), true);
capBuilder.setColorModes(PrintAttributes.COLOR_MODE_COLOR
| PrintAttributes.COLOR_MODE_MONOCHROME,
PrintAttributes.COLOR_MODE_COLOR);
printerInfoBuilder.setCapabilities(capBuilder.build());
Log.i(LOG_TAG, "add *the* printer to the list...");
List<PrinterInfo> discoveredPrinterList = new ArrayList<PrinterInfo>();
discoveredPrinterList.add(printerInfoBuilder.build());
this.addPrinters(discoveredPrinterList);
}
}
Thanks for the Logcat-hint, I was already wondering why I see no error but when I disabled the filter which was activated by default, then I see the following error:
09-05 20:06:05.523 27568-27568/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.android.printspooler, PID: 27568
java.lang.IllegalArgumentException: end cannot be less than zero.
at android.print.PageRange.<init>(PageRange.java:50)
at com.android.printspooler.util.PageRangeUtils.asAbsoluteRange(PageRangeUtils.java:199)
at com.android.printspooler.ui.PrintActivity$DocumentTransformer.computePagesToShred(PrintActivity.java:2620)
at com.android.printspooler.ui.PrintActivity$DocumentTransformer.<init>(PrintActivity.java:2496)
at com.android.printspooler.ui.PrintActivity.transformDocumentAndFinish(PrintActivity.java:1733)
at com.android.printspooler.ui.PrintActivity.requestCreatePdfFileOrFinish(PrintActivity.java:967)
at com.android.printspooler.ui.PrintActivity.onUpdateCompleted(PrintActivity.java:492)
at com.android.printspooler.model.RemotePrintDocument.notifyUpdateCompleted(RemotePrintDocument.java:385)
at com.android.printspooler.model.RemotePrintDocument.access$900(RemotePrintDocument.java:55)
at com.android.printspooler.model.RemotePrintDocument$1.onDone(RemotePrintDocument.java:117)
at com.android.printspooler.model.RemotePrintDocument$WriteCommand.handleOnWriteFinished(RemotePrintDocument.java:1000)
at com.android.printspooler.model.RemotePrintDocument$WriteCommand.access$2200(RemotePrintDocument.java:867)
at com.android.printspooler.model.RemotePrintDocument$WriteCommand$WriteHandler.handleMessage(RemotePrintDocument.java:1061)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:234)
at android.app.ActivityThread.main(ActivityThread.java:5526)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
0
And some lines later there I found:
09-05 20:06:06.956 1005-3292/? I/WindowState: WIN DEATH: Window{ff8499c u0 com.android.printspooler/com.android.printspooler.ui.PrintActivity}
09-05 20:06:06.956 1005-3325/? W/UserState: Not stopping printer state tracking - session destroyed
09-05 20:06:06.956 1005-3924/? D/GraphicsStats: Buffer count: 7
09-05 20:06:06.957 1005-1005/? D/RemotePrintSpooler: Error clearing print spooler client
android.os.DeadObjectException
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:503)
at android.print.IPrintSpooler$Stub$Proxy.setClient(IPrintSpooler.java:358)
at com.android.server.print.RemotePrintSpooler.clearClientLocked(RemotePrintSpooler.java:424)
at com.android.server.print.RemotePrintSpooler.access$400(RemotePrintSpooler.java:53)
at com.android.server.print.RemotePrintSpooler$MyServiceConnection.onServiceDisconnected(RemotePrintSpooler.java:456)
at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1232)
at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1246)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:234)
at com.android.server.SystemServer.run(SystemServer.java:302)
at com.android.server.SystemServer.main(SystemServer.java:174)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
09-05 20:06:06.958 26358-26358/com.geniusbytes.uploadprintservice I/UploadPrintDiscoverySession: #onStopPrinterStateTracking
09-05 20:06:06.958 26358-26358/com.geniusbytes.uploadprintservice I/UploadPrintDiscoverySession: #onStopPrinterDiscovery
09-05 20:06:06.958 26358-26358/com.geniusbytes.uploadprintservice I/UploadPrintDiscoverySession: #onDestroy
09-05 20:06:06.958 26358-26358/com.geniusbytes.uploadprintservice I/UploadPrintService: #onDisconnected()
09-05 20:06:07.006 1005-3886/? I/ActivityManager: Process com.android.printspooler (pid 27568) has died
09-05 20:06:07.006 1005-3886/? W/ActivityManager: Scheduling restart of crashed service com.android.printspooler/.model.PrintSpoolerService in 1000ms
09-05 20:06:07.188 1005-1237/? W/AppOps: Finishing op nesting under-run: uid 1000 pkg android code 24 time=1462541465446 duration=2311 nesting=0
09-05 20:06:08.024 1005-1185/? I/ActivityManager: Start proc 5263:com.android.printspooler/u0a159 for service com.android.printspooler/.model.PrintSpoolerService
09-05 20:06:09.953 391-3149/? D/audio_hw_primary: out_standby: enter: stream (0xb5bf7240) usecase(0: deep-buffer-playback)

How to resolve : android.view.WindowManager$BadTokenException - is your activity running?

I have an activity with lot of Dialogs for ex Dialog_1, Dialog_2, Dialog_3, I have implemented a WebView in one of the Dialogs lets say Dialog_2. When navigate through the Dialog's, first time the Dialog_2 with the WebView opens with no problem, but second time when I navigate to Dialog_3 and come back to Dialog_2 OR Dialog_1 to Dialog_2 and touch the WebView I get an error as mentioned bellow.
I have looked at Bad token exception but it does not work still using
if (! this.isFinishing()) {
showDialog(DIALOG_ADD_A_PERSON_BODY_MAP)
}
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
FATAL EXCEPTION: main
android.view.WindowManager$BadTokenException: Unable to add window -- token android.view.ViewRootImpl$W#41ec0fc8 is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:806)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:265)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:73)
at android.widget.ZoomButtonsController.setVisible(ZoomButtonsController.java:373)
at android.webkit.ZoomControlEmbedded.show(ZoomControlEmbedded.java:41)
at android.webkit.ZoomManager.invokeZoomPicker(ZoomManager.java:1728)
at android.webkit.WebViewClassic.startDrag(WebViewClassic.java:11645)
at android.webkit.WebViewClassic.handleTouchEventCommon(WebViewClassic.java:11170)
at android.webkit.WebViewClassic.onHandleUiTouchEvent(WebViewClassic.java:3225)
at android.webkit.WebViewClassic.onHandleUiEvent(WebViewClassic.java:3135)
at android.webkit.WebViewClassic.access$12000(WebViewClassic.java:278)
at android.webkit.WebViewClassic$PrivateHandler.dispatchUiEvent(WebViewClassic.java:13405)
at android.webkit.WebViewInputDispatcher.dispatchUiEvent(WebViewInputDispatcher.java:1078)
at android.webkit.WebViewInputDispatcher.dispatchUiEvents(WebViewInputDispatcher.java:1066)
at android.webkit.WebViewInputDispatcher.access$300(WebViewInputDispatcher.java:78)
at android.webkit.WebViewInputDispatcher$UiHandler.handleMessage(WebViewInputDispatcher.java:1392)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5365)
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:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
The Dialog code is
case DIALOG_ADD_A_PERSON_BODY_MAP:
try {
LayoutInflater inflaterBodyMap = this
.getLayoutInflater();
final View inflatorBodyMap = inflaterBodyMap
.inflate(
R.layout.dialog_incident_window_body_map,
null);
bodyMapWebView = (WebView) inflatorBodyMap.findViewById(R.id.webView);
bodyMapWebView.getSettings().setJavaScriptEnabled(true);
//bodyMapWebView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
//bodyMapWebView.getSettings().setCacheMode(WebSettings.LOAD_NO_CACHE);
bodyMapWebView.getSettings().setBuiltInZoomControls(true);
bodyMapWebView.getSettings().setSupportZoom(true);
bodyMapWebView.loadUrl("https://www.google.co.uk");
bodyMapWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
builder.setTitle("Injured person");
builder.setView(inflatorBodyMap);
builder.setPositiveButton("Next",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED_ET);
wasThePersonInjured.setText(map_incident_addAPerson.get("InjuredNotes"));
}
});
builder.setNegativeButton("Back",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
showDialog(DIALOG_ADD_A_PERSON_WAS_THE_PERSON_INJURED);
}
});
return builder.create();
} catch (Exception e) {
e.printStackTrace();
}
How do I resolve this error. Your help and suggestions much appreciated.
This happens if your Activity has been killed due to some reason and window token of your activity has expired but you try and access it anyways. So to solve this put this in onPause:
#Override
protected void onPause() {
super.onPause();
if ((progress != null) && progress.isShowing()) {
progress.dismiss();
}
progress = null;
}

How to properly handle onError inside RxJava (Android)?

I'm getting a list of installed apps on the device. It's a costly operation, so I'm using Rx for that:
Observable<List> observable = Observable.create(subscriber -> {
List result = getUserApps();
subscriber.onNext(result);
subscriber.onError(new Throwable());
subscriber.onCompleted();
});
observable
.map(s -> {
ArrayList<String> list = new ArrayList<>();
ArrayList<Application> applist = new ArrayList<>();
for (Application p : (ArrayList<Application>) s) {
list.add(p.getAppName());
applist.add(p);
}
return applist;
})
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnError(throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))
.subscribe(s -> createListView(s, view));
However, my problem is with handling errors.
Normally, user launches this screen, waits for apps to load, selects what is best and goes to next page. However, when user quickly changes the UI - app crashes with NullPointer.
Okay, so I implemented this onError. However it still doesn't work, and with above usecase it throws me this:
04-15 18:12:42.530 22388-22388/pl.digitalvirgo.safemob E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.IllegalStateException: Exception thrown on Scheduler.Worker thread. Add `onError` handling.
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:52)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:176)
at android.app.ActivityThread.main(ActivityThread.java:5419)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
at dalvik.system.NativeStart.main(Native Method)
Caused by: rx.exceptions.OnErrorNotImplementedException
at rx.Observable$31.onError(Observable.java:7134)
at rx.observers.SafeSubscriber._onError(SafeSubscriber.java:154)
at rx.observers.SafeSubscriber.onError(SafeSubscriber.java:111)
at rx.internal.operators.OperatorDoOnEach$1.onError(OperatorDoOnEach.java:70)
at rx.internal.operators.NotificationLite.accept(NotificationLite.java:147)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.pollQueue(OperatorObserveOn.java:177)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber.access$000(OperatorObserveOn.java:65)
at rx.internal.operators.OperatorObserveOn$ObserveOnSubscriber$2.call(OperatorObserveOn.java:153)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
            at android.os.Handler.handleCallback(Handler.java:730)
            at android.os.Handler.dispatchMessage(Handler.java:92)
            at android.os.Looper.loop(Looper.java:176)
            at android.app.ActivityThread.main(ActivityThread.java:5419)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:525)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1046)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:862)
            at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.Throwable
at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment.lambda$getAppList$25(ApplicationsFragment.java:267)
at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment.access$lambda$2(ApplicationsFragment.java)
at pl.digitalvirgo.safemob.fragments.wizard.ApplicationsFragment$$Lambda$3.call(Unknown Source)
at rx.Observable$1.call(Observable.java:145)
at rx.Observable$1.call(Observable.java:137)
at rx.Observable.unsafeSubscribe(Observable.java:7304)
at rx.internal.operators.OperatorSubscribeOn$1$1.call(OperatorSubscribeOn.java:62)
at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:47)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:390)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:153)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:841)
How should I properly handle this problem?
.doOnError() is an operator, and is not as such a part of the Subscriber.
Therefore, having a .doOnError() does not count as an implemented onError().
About the question in one of the comments, of course it is possible to use lambdas.
In this case simply replace
.doOnError(throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))
.subscribe(s -> createListView(s, view))
with
.subscribe(s -> createListView(s, view),
throwable -> L.e(TAG, "Throwable " + throwable.getMessage()))
My take is: you are probably using Action1 in
.subscribe(s -> createListView(s, view));
You will need to replace it with Subscriber or Observer which has abstract method onError. This method will be called from subscriber.onError(new Throwable());
EDIT: This is how I would do it. Upon closer look I think the main problem in your code is the early part where you call subscriber.onError even when there's no error. You probably don't need map either because you are technically passing data as-is without manipulation. But I left it in case it is needed later.
Observable.create(new Observable.OnSubscribe<Application>() {
#Override
public void call(Subscriber<? super Application> subscriber) {
List result = getUserApps();
if (result != null){
for (Application app : result){
subscriber.onNext(app);
}
subscriber.onComplete();
}else{
subscriber.onError(new IOException("no permission / no internet / etc"));
//or if this is a try catch event you can pass the exception
}
}
})
.subscribeOn(Schedulers.io())//the thread *observer* runs in
.observeOn(AndroidSchedulers.mainThread())//the thread *subscriber* runs in
.map(new Func1<Application, String>() {
// Mapping methods are where data are manipulated.
// You can simply skip this and
//do the same thing in Subscriber implementation
#Override
public String call(Application application) {
return application.getName();
}
}).subscribe(new Subscriber<String>() {
#Override
public void onCompleted() {
Toast.makeText(context, "completed", Toast.LENGTH_SHORT).show();
//because subscriber runs in main UI thread it's ok to do UI stuff
//raise Toast, play sound, etc
}
#Override
public void onError(Throwable e) {
Log.e("getAppsError", e.getMessage());
//raise Toast, play sound, etc
}
#Override
public void onNext(String s) {
listAdapter.add(s);
}
});
Here is the newbie response (because I am new in javarx and finally fix this issue) :
Here is your implementation :
Observable.create(new Observable.OnSubscribe<RegionItem>() {
#Override
public void call(Subscriber<? super RegionItem> subscriber) {
subscriber.onError(new Exception("TADA !"));
}
})
.doOnNext(actionNext)
.doOnError(actionError)
.doOnCompleted(actionCompleted)
.subscribe();
In this previous implementation, when I subscribe I trigger the error flow ... and I get an application crash.
The problem is that you HAVE TO manage the error from the subscribe() call. The "doOnError(...)" is just a kind of helper that clone the error and give you a new place to do some action after an error. But it doesn't Handle the error.
So you have to change your code with that :
Observable.create(new Observable.OnSubscribe<RegionItem>() {
#Override
public void call(Subscriber<? super RegionItem> subscriber) {
subscriber.onError(new Exception("TADA !"));
}
})
.subscribe(actionNext, actionError, actionCompleted);
Not sure about the real explanation, but this is how I fix it. Hope it will help.

License Verification Library in Wallpaper

I am currently trying to implement Google's LVL into my wallpaper but seem to have run into an issue with an exception I am not familiar with. I found this Question which helped me greatly, LVL licensing in a Live Wallpaper?. One of the suggestions is to place code within the Engine and I opted to place it in the Class above. The code seems to compile fine but on run time I get an exception, apparently for my Public Key.
FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to create service <my package>.MyWallpaper: java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2076)
at android.app.ActivityThread.access$2500(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:993)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3835)
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:847)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
at com.android.vending.licensing.LicenseChecker.generatePublicKey(LicenseChecker.java:121)
at com.android.vending.licensing.LicenseChecker.<init>(LicenseChecker.java:92)
at com.metastable.epicvis.vis1.ScopeVisualizer.onCreate(ScopeVisualizer.java:41)
at android.app.ActivityThread.handleCreateService(ActivityThread.java:2066)
... 10 more
Caused by: java.security.spec.InvalidKeySpecException: java.io.IOException: corrupted stream - out of bounds length found
at org.bouncycastle.jce.provider.JDKKeyFactory.engineGeneratePublic(JDKKeyFactory.java:92)
at org.bouncycastle.jce.provider.JDKKeyFactory$RSA.engineGeneratePublic(JDKKeyFactory.java:396)
at java.security.KeyFactory.generatePublic(KeyFactory.java:177)
at com.android.vending.licensing.LicenseChecker.generatePublicKey(LicenseChecker.java:112)
... 13 more
Here is the code that I use:
public class MyWallpaper extends WallpaperService implements LicenseCheckerCallback {
private LicenseChecker mChecker;
private static final String BASE64_PUBLIC_KEY = "My public key from google";
private byte[] salt = new byte[] {<20 random int>};
private String deviceId;
private AESObfuscator aes;
#Override
public void onCreate() {
super.onCreate();
deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
aes = new AESObfuscator(salt, getPackageName(), deviceId);
mChecker = new LicenseChecker(this, new ServerManagedPolicy(this, aes), BASE64_PUBLIC_KEY);
mChecker.checkAccess(this);
}
#Override
public void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
#Override
public Engine onCreateEngine() {
return new VisualizerEngine();
}
class MyEngine extends Engine implements SharedPreferences.OnSharedPreferenceChangeListener {
<Unrelevant code removed>
}
#Override
public void allow() {
Toast.makeText(this, "Allowed", Toast.LENGTH_SHORT);
}
#Override
public void dontAllow() {
Toast.makeText(this, "Not Allowed", Toast.LENGTH_SHORT);
}
#Override
public void applicationError(ApplicationErrorCode errorCode) {
// TODO Auto-generated method stub
}
}
Is there a certain way I should format my public key or is it something entirely different?
The exception comes from : mChecker = new LicenseChecker(this, new ServerManagedPolicy(this, aes), BASE64_PUBLIC_KEY);
Any advice would be greatly appreciated.
I have since figured out the issue, apparently I'm terrible and copy and pasting. In stead of click dragging and selecting my key, which I did many times and continued to fail, I simply triple clicked and it copied properly. Heh.

Categories

Resources