IllegalArgumentException In An AsyncTask On Rotate - java

I have successfully sent an email in the background and displayed a progress dialog to the user as said email is sent. However when the user flips the screen while the dialog is up I get an IllegalArgumentException. I have tried using a WeakReference object and it doesn't seem to be fixing the problem. This is my AsyncTask class.
private class SendMailTask extends AsyncTask<Mail, String, EmailStatusResponce> {
private final WeakReference<ProgressDialog> weakReference;
public SendMailTask() {
ProgressDialog progressDialog = new ProgressDialog(SendReportActivity.this);
progressDialog.setMessage("Sending...");
progressDialog.setCancelable(false);
progressDialog.show();
weakReference = new WeakReference<>(progressDialog);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected EmailStatusResponce doInBackground(Mail... mail) {
return mail[0].send();
}
#Override
protected void onPostExecute(EmailStatusResponce result) {
super.onPostExecute(result);
if (result != null && weakReference != null) {
weakReference.get().dismiss(); // This is where the exception is thrown.
if (result.isSuccess()) {
Intent intent = new Intent(SendReportActivity.this, MainActivity.class);
startActivity(intent);
}
else {}
}
}
This is the exception
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{688d3e2 V.E...... R......D 0,0-1026,348} not attached to window manager
Thanks in advance for any and all help.
EDIT: More logcat
--------- beginning of crash
12-11 16:22:40.154 1976-1976/com.blazapps.allenfamilymedicine E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.blazapps.allenfamilymedicine, PID: 1976
java.lang.IllegalArgumentException: View=com.android.internal.policy.PhoneWindow$DecorView{f89e667 V.E...... R......D 0,0-760,232} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:424)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:350)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:116)
at android.app.Dialog.dismissDialog(Dialog.java:362)
at android.app.Dialog.dismiss(Dialog.java:345)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:168)
at com.blazapps.allenfamilymedicine.SendReportActivity$SendMailTask.onPostExecute(SendReportActivity.java:138)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
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)

I still do no know why the exception is being thrown but because I save lots of information in EmailStatusResponse I can just surround the exception with a try catch and if the task was complete I get the result I expected.
try {
weakReference.get().dismiss();
} catch (Exception e) {}
If anyone can figure a better solution I would really appreciate it. I hate just catching exceptions. There is usually a better way.

Related

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.

Jsoup html display in webview not working

I am working on an android app in android studio, the app pulls some data from amazon and displays it in a webview.
For some reason the webview remains blank, I have tested my code in a standard java project using eclipse. The Jsoup code is good and runs clean in eclipse but in android studio it also shows no errors with the exception of no webview.
Here is my Code
public class showdata extends AppCompatActivity {
WebView firstresault;
public String amazonproduct;
public Element productamazon;
public class getres extends AsyncTask<Void,Void,Void> {
#Override
protected Void doInBackground(Void... params) {
try {
Document doc = Jsoup.connect("https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=841351100182").get();
productamazon = doc.select("div#s-item-container").first();
amazonproduct = productamazon.toString();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
WebView wview = (WebView)findViewById(R.id.amazon_product);
wview.loadData( amazonproduct, "text/html", null);
Log.i("amazonproduct", "Null or Not");
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showdata);
new getres();
}
}
I am new to the android api so I am sure that it is something simple. All help is appreciated!
logcat
E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.rober.shoppingappbarcode, PID: 11086
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.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.jsoup.nodes.Element.toString()' on a null object reference
at com.example.rober.shoppingappbarcode.showdata$getres.doInBackground(showdata.java:28)
at com.example.rober.shoppingappbarcode.showdata$getres.doInBackground(showdata.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
you need to execute your AsyncTask using execute() function call
new getres().execute();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showdata);
new getres().execute();
// ^^^^^^^
}
Try using this
productamazon = doc.getElementsByClass("s-item-container").first();
instead of this
productamazon = doc.select("div#s-item-container").first();

java.lang.IllegalArgumentException - dialog.dismiss

