Combine Activity with Fragment - java

Learning what I can from the internet and youtube, I'm sure I am not handling this in the appropriate way. I have an existing app which includes a slide out navigation drawer using fragments. I am now trying to get an activity to run within that fragment without any luck. It works when ran on it's own, but after trying to combine the two, I am not able to get "draftactivity" to run properly. The fragment operates as it should.
public class tapsfragment extends Fragment {
public static tapsfragment newInstance() {
tapsfragment fragment = new tapsfragment();
return fragment;
}
public tapsfragment(){}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
public class DraftActivity extends Activity {
TextView draftfeed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.draft_activity);
draftfeed = (TextView) findViewById(R.id.draftfeed);
new PostAsync().execute();
}
class PostAsync extends AsyncTask<Void, Void, Void> {
ProgressDialog pd;
XMLHelper helper;
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(DraftActivity.this, "Taps", "Loading posts for ******.com ...", true, false);
}
#Override
protected Void doInBackground(Void... arg0) {
helper = new XMLHelper();
helper.get();
return null;
}
#Override
protected void onPostExecute(Void result) {
StringBuilder builder = new StringBuilder();
for (ItemValue post : helper.posts) {
builder.append("\nPost: " + post.getTitle());
builder.append("\n");
}
draftfeed.setText(builder.toString());
pd.dismiss();
}
}

Activity can't run in a fragment, it's the other way around.

Related

Hide/Show ProgressBar using AsyncTask

I'm trying to do the simple act of hiding/showing ProgressBar according to AsyncTask state ,
I have two classes one extends FragmentActivity and second AsyncTask.
MainActivity.java
public class MainActivity extends FragmentActivity {
public static ProgressBar mProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
}
#Override
protected void onStart() {
super.onStart();
// What will happen to the progress bar here?
}
#Override
protected void onStop() {
super.onStop();
// What will happen to the progress bar here?
}
#Override
protected void onResume() {
super.onResume();
// What will happen to the progress bar here?
}
}
MyAsyncTask.java
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
#Override
protected Void doInBackground() {
// start download some images from cloud
// Here the progress bar should start to appear in MainActivity
// mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
// mProgressBar.setVisibility(View.GONE);
}
}
main_activity.xml
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true" />
Hope you understand me, thank to everyone who can help.
The progress bar should appear in onPreExecute() method (still in UI thread). Then you dismiss it when you get back to UI thread in onPostExecute method.
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
#Override
protected void onPreExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
mProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground() {
// start download some images from cloud
// there is a time cost operation
}
#Override
protected void onPostExecute(Void result) {
Log.d(TAG, "Finished book downloading images the cloud");
// Here the progress bar should start to disappear in MainActivity
// mProgressBar.setVisibility(View.GONE);
}
}
You should use onPreExecute() method to show the dialog.
Here is MainActivity
#Override
protected void onResume() {
super.onResume();
new MyAsyncTask().execute();
}
I think you should read APIs first.
Use preExecute and postExecute methods as they run on UI thread.
public class MyAsyncTask extends AsyncTask<Void,Void, Void> {
ProgressBar pBar;
#Override
protected void onPreExecute(Void result) {
pBar=new ProgressBar(getContext());
pBar.show();
}
#Override
protected void onPostExecute(Void result) {
if(pBar !=null and pBar.isShowing()){
pBar.dismiss();
}
}
}
Use interface in Asyntask class for communicate with Activity class
public class MyAsyncTask extends AsyncTask<Void,Void,Void> {
//use context for activity reference
private Context context_;
public MyAsyncTask(Context context) {
this.context_=context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(mCallBack!=null ){
mCallBack.onSuccess("Success");
}else {
mCallBack.onError("Error");
}
}
MyAsyncCallBack mCallBack=null;
public MyAsyncCallBack getmCallBack() {
return mCallBack;
}
public void setmCallBack(MyAsyncCallBack mCallBack) {
this.mCallBack = mCallBack;
}
public interface MyAsyncCallBack{
public void onSuccess(String successMessage);
public void onError(String successMessage);
}
}
Call AsynckTask Class from activity class.Before calling asyntask start progress. and after completing work in asyntask return activity via interface and hide progress.
startProgress();
MyAsyncTask mTask=new MyAsyncTask(YourActivity.this);
mTask.setmCallBack(new MyAsyncTask.MyAsyncCallBack() {
#Override
public void onSuccess(String successMessage) {
//do success work and hide progress
hideProgress();
}
#Override
public void onError(String successMessage) {
//do error work and hide progress
hideProgress();
}
});
mTask.execute();

How to allow the device rotation while onPostExecute (UI Blocking Task) running

