using AsyncTask to create a GLSurfaceView in the background - java

I am have a little trouble understanding the AsyncTask and whether or not i can actually do what i am trying to do.
Within my onCreate method of my activity I am doing a few things, one of which is to create a GLSurfaceView and set my renderer. I want this process to be done by an AsyncTask in the background.
Here is my code
public class ActivityTest extends BaseGameActivity
{
/** Hold a reference to our GLSurfaceView */
private MYGLSurfaceView mGLSurfaceView;
public MYGamePlay GamePlay;
public GoogleApiClient mGoogleApiClient = null;
private AdView adView;
private static final String AD_UNIT_ID = "*******************************";
private Button RotateButton;
private CreateRenderer mCreateRenderer;
private TextView Score;
private RelativeLayout layout;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Dialog loader_dialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
loader_dialog.setContentView(R.layout.loading_screen);
loader_dialog.show();
// Create an ad.
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId(AD_UNIT_ID);
// create the layout that holds the combined game layout
layout = new RelativeLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device.
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("***********************").build();
// Start loading the ad in the background.
adView.loadAd(adRequest);
Score = new TextView(this);
Score.setText(" 0");
RelativeLayout.LayoutParams scoreParams = new
RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
Score.setLayoutParams(scoreParams);
Typeface tf = Typeface.createFromAsset(getAssets(),"Fonts/D3Euronism_b.ttf");
Score.setTextSize(getResources().getDimension(R.dimen.textsize));
Score.setTypeface(tf);
Score.setTextColor(Color.parseColor("#FDAA03"));
LayoutInflater inflater = (LayoutInflater) this.getSystemService(this.LAYOUT_INFLATER_SERVICE);
View userInterface = inflater.inflate(R.layout.user_interface, null);
RotateButton = (Button) userInterface.findViewById(R.id.rotbutton);
RotateButton.setOnTouchListener(new OnTouchListener()
{
#Override
public boolean onTouch(View v, MotionEvent event)
{
//irrelivant
}
});
RelativeLayout.LayoutParams adParams =
new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
adParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
mCreateRenderer = new CreateRenderer(this, Score, mGLSurfaceView);
mCreateRenderer.execute();
layout.addView(userInterface);
layout.addView(Score);
layout.addView(adView, adParams);
setContentView(layout);
}
#Override
protected void onResume()
{
// The activity must call the GL surface view's onResume() on activity onResume().
super.onResume();
//mGLSurfaceView.onResume();
}
#Override
protected void onPause()
{
// The activity must call the GL surface view's onPause() on activity onPause().
super.onPause();
//mGLSurfaceView.onPause();
}
private class CreateRenderer extends AsyncTask<Void, Void, GLSurfaceView>
{
Context baseClassContext;
RBGLSurfaceView myGLSurfaceView;
TextView GameScore;
public CreateRenderer(Context mContext, TextView mScore, RBGLSurfaceView rGLSurfaceView )
{
baseClassContext = mContext;
GameScore = mScore;
myGLSurfaceView = rGLSurfaceView;
}
#Override
protected GLSurfaceView doInBackground(Void... params)
{
final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
final ConfigurationInfo configurationInfo = activityManager.getDeviceConfigurationInfo();
final boolean supportsEs2 = configurationInfo.reqGlEsVersion >= 0x20000;
if (supportsEs2)
{
// Request an OpenGL ES 2.0 compatible context.
/*line 226*/ myGLSurfaceView = new MYGLSurfaceView(baseClassContext); new GLSurfaceView(baseClassContext);
myGLSurfaceView.setEGLContextClientVersion(2);
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
// Set the renderer to our demo renderer, defined below.
mGoogleApiClient = getApiClient();
layout.addView(myGLSurfaceView);
myGLSurfaceView.setRenderer(new MYRenderer(baseClassContext, GameScore, mGoogleApiClient),displayMetrics);
}
else
{
// This is where you could create an OpenGL ES 1.x compatible
// renderer if you wanted to support both ES 1 and ES 2.
}
return myGLSurfaceView;
}
#Override
protected void onPostExecute(GLSurfaceView result)
{
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
}
I have been reading conflicting things about AsyncTask like whether i can create a contstructor and pass things to it.
Any way it fails on line 226 which i have marked in the code above.
Here is the logCat
09-05 09:29:29.554: E/AndroidRuntime(7585): FATAL EXCEPTION: AsyncTask #2
09-05 09:29:29.554: E/AndroidRuntime(7585): java.lang.RuntimeException: An error occured while executing doInBackground()
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.lang.Thread.run(Thread.java:856)
09-05 09:29:29.554: E/AndroidRuntime(7585): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.os.Handler.<init>(Handler.java:197)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.os.Handler.<init>(Handler.java:111)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.view.SurfaceView$1.<init>(SurfaceView.java:122)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.view.SurfaceView.<init>(SurfaceView.java:122)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.opengl.GLSurfaceView.<init>(GLSurfaceView.java:213)
09-05 09:29:29.554: E/AndroidRuntime(7585): at com.game.cuberush.MYGLSurfaceView.<init>(MYGLSurfaceView.java:34)
09-05 09:29:29.554: E/AndroidRuntime(7585): at com.game.test.ActivityTest$CreateRenderer.doInBackground(ActivityTest.java:226)
09-05 09:29:29.554: E/AndroidRuntime(7585): at com.game.test.ActivityTest$CreateRenderer.doInBackground(ActivityTest.java:1)
09-05 09:29:29.554: E/AndroidRuntime(7585): at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-05 09:29:29.554: E/AndroidRuntime(7585): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
09-05 09:29:29.554: E/AndroidRuntime(7585): ... 4 more
this is the first time i have tried to use AsyncTask so i realise i am probably making a mess with it. So any help with this would be great
EDIT method using annotations still produces the same result the code a put the #Background annotation doesnt seem to be running on a seperate thread as the oncreate is still waiting for it, unless i am doing it wrong
called un onCreate
CreateRender(mGLSurfaceView, this, Score, loader_dialog, mGoogleApiClient, displayMetrics);
method CreateRender
#Background
protected void CreateRender(MYGLSurfaceView myGLSurfaceView, Context mContext, TextView mScore, Dialog mDialog, GoogleApiClient gAPI, DisplayMetrics mDispMet )
{
myGLSurfaceView.setRenderer(new MYRenderer(mContext, mScore, mDialog, gAPI),mDispMet);
mGLSurfaceView = returnResult(myGLSurfaceView);
}
#UiThread
MYGLSurfaceView returnResult(MYGLSurfaceView res)
{
return res;
}
this must be wrong

If you get crazy using AsyncTask i prefer to try AndroidAnnotations. Instead of writing a complete class to handle your background tasks, you just use a #Background annotation over your method. This concept saves a lot of code and it works!
This is an example from the android annotations wiki at github:
#EActivity(R.layout.translate) // Sets content view to R.layout.translate
public class TranslateActivity extends Activity {
#ViewById // Injects R.id.textInput
EditText textInput;
#ViewById(R.id.myTextView) // Injects R.id.myTextView
TextView result;
#AnimationRes // Injects android.R.anim.fade_in
Animation fadeIn;
#Click // When R.id.doTranslate button is clicked
void doTranslate() {
translateInBackground(textInput.getText().toString());
}
#Background // Executed in a background thread
void translateInBackground(String textToTranslate) {
String translatedText = callGoogleTranslate(textToTranslate);
showResult(translatedText);
}
#UiThread // Executed in the ui thread
void showResult(String translatedText) {
result.setText(translatedText);
result.startAnimation(fadeIn);
}
// [...]
}

Ive been wrestling with AsyncTask the last couple of days myself. It seems to have some kind of an aversion to surfaces.
I would suggest a change of approach -- create the view in onCreate/onResume ( depending on your needs ) and avoid tying in nonexistent surfaces with AsyncTask.
This approach worked for me, hope it does for you as well!

Your basic problem is that you try to change the UI from a non-ui thread. From the documentation:
Additionally, the Andoid UI toolkit is not thread-safe. So, you must not manipulate your UI from a worker thread—you must do all manipulation to your user interface from the UI thread.
Asynctask is actually a convience for that. It does some background work off the main thread and then runs the onPostExecute() on the ui-thread. That means 2 things: first you can change the ui in onPostExecute() and everything done here will be executed serial to the ui (so it could be blocked)
There is the usual quickfix for that with
activity.runOnUiThread(new Runnable() {
public void run() {
//this will be executed on the ui thread
}
});
which will not help you since it will then block the ui again. Im actually not sure if you can do what you want, since some things just can be done in the background (e.g. inflating a real complex xml in onCreateView()). You could try to create your own looper like:
Class used to run a message loop for a thread. Threads by default do not have a message loop associated with them; to create one, call prepare() in the thread that is to run the loop, and then loop() to have it process messages until the loop is stopped.
class LooperThread extends Thread {
public Handler mHandler;
public void run() {
Looper.prepare();
mHandler = new Handler() {
public void handleMessage(Message msg) {
// process incoming messages here
}
};
Looper.loop();
}
}
and handle your surfaceview there, but Im not sure that works.
Further resouces:
Run SurfaceView off UI Thread
Can't create handler inside thread that has not called Looper.prepare()

Related

Cannot Update Image from Runnable - Android

I have the following class that implements runnable. When I start the thread I get an error preventing me from updating the image. I have tried setting the image as you will see in the runOnUiThread function but it doesn't work. I would like to ultimately update the image every x seconds but I cannot seem to do this unless I put the thread inside the main activity class. Once I move it out nothing I try works.
public class Test implements Runnable {
MainActivity activity;
ArrayList<Media> media = new ArrayList<Media>();
public Test(MainActivity activity){
this.activity = activity;
}
public void run(){
activity.runOnUiThread(new Runnable(){
#Override
public void run() {
ImageView img= (ImageView) activity.findViewById(R.id.imageView1);
img.setImageResource(R.drawable.ic_launcher_foreground);
}
});
}
}
In MainActivity.java's onCreate() function I start the thread.
Test p = new Test(this);
Thread t = new Thread(p);
t.start();
Then my error:
2019-10-31 19:26:47.274 5407-5407/com.desotomatrix.digitalsignageplayer E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.desotomatrix.digitalsignageplayer, PID: 5407
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.desotomatrix.digitalsignageplayer.Test$1.run(Test.java:30)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:209)
at android.app.ActivityThread.main(ActivityThread.java:7021)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:486)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:872)

