android.view.WindowLeaked: Activity - java

im trying to make a splash screen, the codes showing no errors, build succesfully, but when it started,it shows this message at the apps
and when i check the log on android monitor, it show these messages
08-07 05:41:23.709 16344-16344/com.android.andika.soundsmart E/WindowManager: android.view.WindowLeaked: Activity com.android.andika.soundsmart.SplashS has leaked window DecorView#e044f4c[] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:418)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:331)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at android.app.AlertDialog$Builder.show(AlertDialog.java:1112)
at android.app.Activity.performStart(Activity.java:6723)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2662)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2766)
at android.app.ActivityThread.-wrap12(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1507)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6236)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:891)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:781)
this is the code from my splashscreen class
public class SplashS extends AppCompatActivity {
ProgressBar progressBar;
int status = 0;
int proses = 0;
Handler handle = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_s);
getSupportActionBar().setTitle("SPLASHSREEN");
ActionBar ab = getSupportActionBar();
ab.hide();
progressBar = (ProgressBar) findViewById(R.id.tunggu);
new Thread(new Runnable() {
#Override
public void run() {
while(status<100){
status = loading();
handle.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(status);
}
});
}
handle.post(new Runnable() {
#Override
public void run() {
Intent pindah = new Intent(SplashS.this,MenuS.class);
startActivity(pindah);
finish();
}
});
}
private int loading() {
try{
Thread.sleep(45);
}
catch(InterruptedException ie){
ie.printStackTrace();
}
return ++proses;
}
}).start();
}
}
i debug the app via an android phone with android N 7.1 OS.
i'll appreciate any answer, advice, or response. thanks :)

i think that error related to showing dialog where the activity is dismissed , but your code does not showing any dialogs so check if you are using 3rd party libraries which can do that

Related

window view leaked

public class ProgressCircleActivity extends AppCompatActivity {
private ProgressDialog progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_circle_activity);
progressBar = new ProgressDialog(ProgressCircleActivity.this);
progressBar.setMessage("Please wait ...");
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3*1000);
Intent i=new Intent(ProgressCircleActivity.this,PhoneNumberLogin.class);
startActivity(i);
//Remove activity
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
progressBar.dismiss();
}
}).start();
}
}
Here is my logcat
10-05 16:12:22.577 27797-27797/? E/SELinux: [DEBUG] get_category: variable seinfo: default sensitivity: NULL, cateogry: NULL
10-05 16:12:32.397 27797-27797/com.example.dis015.meetdax2danish E/WindowManager: android.view.WindowLeaked: Activity com.example.dis015.meetdax2danish.ProgressCircleActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{25b6bc4a V.E..... R......D 0,0-501,174} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:520)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:287)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
at android.app.Dialog.show(Dialog.java:325)
at com.example.dis015.meetdax2danish.ProgressCircleActivity.onCreate(ProgressCircleActivity.java:25)
at android.app.Activity.performCreate(Activity.java:6575)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1134)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3143)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3300)
at android.app.ActivityThread.access$1000(ActivityThread.java:211)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1705)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6946)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1404)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1199)
This is my splashScreenActivity when i open the app is getting crash.But in some mobiles the app is not crashing.I dont know what is the issue please help me to sort out
You did not dismiss the progressbar so it is showing that leaked window message.
Before finishing the activity please dismiss the progressbar dialog.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.progress_circle_activity);
progressBar = new ProgressDialog(ProgressCircleActivity.this);
progressBar.setMessage("Please wait ...");
progressBar.setCancelable(true);
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
progressBar.setMax(100);
progressBar.show();
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(3*1000);
Intent i=new Intent(ProgressCircleActivity.this,PhoneNumberLogin.class);
startActivity(i);//dismiss the progressdialog
progressBar.dismiss();
//Remove activity
finish();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}

App crashes while can't perform AsyncTask