I'm new to android but based on my understanding that onPostExecute has to run on the main UI thread to be able to access Views and so on which blocks the UI until it finishes. But the application looks ugly -as if it's crashing- when I try to rotate the device while onPostExecute is running (I know it should be a light weight task but I keep in mind slow phones so this might actually happen in my HBO)
Now, here's my code and I know I believe I should use interfaces for communication between my Task, Fragment, and Activity but it's just a proof of concept for now.
//MovieTask Class
public class MovieTask extends AsyncTask<Void, Void, String> {
private Activity activity;
public MovieTask(Activity activity) {
onAttach(activity);
}
//should be an interface
public void onAttach(Activity activit) {
this.activity = activit;
}
//should be an interface
public void onDetach() {
this.activity = null;
}
#Override
protected String doInBackground(Void... params) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
Log.e("ASYNC TASK", "DONE");
return "DONE: FROM DO TO POST";
}
#Override
protected void onPostExecute(String s) {
if(this.activity != null)
{
((MainActivity) activity).ShowResult(s);
Log.e("MovieTask", "Result Received");
}else
Log.e("MovieTask", "Activity is null (1)");
}
}
//My Non-UI Fragment to decouple the Task from the Activity
public class NonUIFragment extends Fragment {
private MovieTask myTask;
private Activity activity;
public NonUIFragment() {
// Required empty public constructor
}
public void BeginTask() {
if (activity != null) {
myTask = new MovieTask(activity);
myTask.execute();
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
//check that the passed context is an Activity first then,
if (context instanceof Activity) {
this.activity = (Activity) context;
if(myTask != null) {
myTask.onAttach((Activity) context);
}
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance
setRetainInstance(true);
}
#Override
public void onDetach() {
super.onDetach();
if(myTask != null) {
myTask.onDetach();
}
}
//Main Activity (Task Consumer)
public class MainActivity extends AppCompatActivity {
NonUIFragment nonUIFragment;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
nonUIFragment = new NonUIFragment();
getSupportFragmentManager()
.beginTransaction()
.add(nonUIFragment, "nonUIFragment")
.commit();
}
else
{
nonUIFragment = (NonUIFragment) getSupportFragmentManager().findFragmentByTag("nonUIFragment");
}
Button btn = (Button) findViewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nonUIFragment.BeginTask();
}
});
}
//should be the consumer interface
public void ShowResult(String result)
{
try {
Thread.sleep(5000);
TextView txtVw = (TextView) findViewById(R.id.txtVw);
txtVw.setText(result);
} catch (InterruptedException e) {
Log.e("MovieTask", "mCallbacks is null (2)");
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
TextView txtVw = (TextView) findViewById(R.id.txtVw);
String result = txtVw.getText().toString();
outState.putString("result", result);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
String result = savedInstanceState.getString("result");
TextView txtVw = (TextView) findViewById(R.id.txtVw);
txtVw.setText(result);
}
}
UPDATE 1
In the chat Jigs suggested trying 'runOnUiThread', however onPostExecute already runs on the UI Thread so unfortunately it's kind of irrelevant. I guess what I'm trying to do is not block the UI while the behaviour of onPostExecute is a UI-Blocking in nature which makes it kind of impossible. I'll leave the question around in case anybody has different thoughts!

NetworkOnMainThread Exception android studio [duplicate]

This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 7 years ago.
I am getting NetworkOnMainThreadException while running my code. I have a Fragment where i am showing some ID from the webservices that gets called when i click on a button. Following is my code. I have used Asynctask as mentioned for this purpose but still i keep getting this error.
public class AboutMeFragView extends Fragment implements ObsrvIntModel {
private Button getConfButton;
private UsrDataCtrl m_UsrDataCtrl;
private UsrDataModel m_UsrDataModel;
private boolean m_bResUpdate;
private String retc;
public static AboutMeFragView newInstance() {
AboutMeFragView aboutMeFragment = new AboutMeFragView();
return aboutMeFragment;
}
public AboutMeFragView() {}
//inflate the data on this view from the relevant xml file fragment_about_me.xml
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment_about_me, container, false);
getConfButton = (Button) rootView.findViewById(R.id.get_config_button);
getConfButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(getActivity(), "Implement methods to get the configuration", Toast.LENGTH_LONG).show();
//call your model to get the data from the server and show it on the UI
enableStrictMode();
new GetCredsTask().execute();
}
});
return rootView;
}
//whenever fragment is associated with our main activity
//following method would get called
//also we make sure here that whatever navigation activity is selected
//our action bar shows up the same activity name
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((CpActivity)activity).onSectionAttached(1);
}
#Override
public void update(boolean result) {
m_bResUpdate = result;
}
public void enableStrictMode()
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
private class GetCredsTask extends AsyncTask<Void, Void, String> {
public GetCredsTask() {
super();
}
#Override
protected String doInBackground(Void... params) {
m_UsrDataModel = new UsrDataModel(AboutMeFragView.this);
m_UsrDataCtrl = new UsrDataCtrl(m_UsrDataModel);
m_UsrDataCtrl.execConfig();
retc = m_UsrDataModel.getM_authid();
if(m_bResUpdate != true) {
retc = "404";
}
Log.d("doInBackground", retc);
return retc;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
Log.d("onPostExecute", retc);
if (m_bResUpdate == true)
Toast.makeText(getActivity(), s, Toast.LENGTH_LONG).show();
else
Toast.makeText(getActivity(), retc, Toast.LENGTH_LONG).show();
super.onPostExecute(s);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
protected void execute() {
doInBackground();
}
}
}
Thanks
You are overriding execute(), which is causing the task to be posted on the main thread instead of executed in the background. The normal implementation posts the execution of the task to a background thread, i.e.
Edit:
public final AsyncTask<Params, Progress, Result> More ...execute(Params... params) {
return executeOnExecutor(sDefaultExecutor, params);
}