I am getting this error in my published application, only clients receive this error. I already tried several times to replicate the same mistake however unsuccessfully.
I also already tried to use the below code at all locations where there is a Dialog but also not solved.
if (dialog.isShowing ()) {
dialog.dismiss ();
}
The error report
java.lang.IllegalArgumentException: View=com.android.internal.policy.impl.PhoneWindow$DecorView{16faa139 V.E..... R.....I. 0,0-0,0} not attached to window manager
at android.view.WindowManagerGlobal.findViewLocked(WindowManagerGlobal.java:412)
at android.view.WindowManagerGlobal.removeView(WindowManagerGlobal.java:338)
at android.view.WindowManagerImpl.removeViewImmediate(WindowManagerImpl.java:122)
at android.app.Dialog.dismissDialog(Dialog.java:522)
at android.app.Dialog.dismiss(Dialog.java:504)
**at br.my.project.de.a(Unknown Source)
at br.my.project.de.onPostExecute(Unknown Source)**
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
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)
I could see that you are trying to dismiss a ProgressDialog on the postExecute of an AsyncTask. This in itself is a good practice but is sometimes buggy, I kind of experienced this also before especially while you're showing the ProgressDialog and suddenly rotate the view.
A solution I've found to fix this is below:
You will need these function to handle the proper dismissal and avoid crashes.
private void dismissProgressDialog(ProgressDialog progressDialog) {
if (progressDialog != null) {
if (progressDialog.isShowing()) {
//get the Context object that was used to create the dialog
Context context = ((ContextWrapper) progressDialog.getContext()).getBaseContext();
// if the Context used here was an activity AND it hasn't been finished or destroyed
// then dismiss it
if (context instanceof Activity) {
// Api >=17
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
if (!((Activity) context).isFinishing() && !((Activity) context).isDestroyed()) {
dismissWithExceptionHandling(progressDialog);
}
} else {
// Api < 17. Unfortunately cannot check for isDestroyed()
if (!((Activity) context).isFinishing()) {
dismissWithExceptionHandling(progressDialog);
}
}
} else
// if the Context used wasn't an Activity, then dismiss it too
dismissWithExceptionHandling(progressDialog);
}
progressDialog = null;
}
}
public void dismissWithExceptionHandling(ProgressDialog dialog) {
try {
dialog.dismiss();
} catch (final IllegalArgumentException e) {
// Do nothing.
} catch (final Exception e) {
// Do nothing.
} finally {
dialog = null;
}
}
On your AsyncTask's onPostExecute implement the function.
#Override
protected void onPostExecute(Boolean b) {
// pass in the progressDialog as a parameter to the method
dismissProgressDialog(progressDialog);
}
fun Activity?.dismissDialog(dialog: Dialog?) {
if (isActivityActive()) {
dialog?.apply {
if (isShowing) dismiss()
}
}
}
fun Activity?.isActivityActive(): Boolean {
return null != this && !isFinishing && !isDestroyed
}
You are calling dismiss on a dialog that is currently not being shown anymore. As in: your Activity/Fragment is possibly already destroyed when you call dismiss.
Write this code in your activity's
onStop()
method.When anybody presses the home button and if dialog is opened than this error will come. Because on click of home button onPause() and onStop() method calls.Hope this helps.
if (dialog!=null && dialog.isShowing ()) {
dialog.dismiss ();
}

Android recieving classcastexception despite being in correct class

I have an activity with a viewpager containing 2 fragments, inside each fragment contains a list, from this list a button can be pressed that creates a new fragment in the viewpager, this works fine until I create a new activity and close it, after the new activity is closed and I return to the previous activity pressing the button to create a new fragment again now gives a classcastexception, almost as if the closed activity is still open, but it is not, I have tried searching this issue and cant find any examples of this being encountered by anyone else which makes me wonder how this could be happening, I will post some code examples below, any help will go a long way thanks.
Click listener in ListAdapter:
holder.rlStatusContainer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add new comment fragment and set page
try {
((HomeFragmentActivity) activity).addCommentFragment(data.get(finalPosition));
} catch (Exception e) {
e.printStackTrace();
}
}
});
Method in activity:
public void addCommentFragment(ArrayList<Object> fragmentExtras) {
list.add(NavigationFragment.newInstance(9, getApplicationContext(), this, fragmentExtras));
adapter.notifyDataSetChanged();
pager.setCurrentItem(list.size());
}
Error received:
12-13 13:37:50.177 17262-17262/test.test.com.test E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: test.test.com.test, PID: 17262
java.lang.ClassCastException: test.test.com.test.activities.NewPostActivity cannot be cast to test.test.com.test.activities.HomeFragmentActivity
at test.test.com.test.adapters.ListHomeAdapter$4.onClick(ListHomeAdapter.java:462)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

