Question

I want to show a toast message from within a thread that is running on the UiThread however it appears the Runnable is not referenced correctly in my call. Please see my very basic implementation below:

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(this, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

I believe that this is not the actual runnable that the makeText function requires. How would you get the actual Runnable in this case?

Était-ce utile?

La solution

do not use this keyword,best practice is to create Context variable and initialize it in onCreate method,and use every where in your activity.

Context context;

@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layoutname);
    context=this;
}   

now use it like this:

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(context, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

in your case,this refers to the runnable class not the Context. so you can use context for toast

Autres conseils

use this

this.runOnUiThread(new Runnable() {
     public void run() {
                Toast.makeText(youractivityname.this, "Authenticated.", Toast.LENGTH_SHORT).show();
            }
        }
);

this refers to the runnable class not the context. so you can use the activityname.this

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top