Android Game development E/JavaBinder: FAILED BINDER TRANSACTION

How to deal with E/JavaBinder: FAILED BINDER TRANSACTION that crashes the app?
I am making an android game using a SurfaceView.
I am also using a dedicated thread for the infinite Game-Loop itself, which contains both an update() method, as well as a draw() method.
The update() method updates characters position(logic) and sprites, while the draw() method draws to the canvas.
The dedicated thread handles both update() and draw() since they need to be synchronized.
The onTouchEvents (user clicks) are handled by the main thread.
Although I cannot tell for sure, I suspect that I am getting this error: E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! , because
both the draw() method and the update() method call other methods that call other methods and so on.. resulting in an almost a recursive behavior.
For example my update() method, calls characterOne.update().. which then calls characterOneSpells.update() which then calls spellOne.update() and so on... same thing for the draw(). I suspect that this overflows the bind buffer or something like that.. I am not sure.. and all of this is happening in an infinite loop infinite amount of times.
Note that I took this approach ( methods call methods that call other methods) because logically it made sense to me that a character should be responsible to draw itself, and a spell should be responsible to draw itself, rather than the character be responsible to draw and update the spells and so on. It made sense to me that every object should be responsible to draw itself and update itself, and that is my reasoning, I might be wrong, please let me know what you think.
Now, I am new to game making, and in fact this is my first game, so please take it easy on me, I am trying to learn!
Sample of my code and the error log can be found below.
Any insight to why I am getting this E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! and how to fix it would be very much appreciated! Also feel free to suggest a better design or approach, since I am trying to learn.
Thank you!
I marked the important parts of the code with ** Important ** comment to make things easier.`
ERROR LOG:
11-17 17:07:30.132 934-1460/? E/JavaBinder: !!! FAILED BINDER TRANSACTION !!!
11-17 17:07:30.388 1451-1451/? E/RecyclerView: No adapter attached; skipping layout
11-17 17:07:32.328 934-992/? E/InputDispatcher: channel '329e61e3 com.amazon.firelauncher/com.amazon.firelauncher.Launcher (server)' ~ Channel is unrecoverably broken and will be disposed!
11-17 17:07:32.407 146-146/? E/lowmemorykiller: Error opening /proc/2493/oom_score_adj; errno=2
11-17 17:07:32.442 934-1011/? E/WifiService: Multicaster binderDied
11-17 17:07:32.462 146-146/? E/lowmemorykiller: Error opening /proc/2493/oom_score_adj; errno=2
11-17 17:07:32.464 146-146/? E/lowmemorykiller: Error opening /proc/2493/oom_score_adj; errno=2
11-17 17:07:32.464 146-146/? E/lowmemorykiller: Error opening /proc/1217/oom_score_adj; errno=2
11-17 17:07:36.426 6868-6868/? E/cr_AWVDeploymentClient: Chromium Version = v59 key doesn't exist. So, default version config will be used.
11-17 17:07:36.428 6868-6868/? E/cr_AWVDeploymentClient: Default device config doesn't exist
11-17 17:07:39.313 934-992/? E/InputDispatcher: channel '11e88fc0 info.evyatar.mystrategygame/info.evyatar.mystrategygame.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
11-17 17:07:40.905 7010-7051/? E/SQLiteLog: (283) recovered 44 frames from WAL file /data/user/0/com.amazon.firelauncher/databases/producer.db-wal
11-17 17:07:41.091 7010-7059/? E/SQLiteLog: (283) recovered 90 frames from WAL file /data/user/0/com.amazon.firelauncher/databases/CardDeviceAgentDB-wal
11-17 17:07:43.558 7010-7010/? E/RecyclerView: No adapter attached; skipping layout
11-17 17:07:43.622 7089-7089/? E/TimeoutManagerClient: bindService() Failed to bind to ECService
11-17 17:07:43.631 7165-7165/? E/Dagger2: ApplicationModule context already set
11-17 17:07:44.924 7089-7311/? E/...iceDataCommunication: Got a RemoteMAPException
com.amazon.identity.auth.device.framework.RemoteMAPException: com.amazon.identity.auth.device.api.DeviceDataStoreException: Key ke_device was not found in the device data store. This device does not support ke_device. This error is expected if the device not support ke_device.
at com.amazon.identity.auth.device.framework.SecureContentResolver.acquireContentProviderClient(SecureContentResolver.java:118)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.retriveValueFromCentralStore(DeviceDataCommunication.java:59)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.getValue(DeviceDataCommunication.java:52)
at com.amazon.identity.auth.device.devicedata.DeviceDataStoreSystemPropertyDecorator.getValue(DeviceDataStoreSystemPropertyDecorator.java:52)
at com.amazon.identity.auth.device.api.DeviceDataStore.getValue(DeviceDataStore.java:96)
at com.amazon.avod.identity.DeviceProperties.isKidsEditionDevice(DeviceProperties.java:374)
at com.amazon.avod.identity.DeviceProperties.initialize(DeviceProperties.java:201)
at com.amazon.avod.core.ApplicationComponents$InitializeDeviceProperties.initialize(ApplicationComponents.java:543)
at com.amazon.avod.core.ApplicationComponents$InitializeRunnable.run(ApplicationComponents.java:787)
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:818)
Caused by: com.amazon.identity.auth.device.api.DeviceDataStoreException: Key ke_device was not found in the device data store. This device does not support ke_device. This error is expected if the device not support ke_device.
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication$1.useContentProviderClient(DeviceDataCommunication.java:93)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication$1.useContentProviderClient(DeviceDataCommunication.java:61)
at com.amazon.identity.auth.device.framework.SecureContentResolver.acquireContentProviderClient(SecureContentResolver.java:112)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.retriveValueFromCentralStore(DeviceDataCommunication.java:59) 
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.getValue(DeviceDataCommunication.java:52) 
at com.amazon.identity.auth.device.devicedata.DeviceDataStoreSystemPropertyDecorator.getValue(DeviceDataStoreSystemPropertyDecorator.java:52) 
at com.amazon.identity.auth.device.api.DeviceDataStore.getValue(DeviceDataStore.java:96) 
at com.amazon.avod.identity.DeviceProperties.isKidsEditionDevice(DeviceProperties.java:374) 
at com.amazon.avod.identity.DeviceProperties.initialize(DeviceProperties.java:201) 
at com.amazon.avod.core.ApplicationComponents$InitializeDeviceProperties.initialize(ApplicationComponents.java:543) 
at com.amazon.avod.core.ApplicationComponents$InitializeRunnable.run(ApplicationComponents.java:787) 
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:818) 
11-17 17:07:45.701 7010-7085/? E/...iceDataCommunication: Got a RemoteMAPException
com.amazon.identity.auth.device.framework.RemoteMAPException: com.amazon.identity.auth.device.api.DeviceDataStoreException: Key re_device was not found in the device data store. This device does not support re_device. This error is expected if the device not support re_device.
at com.amazon.identity.auth.device.framework.SecureContentResolver.acquireContentProviderClient(SecureContentResolver.java:118)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.retriveValueFromCentralStore(DeviceDataCommunication.java:59)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication.getValue(DeviceDataCommunication.java:52
at java.lang.Thread.run(Thread.java:818)
Caused by: com.amazon.identity.auth.device.api.DeviceDataStoreException: Key re_device was not found in the device data store. This device does not support re_device. This error is expected if the device not support re_device.
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication$1.useContentProviderClient(DeviceDataCommunication.java:93)
at com.amazon.identity.auth.device.devicedata.DeviceDataCommunication$1.useContentProviderClient(DeviceDataCommunication.java:61)
at com.amazon.firelauncher.services.MapCache.updateDeviceData(MapCache.java:579) 
at com.amazon.firelauncher.services.MapCache.access$700(MapCache.java:47) 
at com.amazon.firelauncher.services.MapCache$3.run(MapCache.java:491) 
at com.amazon.firelauncher.services.BackgroundExecutor$InternalRunnable.run(BackgroundExecutor.java:180) 
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:818) 
11-17 17:07:45.930 7343-7343/? E/SQLiteLog: (283) recovered 120 frames from WAL file /data/securedStorageLocation/com.amazon.providers.contentsupport/contentsupport.db-wal
11-17 17:07:45.979 7343-7343/? E/SQLiteLog: (284) automatic index on languages(packageId)
11-17 17:07:46.007 7343-7343/? E/SQLiteLog: (284) automatic index on languages(packageId)
11-17 17:07:47.386 7010-7417/? E/F_C.ArcusRemoteConfigur: No valid offline remote setting found for the current device, not setting default
java.lang.Exception: Error getting the baseline setting for Arcus config cms
at com.amazon.firelauncher.reccardproducer.settings.OfflineSetting.value(OfflineSetting.java:106)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
Caused by: java.lang.Exception: Exception reading from cms/baseline.json
at com.amazon.firelauncher.reccardproducer.settings.JSONFile.value(JSONFile.java:43)
at com.amazon.firelauncher.reccardproducer.settings.JSONFile.value(JSONFile.java:14)
at com.amazon.firelauncher.reccardproducer.settings.OfflineSetting.value(OfflineSetting.java:88)
at com.amazon.firelauncher.reccardproducer.settings.OfflineSetting.value(OfflineSetting.java:22) 
at com.amazon.firelauncher.reccardproducer.arcus.ArcusRemoteConfiguration$1.map(ArcusRemoteConfiguration.java:67) 
at com.amazon.firelauncher.reccardproducer.arcus.ArcusRemoteConfiguration$1.map(ArcusRemoteConfiguration.java:60) 
at com.amazon.firelauncher.reccardproducer.arcus.ArcusRemoteConfiguration.initialize(ArcusRemoteConfiguration.java:117) 
at com.amazon.firelauncher.reccardproducer.cards.RecommendationsController.getInstance(RecommendationsController.java:111) 
at com.amazon.firelauncher.reccardproducer.ProducerService.onHandleIntent(ProducerService.java:57) 
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.os.HandlerThread.run(HandlerThread.java:61) 
Caused by: java.io.FileNotFoundException: cms/baseline.json
at android.content.res.AssetManager.openAsset(Native Method)
at android.content.res.AssetManager.open(AssetManager.java:313)
at android.content.res.AssetManager.open(AssetManager.java:287)
at com.amazon.firelauncher.reccardproducer.settings.JSONFile.value(JSONFile.java:29)
at com.amazon.firelauncher.reccardproducer.settings.JSONFile.value(JSONFile.java:14) 
at com.amazon.firelauncher.reccardproducer.settings.OfflineSetting.value(OfflineSetting.java:88) 
at com.amazon.firelauncher.reccardproducer.cards.RecommendationsController.getInstance(RecommendationsController.java:111) 
at com.amazon.firelauncher.reccardproducer.ProducerService.onHandleIntent(ProducerService.java:57) 
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:135) 
at android.os.HandlerThread.run(HandlerThread.java:61) 
11-17 17:07:47.400 7010-7417/? E/F_C.FireDeviceAttribute: BuildNumber is not a valid String attribute (wrong type: Integer)
11-17 17:07:47.416 7010-7417/? E/F_C.ArcusParameters: Exception getting attribute %s, no attribute added
java.lang.NullPointerException: attrValue cannot be null
at com.amazonaws.mobileconnectors.remoteconfiguration.internal.gear.Checks.checkNotNull(Checks.java:20)
at com.amazonaws.mobileconnectors.remoteconfiguration.internal.AttributesImpl.addAttributePrivate(AttributesImpl.java:193)
at com.amazonaws.mobileconnectors.remoteconfiguration.internal.AttributesImpl.addAttribute(AttributesImpl.java:103)
at com.amazon.firelauncher.reccardproducer.arcus.ArcusParameters.decorateManager(ArcusParameters.java:87)
at com.amazon.firelauncher.reccardproducer.arcus.ArcusRemoteConfiguration.initialize(ArcusRemoteConfiguration.java:119)
at com.amazon.firelauncher.reccardproducer.cards.RecommendationsController.getInstance(RecommendationsController.java:111)
at com.amazon.firelauncher.reccardproducer.ProducerService.onHandleIntent(ProducerService.java:57)
at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:65)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.os.HandlerThread.run(HandlerThread.java:61)
Sample Code
public class GameLoop extends SurfaceView implements SurfaceHolder.Callback {
private Context myContext;
private SurfaceHolder mySurfaceHolder;
private Bitmap backgroundImg;
private int screenW = 1;
private int screenH = 1;
private boolean running = false;
private boolean onTitleScreen = true;
private GameLoopThread thread;
private int backgroundOrigW;
private int backgroundOrigH;
private float scaleW;
private float scaleH;
private float drawScaleW;
private float drawScaleH;
private int fingerX, fingerY;
private boolean isDragging = false;
SingltonAssetsObject mSingltonAssetsObject;
private boolean gameOver;
Point userClickPoint;
//Characters
CharacterTypeOne characterFighterOne,characterFighterTwo,characterFighterThree;
CharacterTypeTwo CharacterMage;
public GameLoop(Context context, AttributeSet attrs) {
super(context, attrs);
SurfaceHolder holder = getHolder();
holder.addCallback(this);
//init clickRectangle
userClickPoint = new Point();
//creates the gameLoop thread DRAW THREAD
thread = new GameLoopThread(holder,context);
setFocusable(true);
}
public void initCharacters(){
mSingltonAssetsObject = SingltonAssetsObject.getInstance(myContext,scaleW,scaleH);
characterFighterOne = new characterFighterOne(myContext,1000,1,150,350,100,15,1.0,scaleW,scaleH,drawScaleW,drawScaleH,screenW,screenH);
characterFighterTwo = new characterFighterOne(myContext,1001,67,350,350,100,15,1.0,scaleW,scaleH,drawScaleW,drawScaleH,screenW,screenH);
characterFighterThree = new characterFighterOne(myContext,1002,99,550,350,1000,15,1.0,scaleW,scaleH,drawScaleW,drawScaleH,screenW,screenH);
characterMage = new characterMage(myContext,50,28,650,250,100,15,0.1,scaleW,scaleH,drawScaleW,drawScaleH,screenW,screenH);
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return thread.doTouchEvent(event);
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
thread.setSurfaceSize(width, height);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
thread.setRunning(true);
if (thread.getState() == Thread.State.NEW) {
thread.start();
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
thread.setRunning(false);
}
class GameLoopThread extends Thread{
public GameLoopThread(SurfaceHolder surfaceHolder, Context context){
//initialzied in inner class and not outter because this variable will act as a lock and will be shard with all threads
mySurfaceHolder = surfaceHolder;
myContext = context;
//the background image of the title screen
backgroundImg = BitmapFactory.decodeResource(context.getResources(), R.drawable.title);
backgroundOrigW = backgroundImg.getWidth();
backgroundOrigH = backgroundImg.getHeight();
}
//This method is the main game loop
public void run() {
while (running) {
try { //lock canvas for drawing
c = mySurfaceHolder.lockCanvas(null);
synchronized (mySurfaceHolder) {
if (!gameOver)
{
//** important ***
updateAnimationsAndPosition();
}
// **important **
draw(c);
}
} finally {
if (c != null) { //unlock canvas
mySurfaceHolder.unlockCanvasAndPost(c);
}
}
} //while loop ends
} //run Method ends (gameLOOP)
//This method will draw everything to the screen
public void draw(Canvas canvas){
canvas.drawBitmap(backgroundImg, 0, 0, null);
if (!onTitleScreen) {
/* **Important**
Note: characterFighterOne.draw(canvas) calls spells.draw(canvas)
which calls spellOne.draw(canvas).. which call spellIndicartor.draw(canvas)
and so on... might be cauing the isssue?*/
characterFighterOne.draw(canvas);
characterFighterTwo.draw(canvas);
characterFighterThree.draw(canvas);
characterMage.draw(canvas);
}
}
//This method updates the animations, for example changes image every tick
public void updateAnimationsAndPosition(){
if(!onTitleScreen){
/***Important**
Note: characterFighterOne.updateAnimationsAndPosition() calls spells.update()
which calls spellOne.update().. which call spellIndicartor.update()
and so on... might be causing the issue?*/
characterFighterOne.updateAnimationsAndPosition();
characterFighterTwo.updateAnimationsAndPosition();
characterFighterThree.updateAnimationsAndPosition();
characterMage.updateAnimationsAndPosition();
}
}
public void setSurfaceSize(int width, int height) {
synchronized (mySurfaceHolder) {
screenW = width;
screenH = height;
backgroundImg = Bitmap.createScaledBitmap(backgroundImg, width, height, true);
drawScaleW = (float) screenW / 960; //screen/background width image
drawScaleH = (float) screenH / 640;
}
}
//This method is in charge of user input ( clicks on screen, and how to respond to them)
public boolean doTouchEvent(MotionEvent event){
if(!onTitleScreen){
characterFighterOne.doTouchEvent(event);
characterFighterTwo.doTouchEvent(event);
characterFighterThree.doTouchEvent(event);
characterMage.doTouchEvent(event);
userClickPoint.set((int)event.getX(),(int)event.getY());
}
synchronized (mySurfaceHolder) {
int eventaction = event.getAction();
int X = (int)event.getX();
int Y = (int)event.getY();
switch (eventaction ) {
case MotionEvent.ACTION_DOWN:
if(!gameOver){
fingerX = X;
fingerY = Y;
if (!onTitleScreen) {
}
}
break;
case MotionEvent.ACTION_MOVE:// used for dragging purposes
break;
case MotionEvent.ACTION_UP:
//Here I load all the images to memory ( while on the titleScreen normal size & scaled, find a better place, maybe OnCreate, leave for now)
if (onTitleScreen) {
backgroundImg = BitmapFactory.decodeResource(myContext.getResources(), R.drawable.background);
backgroundImg = Bitmap.createScaledBitmap(backgroundImg, screenW, screenH, true);
onTitleScreen = false;
scaleW = (float) screenW/ (float) backgroundOrigW;
scaleH = (float) screenH/ (float) backgroundOrigH;
initCharacters();
}
if (gameOver) {
gameOver = false;
}
break;
}
}
return true;
}
//This method enables and disables the Thread
public void setRunning(boolean b) {
running = b;
}
}
}

java.lang.IllegalStateException: AssetManager has been finalized

I went to sleep yesterday with my app working and today when I tried to run it won't start at all. As soon as I try to open it crashes with a java.lang.IllegalStateException. I've gone several commits back in my code just to rule out it was something I did recently and still. This makes no sense, how can an app just stop working over night? I've looked for the error in the internet and there is not a lot of useful information about it. Is this really an odd error?
Here's the complete stack trace:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.IllegalStateException: AssetManager has been finalized!
at android.os.Parcel.readException(Parcel.java:1439)
at android.os.Parcel.readException(Parcel.java:1385)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:1947)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1419)
at android.app.Activity.startActivityForResult(Activity.java:3390)
at android.app.Activity.startActivity(Activity.java:3583)
at com.android.launcher2.Launcher.startActivity(Launcher.java:2442)
at com.android.launcher2.Launcher.startActivitySafely(Launcher.java:2469)
at com.android.launcher2.AppsCustomizePagedView.onClick(AppsCustomizePagedView.java:584)
at android.view.View.performClick(View.java:4240)
at android.view.View$PerformClick.run(View.java:17721)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5136)
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:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Since like I said it doesn't seem to be anything that I did I'm not sure what code to post. But given that the app crashes on start here's the code for the two main classes that are supposed to start first:
App
public class App extends Application {
private static App instance;
private static final String TAG = "Starter";
#Override
public void onCreate() {
super.onCreate();
instance = this;
// Enable Local Datastore.
Parse.enableLocalDatastore(this);
//TODO: Register subclasses
// ParseObject.registerSubclass(Challenge.class);
//Parse server
Log.d(TAG, "Initializing Parse");
Parse.initialize(new Parse.Configuration.Builder(this)
.applicationId(getString(R.string.parse_app_id))
.clientKey(getString(R.string.parse_client_key))
.server(getString(R.string.server_address)).build()
);
//Facebook
if (AccessToken.getCurrentAccessToken() == null)
ParseFacebookUtils.initialize(this);
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// Optionally enable public read access.
defaultACL.setPublicReadAccess(true);
defaultACL.setPublicWriteAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Log.d(TAG, "Parse ready");
}
public static App getInstance(){
return instance;
}
}
SplashActivity
public class SplashActivity extends AppCompatActivity {
private static final String TAG = "Splash";
private boolean firstTime = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_splash);
firstTime = getSharedPreferences(Constants.GENERAL_SHARED_PREFS, MODE_PRIVATE)
.getBoolean(Constants.FIRSTTIME, true);
if (isLoggedIn())
if (firstTime)
startActivity(new Intent(SplashActivity.this, FirstTimeActivity.class));
else
startActivity(new Intent(SplashActivity.this, MenuActivity.class));
else {
Log.d(TAG, "Calling Home");
startActivity(new Intent(SplashActivity.this, WelcomeActivity.class));
finish();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
super.onDestroy();
}
public boolean isLoggedIn() {
AccessToken accessToken = AccessToken.getCurrentAccessToken();
String parseSession = ParseUser.getCurrentUser().getSessionToken();
return parseSession != null;
}
}
Your stacktrace links to this class in the AOSP.
I think this crash has nothing to do with your app, but as an error in the Launcher class. Try installing from USB debugging and see if that works.
But there are still some details that are blurry. These lines are (from bottom of the stacktrace to the top) the lines that cause problems in com.android.launcher2 package:
https://android.googlesource.com/platform/packages/apps/Launcher2/+/android-4.2.2_r1/src/com/android/launcher2/AppsCustomizePagedView.java#584
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2469
https://android.googlesource.com/platform/packages/apps/Launcher2/+/master/src/com/android/launcher2/Launcher.java#2442
From this error, I assume you are using a Nexus or Pixel (or any device with the unaltered source code, meaning stock android.).
From what I can tell from this error, this is not an error related to your app. It appears to be an issue with the launcher you are using. Try installing from USB debugging, or change launcher, and see if that works. Try rebooting your device as well.
Further, from what I see of your code, there are no parcelable classes in use
This error can also be caused when Instant Run loses connection with the Android Emulator as a result of which new app changes are not persisted in the emulator.
Running the app again will solve the issue.

BadTokenException even after referring to Activity and not the application context

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.

Android - Using thread

I have three class in my app.
First extends Activity
public class TestProjActivity extends Activity {
/** Called when the activity is first created. */
String my ="";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new Thread(new Runnable() {
public void run() {
Translation th = new Translation(this);
my = th.doSomeJob();
}
}).start();
Log.d("ONCREATE", my);
}
}
Second is DBHelper
public class DBHelper {
private final Context myContext;
public DBHelper(Context context) {
this.myContext = context;
}
}
and third one extends DBhelper
public class Translation extends DBHelper {
public Translation(Runnable runnable) {
super((Context) runnable);
}
public String doSomeJob(){
return "Yes I DID!";
}
}
future I will change this classes to do real job but now,
when I run this I get this error:
05-11 13:15:53.003: E/AndroidRuntime(512): Uncaught handler: thread Thread-8 exiting due to uncaught exception
05-11 13:15:53.028: E/AndroidRuntime(512): java.lang.ClassCastException: iKA.PROJ.TestProjActivity$1
05-11 13:15:53.028: E/AndroidRuntime(512): at another.pack.Translation.(Translation.java:10)
05-11 13:15:53.028: E/AndroidRuntime(512): at iKA.PROJ.TestProjActivity$1.run(TestProjActivity.java:20)
05-11 13:15:53.028: E/AndroidRuntime(512): at java.lang.Thread.run(Thread.java:1096)
05-11 13:15:53.053: I/dalvikvm(512): threadid=7: reacting to signal 3
05-11 13:15:53.053: E/dalvikvm(512): Unable to open stack trace file '/data/anr/traces.txt': Permission denied
05-11 13:20:53.135: I/Process(512): Sending signal. PID: 512 SIG: 9
What do I wrong ?
You're trying to cast your Runnable into a Context. This is not possible
I think that you want to do is
Translation th = new Translation(TestProjActivity.this);
and
public Translation(Context context) {
super(context);
}
Translation constructor take Activity(Context). But Translation constructor signature take Runnable. I think this is your problem (wrong class cast from Context/Activity to Runnable).

Categories