Asynctask in another class?

I have a problem with the call of asyncTask....
i have a class named arrivi
public class arrivi extends Fragment {
ListView list;
int thread = 0;
public String[] lista = new String[200];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.arrivi, container, false);
new MyTask().execute("");
return ios;
}
//INIZIO THREAD
public class MyTask extends AsyncTask<String, Void, String> {
with new MyTask this work fine...
but i want call MyTask into MainActivity.java
public class MainActivity extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
.....
.....
i have tried to
arrivi a = new arrivi();
a.MyTask.execute("");
i don't know...
how to make a call?? can you make me an example of code?
Thank u guys!
There are two ways to do this, but what it looks like you are trying to do here is actually to make MyTask static:
public static class MyTask extends AsyncTask<String, Void, String> {
and that way, in your activity, you can just call:
new arrivi.MyTask().execute();
(Optional) further explanation:
the other alternative is to use the syntax -
new arrivi().new MyTask().execute(); which i think is what you could also be trying to accomplish.
given that you are calling your MyTask in two separate places, it seems you might as well either make your MyTask static OR place MyTask in its own class outside of both of these two classes (in order to syntactically make this correct. This, however, depends on if you want MyTask to interact with your fragment arrivi. For example, if, in your onPostExecute() of MyTask, you want to access something that arrivi has (such as a view), you probably want to place MyTask inside of arrivi still, and not use the static declaration
thank u for replies... in mainactivity i have this:
public class MainActivity extends FragmentActivity {
ViewPager Tab;
TabPagerAdapter TabAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabAdapter = new TabPagerAdapter(getSupportFragmentManager());
Tab = (ViewPager)findViewById(R.id.pager);
Tab.setOnPageChangeListener(
new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar = getActionBar();
actionBar.setSelectedNavigationItem(position); }
});
Tab.setAdapter(TabAdapter);
actionBar = getActionBar();
//Enable Tabs on Action Bar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener(){
#Override
public void onTabReselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
Tab.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.app.ActionBar.Tab tab,
FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
//Add New Tab
actionBar.addTab(actionBar.newTab().setText("Info").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Arrivi").setTabListener(tabListener));
actionBar.addTab(actionBar.newTab().setText("Partenze").setTabListener(tabListener));
if (isOnline()) {
//System.out.println("CONNESSIONE OK");
new arrivi().new MyTask().execute();
}else{
try {
AlertDialog alertDialog = new AlertDialog.Builder(this).create();
alertDialog.setTitle("Info");
alertDialog.setMessage("Connessione Internet non disponibile.");
alertDialog.setButton("Esci", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
alertDialog.show();
}
catch(Exception e) { }
}
}
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
}
and this is arrivi class:
public class arrivi extends Fragment {
ListView list;
int thread = 0;
public String[] lista = new String[200];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View ios = inflater.inflate(R.layout.arrivi, container, false);
new MyTask().execute("");
return ios;
}
//INIZIO THREAD
public class MyTask extends AsyncTask<String, Void, String> {
ProgressDialog prog;
String info;
#Override
protected void onPreExecute() {
prog = new ProgressDialog(getActivity());
prog.setMessage("Connessione in corso...");
prog.show();
prog.setCanceledOnTouchOutside(false);
prog.setCancelable(false);
}
#Override
protected String doInBackground(String... params) {
try {
org.jsoup.nodes.Document doc = Jsoup.connect("http://site.eu").timeout(7*1000).get();
org.jsoup.nodes.Element tabella = doc.getElementsByClass("tabella-voli").first();
Iterator<org.jsoup.nodes.Element> iterator = tabella.select("td").iterator();
while(iterator.hasNext()){
thread++;
lista[thread] = iterator.next().text();
System.out.println("Posizione["+thread+"]"+lista[thread]);
}
}catch (IOException e) {
e.printStackTrace();
}
return info;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
prog.dismiss();
CheckRow();
}
}// FINE THREAD
but when i lunch my app, crashes and here there is a logcat
http://paste.ubuntu.com/7253904/
i think line 43 is NULL... prog = new ProgressDialog(getActivity());
..thank you so much guys!!

How to use a ProgressDialog properly with an AsyncTask without causing window leaks?

I have an AsyncTask which shows a ProgressDialog. The AsyncTask is started when the activity is started:
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_layout);
new MyTask().execute();
}
// ... other code
private class MyTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog dialog = new ProgressDialog(MyActivity.this);
#Override
protected void onPreExecute() {
dialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// get data from a server
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
// call to a method in MyActivity which updates the UI.
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
}
This code works perfectly, untill I rotate my screen. Which makes sense, because the context that was used to create the dialog doesn't exist anymore (because the activity is re-created when rotating), and a window leak is caused.
The only solution I could think of isn't a really nice one: create a static instance of the task and dialog, and simply dismiss the dialog when the activity is destroyed, and recreate the dialog in the oncreate method if the task is still running.
So how would I solve something like this without losing functionality (so the dialog must always be shown when the task is running, and rotating the device should be allowed)?
As Raghunandan suggested in his comment, I looked into Fragments and solved my problem.
I created a Fragment which starts my AsyncTask, as explained in the blogpost that Raghunandan provided.
And to make sure that my Dialog didn't get leaked, I created a DialogFragment, as described here (Basic Dialog).
Here's my working code:
My Activity:
public class MyActivity extends Activity implements MyTaskFragment.TaskCallbacks {
private MyTaskFragment task;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_layout);
FragmentManager fm = getFragmentManager();
task = (MyTaskFragment) fm.findFragmentByTag("myTask");
if (task == null) {
task = new MyTaskFragment();
fm.beginTransaction().add(task, "myTask").commit();
}
}
#Override
public void onPreExecute() {
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("myDialog");
if (prev != null) {
ft.remove(prev);
}
ft.addToBackStack(null);
StringProgressDialogFragment dialog = StringProgressDialogFragment.newInstance("My message");
dialog.show(ft, "myDialog");
}
#Override
public void onPostExecute() {
StringProgressDialogFragment dialog = (StringProgressDialogFragment) getFragmentManager().findFragmentByTag("myDialog");
if (dialog!=null) {
dialog.dismiss();
}
// update UI
}
// ... other code
}
My Task fragment:
public class MyTaskFragment extends Fragment {
private TaskCallbacks mCallbacks;
private Task mTask;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (TaskCallbacks) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Retain this fragment across configuration changes.
setRetainInstance(true);
// Create and execute the background task.
mTask = new Task();
mTask.execute();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private class Task extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
mCallbacks.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// do stuff
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
mCallbacks.onPostExecute();
}
}
public static interface TaskCallbacks {
void onPreExecute();
void onPostExecute();
}
}
My Dialog fragment:
public class StringProgressDialogFragment extends DialogFragment {
private String message;
public static StringProgressDialogFragment newInstance(String message) {
StringProgressDialogFragment dialog = new StringProgressDialogFragment();
Bundle args = new Bundle();
args.putString("message", message);
dialog.setArguments(args);
return dialog;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
ProgressDialog dialog = new ProgressDialog(getActivity());
message = getArguments().getString("message");
dialog.setMessage(message);
return dialog;
}
}
New Loaders API can help you (available via support package) - man. They will solve problem with rotation, but not a mem. leak. To solve mem. leaks write your own "AsyncTask" (with a "clearContext" routine) and clear it's context in activity's onDestroy (or onPause, depends on your architecture). It may looks like a bicycle, but the task takes max 1 day, and you will have a full control on all the resources you background worker use.
By the way: consider using dialogs through fragments, because it solves dialog kill on screen rotation.
try with sample. it will work. basically just restrict the oncreate call by handling the config change. this solution may help you.
public class MainActivity extends Activity {
LoadProgrssdata task = new LoadProgrssdata();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "oncreate called", Toast.LENGTH_SHORT).show();
task.execute();
}
public class LoadProgrssdata extends AsyncTask<Void, Void, Void> {
ProgressDialog progressDialog;
//declare other objects as per your need
#Override
protected void onPreExecute()
{
progressDialog= ProgressDialog.show(MainActivity.this, "Progress Dialog Title Text","Process Description Text", true);
//do initialization of required objects objects here
};
#Override
protected Void doInBackground(Void... params)
{
//do loading operation here
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
progressDialog.dismiss();
};
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.e("orientation ", "landscape");
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Log.e("orientation ", "portrait");
}
}
}
and in android manifest file:
<activity
android:name="com.example.MainActivity"
android:label="#string/app_name"
android:configChanges="orientation|keyboardHidden|screenSize" />
I managed to fix this problem by trying to catch any crash that, may occurs, in doInBackground.

Categories

Resources