I have a problem with AsyncTask in my app. AsyncTask is located in SplashScreenAcivity.java. It downloads data using json for MainActivity.java while showing splash screen. When data is loaded, app shows MainActivity screen. However, when i turn off internet connection app crashes. Instead of it i would like to move to MainActivity.java and show toast that internet connection must be turned on. SplashScreen.java loads data for listView in MainActivity.
SplashActivityScreen.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
new DownloadData().execute();
}
private class DownloadData extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... voids) {
SyncHttpClient clientOne = new SyncHttpClient();
clientOne.get("https://api.themoviedb.org/3/tv/top_rated?api_key=d253f520df9cd868af7db8daaa0db8fb&language=en-US", new JsonHttpResponseHandler() {
#Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
try {
tvseries0 = response.getJSONArray("results").getJSONObject(0).getString("name");
tvseries1 = response.getJSONArray("results").getJSONObject(1).getString("name");
tvseries2 = response.getJSONArray("results").getJSONObject(2).getString("name");
tvseries3 = response.getJSONArray("results").getJSONObject(3).getString("name");
tvseries4 = response.getJSONArray("results").getJSONObject(4).getString("name");
tvseries5 = response.getJSONArray("results").getJSONObject(5).getString("name");
tvseries6 = response.getJSONArray("results").getJSONObject(6).getString("name");
tvseries7 = response.getJSONArray("results").getJSONObject(7).getString("name");
tvseries8 = response.getJSONArray("results").getJSONObject(8).getString("name");
tvseries9 = response.getJSONArray("results").getJSONObject(9).getString("name");
tvseries10 = response.getJSONArray("results").getJSONObject(10).getString("name");
tvseries11 = response.getJSONArray("results").getJSONObject(11).getString("name");
tvseries12 = response.getJSONArray("results").getJSONObject(12).getString("name");
tvseries13 = response.getJSONArray("results").getJSONObject(13).getString("name");
tvseries14 = response.getJSONArray("results").getJSONObject(14).getString("name");
tvseries15 = response.getJSONArray("results").getJSONObject(15).getString("name");
tvseries16 = response.getJSONArray("results").getJSONObject(16).getString("name");
tvseries17 = response.getJSONArray("results").getJSONObject(17).getString("name");
tvseries18 = response.getJSONArray("results").getJSONObject(18).getString("name");
tvseries19 = response.getJSONArray("results").getJSONObject(19).getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onFailure(int statusCode, Header[] headers,Throwable e , JSONObject response) {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.putExtra("tvseries0", tvseries0);
i.putExtra("tvseries1", tvseries1);
i.putExtra("tvseries2", tvseries2);
i.putExtra("tvseries3", tvseries3);
i.putExtra("tvseries4", tvseries4);
i.putExtra("tvseries5", tvseries5);
i.putExtra("tvseries6", tvseries6);
i.putExtra("tvseries7", tvseries7);
i.putExtra("tvseries8", tvseries8);
i.putExtra("tvseries9", tvseries9);
i.putExtra("tvseries10", tvseries10);
i.putExtra("tvseries11", tvseries11);
i.putExtra("tvseries12", tvseries12);
i.putExtra("tvseries13", tvseries13);
i.putExtra("tvseries14", tvseries14);
i.putExtra("tvseries15", tvseries15);
i.putExtra("tvseries16", tvseries16);
i.putExtra("tvseries17", tvseries17);
i.putExtra("tvseries18", tvseries18);
i.putExtra("tvseries19", tvseries19);
startActivity(i);
finish();
}
}
}
Crash 1
04-30 13:15:35.165 12349-12365/przemo.me.recommend.recommendme E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: przemo.me.recommend.recommendme, PID: 12349
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:318)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.lang.RuntimeException: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at com.loopj.android.http.AsyncHttpResponseHandler.onUserException(AsyncHttpResponseHandler.java:304)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:395)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401) 
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319) 
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109) 
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95) 
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078) 
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037) 
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64) 
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56) 
at android.os.AsyncTask$2.call(AsyncTask.java:304) 
at java.util.concurrent.FutureTask.run(FutureTask.java:237) 
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
at java.lang.Thread.run(Thread.java:761) 
Crash 2
04-30 13:15:35.162 12349-12365/przemo.me.recommend.recommendme E/AsyncHttpRH: User-space exception detected!
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:346)
at android.widget.Toast.<init>(Toast.java:101)
at android.widget.Toast.makeText(Toast.java:260)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData$1.onFailure(SplashScreenActivity.java:103)
at com.loopj.android.http.JsonHttpResponseHandler.onFailure(JsonHttpResponseHandler.java:233)
at com.loopj.android.http.AsyncHttpResponseHandler.handleMessage(AsyncHttpResponseHandler.java:359)
at com.loopj.android.http.AsyncHttpResponseHandler.sendMessage(AsyncHttpResponseHandler.java:401)
at com.loopj.android.http.AsyncHttpResponseHandler.sendFailureMessage(AsyncHttpResponseHandler.java:319)
at com.loopj.android.http.AsyncHttpRequest.run(AsyncHttpRequest.java:109)
at com.loopj.android.http.SyncHttpClient.sendRequest(SyncHttpClient.java:95)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1078)
at com.loopj.android.http.AsyncHttpClient.get(AsyncHttpClient.java:1037)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:64)
at przemo.me.recommend.recommendme.SplashScreenActivity$DownloadData.doInBackground(SplashScreenActivity.java:56)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
You can not do UI operations from non UI thread. Like in your code you are showing Toast in Async task thread.
You should replace
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
with this
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
use -
SplashScreenActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(SplashScreenActivity.this, "Turn on the internet and swipe to refresh.", Toast.LENGTH_SHORT).show();
}
});
Here is a server connection AsyncTask task that I created years ago in Android Java. The background task works successfully. I used it to update in the background the data repository in the App I developed at that time.
public class DataExchangeStore extends Application {
public void startServerConnection(Context contextGlobal, Activity activityGlobal) {
this.contextGlobal = contextGlobal;
this.activityGlobal = activityGlobal;
connectTask = new ConnectTask();
connectTask.execute("");
}
private ConnectTask connectTask;
public class ConnectTask extends AsyncTask<String, String, TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
android.os.Process.setThreadPriority( android.os.Process.THREAD_PRIORITY_BACKGROUND);
// we create a TCPClient object
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
#Override
// here the messageReceived method is implemented
public void messageReceived(ChatMessage message) {
// this method calls the onProgressUpdate
publishProgress(message.getMessage());
}
}, contextGlobal, activityGlobal);
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
System.err.println(values[0]);
// do your stuff here
}
}
Import is to permanently lock the screen orientation of the activity, specifying the screenOrientation attribute in the Android-Manifest file with portrait or landscape values:
<activity android:screenOrientation="portrait" />
Although previous answers are not wrong, using runOnUiThread() to jump out of the background thread in the AsyncTask is not a good practice. You have the onPostExecute() method for that.
What you should be doing is passing a result object to onPostExecute(). This object would encapsulate the result state (ie: error or success) and the actual data received. Then in onPostExecute() you check the result state and display a Toast if the state is error.
And do yourself a favor and replace your 20 TvSerie objects by a List<TvSerie> and do a loop in you AsyncTask to populate the list.
Please refer to the AsyncTask documentation for details on how to properly use it.

