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!
Related
I use loader to do task in back ground in method loadInBackground i added for loop to print log in logcat 50 time , so when i click the button start print log in logcat
but when i click the button i don't have any action and i don't have ant error , what is problem ?
mainActicity
public class MainActivity extends AppCompatActivity implements android.app.LoaderManager.LoaderCallbacks<String> {
TextView textView;
android.app.LoaderManager loaderManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loaderManager=getLoaderManager();
textView=findViewById(R.id.tv_result);
if (loaderManager.getLoader(0) ==null){
loaderManager.initLoader(0,null,this);
}
}
public void StartMysynstack (View view){
loaderManager.initLoader(0,null,this);
}
#Override
public android.content.Loader<String> onCreateLoader(int i, Bundle bundle) {
return new Myloader(this);
}
#Override
public void onLoadFinished(android.content.Loader<String> loader, String s) {
textView.setText(s);
}
#Override
public void onLoaderReset(android.content.Loader<String> loader) {
}
}
my loader
public class Myloader extends AsyncTaskLoader<String> {
int i;
public Myloader(Context context) {
super(context);
}
#Override
public String loadInBackground() {
for( i=0;i<=100;i++){
try {
Thread.sleep(50);
Log.d("waad","loadInBackground"+i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return "Task result";
}
}
you can try calling it manually.
getLoaderManager().initLoader(0, null, this).forceLoad();
so according to your code you can make following changes.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loaderManager=getLoaderManager();
textView=findViewById(R.id.tv_result);
if (loaderManager.getLoader(0) ==null){
loaderManager.initLoader(0,null,this).forceLoad();;
}
}
I have the following fragment.The problem is that every time I launch this the app crashes with the following exception : attempt to invoke virtual method android.content.Context android.support.v4.app.FragmentActivity.getApplicationContext() on a null object reference. From what I understand getActivity is called correctly, however the FragmentActivityTesting does not return any context, I'm not sure why this is the case:
public class FragmentATesting extends Fragment {
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onCreate(Bundle SavedInstanceState) {
super.onCreate(SavedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_a,container,false);
}
#Override
public void onActivityCreated(Bundle SavedInstanceState){
super.onActivityCreated(SavedInstanceState);
}
#Override
public void onStart() {
super.onStart();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onResume() {
super.onResume();
final SessionManager session = new SessionManager(getActivity().getApplicationContext());
TextView username = (TextView) getView().findViewById(R.id.username_info_txt);
HashMap<String,String> userString = session.getUserDetails();
String usernamee = userString.get("username");
username.setText(usernamee);
vote(usernamee);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
private void vote(final String userId) {
class UploadImage extends AsyncTask<String, Void, String> {
RequestHandler rh = new RequestHandler();
#Override
protected String doInBackground(String... params) {
HashMap<String, String> data = new HashMap<>();
data.put("username",userId);
String result = rh.sendPostRequest(SL_URL2, data);
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
JSONObject jsonObject = null;
String likess = "";
try {
jsonObject = new JSONObject(s);
} catch (JSONException e) {
e.printStackTrace();
}
try {
likess = jsonObject.getString("amount");
} catch (JSONException e) {
e.printStackTrace();
}
TextView amount = (TextView) getView().findViewById(R.id.likes_info_txt);
amount.setText(likess + " Likes");
}}
UploadImage ui = new UploadImage();
ui.execute();
}`
It is inside my ViewPager defined as follows:
public class FragmentActivityTesting extends FragmentActivity {
ViewPager viewPager = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fragment_activity_testing);
viewPager = (ViewPager) findViewById(R.id.pic_pager);
setStatusBarColor();
FragmentManager fragmentManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmentManager));
viewPager.setCurrentItem(1);
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("CLOSE_ALL");
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
finish();
}
};
registerReceiver(broadcastReceiver, intentFilter);
}
#TargetApi(21)
public void setStatusBarColor() {
Window window = this.getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
if (Integer.valueOf(android.os.Build.VERSION.SDK) >= 21) {
window.setStatusBarColor(this.getResources().getColor(R.color.green));
}
}}
class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = null;
if (position ==0) {
fragment = new FragmentATesting();
}
else if (position == 1) {
fragment = new FragmentBTesting();
}
else if (position == 2) {
fragment = new FragmentCTesting();
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
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.
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);
}
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.