Android: get error near runOnUiThread when I use it next to fragment

I am new to Android development and I want to associate a button with animation. I get an error near runOnUiThread() and getApplication() . When I add this as an operation, this is normal, but when declared in MainFragment , it gives an error. However, when I fix the errors, it creates a method and returns false.

 public class MainFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.activity_main, container, false); ImageButton btnFacebook = (ImageButton)rootView.findViewById(R.id.facebook2); final Animation alpha = AnimationUtils.loadAnimation(getActivity(), R.anim.anim_alpha); btnFacebook.setOnClickListener(new Button.OnClickListener(){ @Override public void onClick(View arg0) { arg0.startAnimation(alpha); Thread thread = new Thread() { @Override public void run() { try { Thread.sleep(1000); }catch(InterruptedException e){ } runOnUiThread(new Runnable() { @Override public void run() { startActivity(new Intent(getApplication(),FacebookActivity.class)); } }); } }; thread.start(); }}); return rootView; }} 

In the XML file, I have only the facebook button. When I click this, it should trigger the animation, and then the onclick event should happen, but I don't know why this error appears:

The runOnUiThread method (new Runnable () {}) is undefined for the type new Thread () {}

And next to the getapplication () method, the getApplication () method is undefined for the type new Runnable () {}

If I create two methods, the error goes away, but then when I click on the button, it will not go into the facebookActivity.java file.

Can someone say / help what I should add in order to solve this problem. Thank you

+6
source share
3 answers

runOnUIThread(...) is an Activity method.

So use this:

 getActivity().runOnUIThread(...); 

But be careful. You are dealing with asynchronous threads, so your Fragment can be separated from Activity , resulting in a getActivity() returning null . You might want to add an if(isAdded()) or if(getActivity() != null) before executing.

Alternatively, use AsyncTask , which processes this execution on the ui thread itself.

+8
source
 runOnUiThread(new Runnable(){}) is method in Activity not in the Fragment. 

so you need to change

 runOnUiThread(new Runnable(){}) 

in

 getActivity().runOnUiThread(new Runnable(){}) 

For your application, it is better to use a Handler instead of Thread to wait 1000 milliseconds.

+2
source

Use getActivity() instead of getApplication() .

which returns the activity associated with the fragment. Activity is context.

+2
source

All Articles