Android WebView activity crashes :java.lang.IllegalStateException: Calling View methods on another thread than the UI thread

I have a custom android plugin for unity which opens a Webview activity. When I try to open the activity it crashes. When I try to initialise the WebView, below log statements appear from log cat.
Caused by: java.lang.IllegalStateException: Calling View methods on another thread than the UI thread.
at com.android.webview.chromium.WebViewChromium.createThreadException(WebViewChromium.java:252)
at com.android.webview.chromium.WebViewChromium.checkThread(WebViewChromium.java:267)
at com.android.webview.chromium.WebViewChromium.init(WebViewChromium.java:163)
at android.webkit.WebView.<init>(WebView.java:661)
at android.webkit.WebView.<init>(WebView.java:596)
at android.webkit.WebView.<init>(WebView.java:579)
at android.webkit.WebView.<init>(WebView.java:566)
at android.webkit.WebView.<init>(WebView.java:556)
at com.vadrnet.unitysdk.MyWebViewClass.<init>(MyWebViewClass.java:31)
at com.vadrnet.unitysdk.WebViewActivity$1.run(WebViewActivity.java:207)
at android.app.Activity.runOnUiThread(Activity.java:5850)
at com.vadrnet.unitysdk.WebViewActivity.onCreate(WebViewActivity.java:205)
at android.app.Activity.performCreate(Activity.java:6582)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
at android.app.ActivityThread.-wrap11(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:207)
at android.app.ActivityThread.main(ActivityThread.java:5776)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
My code for starting the activity via Unity Script is
AndroidJavaClass unity = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject currentActivity = unity.GetStatic<AndroidJavaObject>("currentActivity");
currentActivity.Call("runOnUiThread", new AndroidJavaRunnable(() =>
{
AndroidJavaClass jc = new AndroidJavaClass("com.vadrnet.unitysdk.ManagerClass");
AndroidJavaObject className = jc.CallStatic<AndroidJavaObject>("instance");
className.Call("click", currentActivity, url);
}));
and the Click function in the Plugin is
public void click(Activity root, String url){
Intent intent = new Intent(root, WebViewActivity.class);
intent.putExtra("url", url);
root.startActivity(intent);
}
I couldn't get why the error occurs despite being opening the activity in the UI thread itself. Any help would be great.
you can use this bit of code may be it will be of help
please check this before posting
QA link
runOnUiThread(new Runnable() {
#Override
public void run() {
// Code for WebView goes here
}
});
// This code is BAD and will block the UI thread
webView.loadUrl("javascript:fn()");
while(result == null) {
Thread.sleep(100);
}
The best solution by the web is
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Your code
}
});
When you do that look here so see how to use runOnUiThread currently
Example on how to use it in Unity (documentation link):
void Start()
{
AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
activity.Call("runOnUiThread", new AndroidJavaRunnable(runOnUiThread));
}
void runOnUiThread()
{
Debug.Log("I'm running on the Java UI thread!");
}
Another Example on how to use it in Unity: (Link to source)
UnityPlayer.currentActivity.runOnUiThread(new Runnable() {
public void run() {
// Run in Thread...
}
});
But you can also use
UserContrl1_LOadDataMethod()
{
string name = "";
if(myObject.InvokeRequired)
{
myObject.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
}
if(name == "MyName")
{
// do whatever
}
}
For more info you can use This Link