Activity getting destroyed when starting another activity for file viewing

I'm performing file viewing operation as follows:
private void openFile(File file, String format) {
try {
if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimeType = "*/*";
if (format.length() > 0) {
mimeType = MimeTypeMap.getSingleton()
.getMimeTypeFromExtension(format);
if (mimeType == null)
mimeType = "*/*";
} else
mimeType = "*/*";
intent.setDataAndType(path, mimeType);
try {
startActivity(intent);
} catch (Exception e) {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_NoCompatibleApp, Toast.LENGTH_SHORT)
.show();
e.printStackTrace();
}
} else {
Toast.makeText(LoginSuccessActivity.this,
constants.Error_DocNotFound, Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
e.printStackTrace();
}
}
This is working fine, as I get app chooser pop-up for the filetypes which has multiple apps related to it(for eg. kingsoft office and polaris office for word file) OR directly file is opened for the filetypes which has only one app related to it(HTMLViewer for html file).
What I don't understand is my main activity is getting destroyed in few moments after calling file viewer activity. I've checked this by placing logs in onPause(), onStop() and onDestroy(). So, after file viewing is done, when I press back key, instead of taking back to app, it navigated to main menu.
I tried with startActivityForResult(intent, 1); instead of startActivity(intent); hoping that it'll preserve my main activity as it'll be waiting for result, but to no avail.
Please note that I've added android:configChanges="orientation|screenSize" in manifest file and
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
in java file.
Am I doing anything wrong?
Any help appreciated.
Sometimes, mind you, "Sometimes", I get follwing messages on log:
file:// Uri exposed through Intent.getData()
java.lang.Throwable: file:// Uri exposed through Intent.getData()
at android.os.StrictMode.onFileUriExposed(StrictMode.java:1597)
at android.net.Uri.checkFileUriExposed(Uri.java:2338)
at android.content.Intent.prepareToLeaveProcess(Intent.java:7194)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1418)
at android.app.Activity.startActivityForResult(Activity.java:3423)
at android.app.Activity.startActivityForResult(Activity.java:3384)
at android.app.Activity.startActivity(Activity.java:3626)
at android.app.Activity.startActivity(Activity.java:3594)
at com.android.internal.app.ResolverActivity.onIntentSelected(ResolverActivity.java:407)
at com.android.internal.app.ResolverActivity.startSelected(ResolverActivity.java:299)
at com.android.internal.app.ResolverActivity.onButtonClick(ResolverActivity.java:289)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3809)
at android.view.View.performClick(View.java:4424)
at android.view.View$PerformClick.run(View.java:18383)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4998)
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:777)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
at dalvik.system.NativeStart.main(Native Method)
Add these lines to your Intent and try to Start Activity,
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(Your_MimeType);
I m using this code in my App
String MimeType = URLConnection.guessContentTypeFromName(myFile.getAbsolutePath());
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setType(MimeType);
Uri uri_path = Uri.fromFile(myFile);
intent.setDataAndType(uri_path, MimeType);
try
{
_context.startActivity(intent);
}
catch(ActivityNotFoundException e)
{
Toast.makeText(_context,"Activity Not Found..", Toast.LENGTH_SHORT).show();
}
Refer this link also for better understanding
Hope it will help you.
Activity can get destroyed any time. If someone has some data to retain one can do as follows:
class MyActivity {
private String mMyString;
public void onSaveInstanceState(Bundle b) {
b.putString("MYDATA", mMyString);
super.onSaveInstanceState(b);
}
public void onCreate(Bundle savedState) {
super.onCreate(savedState)
if(savedState != null) {
mMyString = savedState.getString("MYDATA");
}
}
You can this way create your own subclass private static class State implements Serializable and save it in onSaveInstanceState()

Categories

Resources