CalledFromWrongThreadException
I think you can't do view modifications from another thread than the UI thread, so either create handlers in the oncreate and post your thread to it, or use AsyncTask, or runOnUIThread method to send portions of code directly to the UI thread.
how can i Fix this CalledFromWrongThreadException?
textView.setText(data);
causes this problem because you are trying to set the text of UI element in a non ui thread. You should change the code and do it in ui thread by calling RunOnUiThread
:
runOnUiThread(new Runnable() {
@Override
public void run() {
textView.setText(data);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
});
This will allways happen if you try to manipulate any UI element (not only a textView) inside a non ui thread (like your Runnable). As an alternative to your Runnable you can also try AsyncTask
to do your actions and manipulate the UI element in onPostExecute()
.
new AsyncTask<Void,Void,Void>(){
String data="";
@Override
protected Void doInBackground(Void... params) {
URL dataPath = new URL("http://abdallahmurad.hostkda.com/myfirst_echo_test.php");
HttpURLConnection myFirstConnection = (HttpURLConnection) dataPath.openConnection();
InputStreamReader inputStreamReader = new InputStreamReader(myFirstConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
data = bufferedReader.readLine();
return null;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
textView.setText(data);
Toast.makeText(MainActivity.this, data, Toast.LENGTH_SHORT).show();
}
}.execute();
keep in mind that also the toast has to be called in OnPostExecute
.
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views
Look like you are on the wrong thread. Try using a Handler to update the GUI on the right thread. See Handling Expensive Operations in the UI Thread example from android.com. Basically you would wrap byeSetup
in a Runnable
and invoke it with a Handler
instance.
Handler refresh = new Handler(Looper.getMainLooper());
refresh.post(new Runnable() {
public void run()
{
byeSetup();
}
});
Kotlin coroutines CalledFromWrongThreadException
I would suggest to address it in the following way:
First, explicitly offload your "heavy job" into background threads using withContext
function like this:
// explicitly request it to be executed in bg thread
suspend private fun getImages(): MutableList<Image> = withContext(CommonPool) {
val uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI
...
}
Then, always run the coroutines that touch the views or other UI objects in UI thread:
launch(UI) {
val images = getImages(galleryPath)
imageListAdapter.setItems(images)
}
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views
Toast must be in UI thread .
Toast.makeText(getApplicationContext(), "Start Talking....",Toast.LENGTH_LONG).show();
Android - ViewRootImpl$CalledFromWrongThreadException
Put this in onCreate()
ImageView imageView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.order);
imageView = (ImageView)findViewById(R.id.imgView);
new DownloadFilesTask().execute();
}
And your AsyncTask
class should be like this,
private class DownloadFilesTask extends AsyncTask<Void, Void, Void> {
Drawable drawable;
@Override
protected Void doInBackground(Void... params) {
drawable = createDrawableFromURL(
"http://savagelook.com/misc/sl_drop2.png");
return null;
}
protected void onPostExecute(Void result) {
imageView.setImageDrawable(drawable);
}
}
Getting ViewRootImpl$CalledFromWrongThreadException when calling invalidate function in Custom Surface View
Only the original thread that created a view hierarchy can touch its views.
You need to use RunOnUiThread
from within your thread code whenever you update your views:
RunOnUiThread (() => {
someView.SomeProperty = "SO";
});
re: https://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)
Android: got CalledFromWrongThreadException in onPostExecute() - How could it be?
i was suffering from the same problem, this is another android framework bug...
what is happening:
in certain circumstances an application can have more than one "looper" and therefore more than one "UI thread"
--side note-- i am using the term "UI thread" in the loosest of senses in this answer, since when people say "UI thread" they usually mean main or entry thread, Android like many of other OS before it, allow for for multiple message pumps (called a Looper
in Android, see: http://en.wikipedia.org/wiki/Event_loop) for different UI trees, as such android for all intents and purposes is capable of running more than one "UI thread" in certain circumstances and using that term leads to rampant ambiguities... --end side note--
this means:
since an application can have more than one "UI thread" and an AsyncTask
always "Runs on the UI thread" [ref], someone decided [poorly] that instead of the AsyncTask always running on its creation thread (which in 99.999999% of cases would be the correct "UI thread") they decided to use hocus pocus (or a poorly crafted shortcut, you decide) to execute on the "main looper"..
example:
Log.i("AsyncTask / Handler created ON: " + Thread.currentThread().getId());
Log.i("Main Looper: " + Looper.getMainLooper().getThread().getId() + " myLooper: "+ Looper.myLooper().getThread().getId());
new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... params) {
Log.i("doInBackground ran ON: " + Thread.currentThread().getId());
// I'm in the background, all is normal
handler.post(new Runnable() {
@Override
public void run() {
Log.i("Handler posted runnable ON: " + Thread.currentThread().getId());
// this is the correct thread, that onPostExecute should be on
}
});
return null;
}
@Override
protected void onPostExecute(Void result) {
Log.i("onPostExecute ran ON: " + Thread.currentThread().getId());
// this CAN be the wrong thread in certain situations
}
}.execute();
if called from the bad situation described above the output will look something like this:
AsyncTask / Handler created ON: 16
Main Looper: 1 myLooper: 16
doInBackground ran ON: 12
onPostExecute ran ON: 1
Handler posted runnable ON: 16
that's a huge FAIL for AsyncTask
as shown this can be mitigated using a Handler.post(Runnable)
in my specific case the duality of my "UI thread" situation was caused by the fact that I was creating a dialog in response to a JavaScript interface method called from a WebView
, basically: the WebView
had its own "UI thread" and that was the one that i was currently running on..
from what i can tell (without really caring about or reading into it too much) it seems that the AsyncTask
class' callback methods in general run off a single statically instantiated handler (see: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.0.3_r1/android/os/AsyncTask.java#AsyncTask.0sHandler), which means that it is always going to execute on the "main thread" or "entry thread" which they incorrectly refer to as the "UI thread" (which is presumed as any thread where UI interactions take place, eg. multiple threads in this case) this is both shoddy craftsmanship and shoddy documentation from the android team... weak sauce, the sauce is weak
hope this helps you -ck
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
To keep it simple, I would do this:
btnBuscarProduto.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Looper.prepare();
/*This is a string*/resultadoBusca = buscar(edtBuscaProduto.getText().toString());
System.out.println("Resultado da Busca: "+resultadoBusca);
MyActivity.this.runOnUiThread(new Runnable(){
@Override
public void run() {
if(resultadoBusca.equalsIgnoreCase("Vazio")){
Toast toast = Toast.makeText(getActivity(), "Nada Encontrado", Toast.LENGTH_SHORT);
toast.show();
}else{
/*This is a List<String>*/listaBusca = makeList(resultadoBusca);
System.out.println("Lista da Busca"+listaBusca);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, list);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item);
spnProdutos.setAdapter(spinnerArrayAdapter);
}
}});
}
}).start();
}
});
ViewRootImpl$CalledFromWrongThreadException rxjava setVisibiltiy through rxjava
You applied delay
after observeOn
so the flow was switched away from the UI thread. Drop observeOn
and reorder the flow as follows:
Disposable disposable = Single.concat(
getClearStorageObservable()
.doOnError(Timber::e)
.onErrorResumeNext(Single.just(false)),
getDownloadObservable())
.subscribeOn(schedulers().io())
.timeout(5, TimeUnit.SECONDS, schedulers().ui())
.delay(DELAY_VALUE, TimeUnit.SECONDS, schedulers().ui())
.subscribe(status -> hideErrorInformation(),
error -> showErrorInformation()
);
disposables().add(disposable);
Related Topics
How to Use Mkfifo Using Android's Ndk
Gradle Duplicate Entry: Java.Util.Zip.Zipexception
Custom Font for Android Listview
Which View Should Be Used for New Material Design Bottom Navigation
Android Home Screen Widget (Icon, Label - Style)
Using the "Animated Circle" in an Imageview While Loading Stuff
What Is the Meaning of Android.Intent.Action.Main
How to Set Recyclerview App:Layoutmanager="" from Xml
Android Getorientation Azimuth Gets Polluted When Phone Is Tilted
@Android Display /Res/Viewable in Webview
Android - Build Separate APKs for Different Processor Architectures
Retrieve Contact Phone Number from Uri in Android
How to Implement a Gcm Hello World for Android Using Android Studio
Android Sharedpreferences Limitations
Sending Intent with Bundle Using Console
Live-Stream Video from One Android Phone to Another Over Wifi