Android App crashes on Lollipop

hi I am using google license checker on my app it works on API 19 and below but crashes on lollipop. I saw the code that has to be add to my license check code but I don't know where to put this code or what should I edit. here is my code
log:
java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.android.vending.licensing.ILicensingService }
at android.app.ContextImpl.validateServiceIntent(ContextImpl.java:1674)
at android.app.ContextImpl.bindServiceCommon(ContextImpl.java:1773)
at android.app.ContextImpl.bindService(ContextImpl.java:1751)
at android.content.ContextWrapper.bindService(ContextWrapper.java:538)
at com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.doCheck(Splash.java:103)
at appinventor.ai_drsalmanshah165.Clinical_Examination.Splash.onCreate(Splash.java:51)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
... 10 more
Java code:
public class Splash extends Activity {
MyLicenseCheckerCallback mLicenseCheckerCallback;
LicenseChecker mChecker;
byte[] SALT = new byte[] {
my salt no. };
//Handler mHandler;
String BASE64_PUBLIC_KEY="MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAoxvDF3HGQtrRch14wCPN6nAxasak8X4shJM6bCumNS+6xRXTnRZOSyAvHNa1145KlE/i1sy/";
Context mContext;
IBinder serviceBinder;
String deviceId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.splash);
mLicenseCheckerCallback = new MyLicenseCheckerCallback();
deviceId = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
// Construct the LicenseChecker with a policy.
mChecker = new LicenseChecker(
this, (Policy) new ServerManagedPolicy(Splash.this, new AESObfuscator(SALT, getPackageName(), deviceId)),
BASE64_PUBLIC_KEY);
doCheck();
}
private class MyLicenseCheckerCallback implements LicenseCheckerCallback {
#Override
public void allow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verified", Toast.LENGTH_SHORT).show();
Intent intent=new Intent(Splash.this,Home.class);
startActivity(intent);
finish();
// Should allow user access.
// so do nothing
}
#Override
public void dontAllow(int reason) {
// TODO Auto-generated method stub
if (isFinishing()) {
// Don't update UI if Activity is finishing.
return;
}
// Toast.makeText(Splash.this, "License Verification Failed", Toast.LENGTH_SHORT).show();
createDialog();
}
#Override
public void applicationError(int errorCode) {
// TODO Auto-generated method stub
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mChecker.onDestroy();
}
private void doCheck() {
// mCheckLicenseButton.setEnabled(false);
setProgressBarIndeterminateVisibility(true);
/// mStatusText.setText(R.string.checking_license);
mChecker.checkAccess(mLicenseCheckerCallback);
}
public void createDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("PIRACY WARNING");
builder.setMessage("This application is not licensed. Please purchase it from Android Market. If you received this message in error, please contact Support.");
builder.setPositiveButton("Buy Now", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(
"http://market.android.com/details?id=" + getPackageName()));
startActivity(marketIntent);
}
});
builder.setNegativeButton("Quit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
}
and here is the other code which I got that this can solve my problem. but don't know where to put it.
Intent serviceIntent = new Intent(
new String(Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")));
serviceIntent.setPackage("com.android.vending");
boolean bindResult = mContext
.bindService(
serviceIntent,
this, // ServiceConnection.
Context.BIND_AUTO_CREATE);
Waiting for an official solution, the current solution consists in patching Google's LicenseChecker class
com.google.android.vending.licensing.LicenseChecker.checkAccess(LicenseChecker.java:150)
like this:
new String(
- Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U="))),
+ Base64.decode("Y29tLmFuZHJvaWQudmVuZGluZy5saWNlbnNpbmcuSUxpY2Vuc2luZ1NlcnZpY2U=")))
+ .setPackage("com.android.vending"), // this fix the 'IllegalArgumentException: Service Intent must be explicit'
this, // ServiceConnection.
Adding package name with statement setPackage("com.android.vending") makes the Intent explicit, i.e., 'safe' (as requested by Android Lollipop )
Note:
Please pay attention as after modifying LicenseChecker class you must change the min sdk version from 3 to 4 (thanks russellhoff)
Source:
https://code.google.com/p/android/issues/detail?id=78505#c19

Android spinner throws a Null pointer exception

So I have a service that contains a Timer. The service is meant to run even when the app in the background and is supposed to pull the user to the app when the timer executes the method(from another activity). The service is triggered on and off by a toggle button. Currently my R.id reference to my spinner keeps throwing a NullPointerException that i don't know how to fix. Can someone please help me out?
The Method the Timer is running:
public String TemperatureCatch()
{
/*this line throws the error */ Spinner reeferchoice = (Spinner)findViewById(R.id.optionselecti);
String reeferChoicei = reeferchoice.getSelectedItem().toString();
if (reeferChoicei.equals("Yes")) {
final ToneGenerator tg = new ToneGenerator(AudioManager.STREAM_NOTIFICATION, 500);
tg.startTone(ToneGenerator.TONE_CDMA_ABBR_ALERT);
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Temperature");
alert.setMessage("Input Temperature in F° (-20 to 65) ");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_PHONE);
alert.setView(input);
alert.setPositiveButton("Check-In", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
temperaturei = input.getText().toString();
Toast.makeText(getBaseContext(), "Updated", Toast.LENGTH_SHORT).show();
Updater(temperaturei);
}
});
alert.show();
} else if (reeferChoicei.equals("No")) {
temperaturei = "DRY";
Updater(temperaturei);
}
return temperaturei;
}
My service code:
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import java.util.Timer;
import java.util.TimerTask;
public class MyService extends Service {
Locator locator;
Timer myTimer;
#Override
public void onCreate() {
locator = new Locator();
myTimer = new Timer();
}
private class MyTimerTask extends TimerTask
{
#Override
public void run() {
Handler handler = new Handler(Looper.getMainLooper());
handler.postDelayed(new Runnable() {
#Override
public void run() {
locator.TemperatureCatch();
}
}, 1000);
}
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
MyTimerTask myTimerTask = new MyTimerTask();
myTimer.scheduleAtFixedRate(myTimerTask, 0, 15000);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
myTimer.cancel();
}
}
the button:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if (isChecked)
{
startService(new Intent(this, MyService.class));
Toast.makeText(this,"Check-In will be done every 15 seconds",Toast.LENGTH_SHORT).show();
}
else
{
stopService(new Intent(this, MyService.class));
Toast.makeText(this,"Manual Check-In enabled",Toast.LENGTH_SHORT).show();
}
}
the stack trace:
Process: com.example.adrian.trucktracker, PID: 9617
java.lang.NullPointerException
at android.app.Activity.findViewById(Activity.java:1952)
at com.example.adrian.trucktracker.Locator.TemperatureCatch(Locator.java:192)
at com.example.adrian.trucktracker.MyService$MyTimerTask$1.run(MyService.java:32)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5872)
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:852)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:668)
at dalvik.system.NativeStart.main(Native Method)
You should not create a instance of Activity class.
locator = new Locator(); // do not do this
This results in NullPointerException when you initialize views.
Can i Create the object of a activity in other class?
Also what you are doing seems to be a design issue.
As previous comments already pointed out, service wont have any UI, so you cannot make findViewById method call.
If you want your service to change the UI, bind to this service from your activity and using callbacks/delegates, you can notify the activity to change the UI from the service.
Activity objects are not supposed to be initialized by calling its constructor. By doing so, your overriden method onCreate() never get called, so the views are not initialized and findViewById will fail.
You should instead start the activity in the service instead of calling its contructor, something like this:
Intent t = new Intent (this, Locator.class);
t.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(t);
You can have a static getter in Locator class to get the instance of the Activity, so that you can use it in the Service.

Categories

Resources