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);
}
}
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
.
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.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 - Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException
Bad practice of use of AsyncTask,
You are trying to update your Main UI Thread from doInBackGround()
as AsyncTask never allowed that.
Never update your UI from doInBackGround()
of AsyncTask as its only worker thread. So write your Main UI updatation code in onPostExecute()
method of AsyncTask..
@Override
protected Void doInBackground(Void... params) {
try {
URL myFileUrl = new URL("http://sposter.smartag.my/images/chicken_soup.jpg");
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
downloadBitmap = BitmapFactory.decodeStream(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
onPostExecute()
{
ImageView image = (ImageView) findViewById(R.id.imview);
image.setImageBitmap(downloadBitmap);
}
Timer causing ViewRootImpl$CalledFromWrongThreadException?
The TimerTask
is executed on a worker thread (non-UI thread). Your UI (sinceView
) has to be accessed from the main (UI) thread. There is a helper method in an Activity
to do this: runOnUiThread.
MainActivity.this.runOnUiThread(new Runnable() {
sinceView.setText(Helpers.toDuration(longLast));
});
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views. (RxJava)
You should be using observeOn(AndroidSchedulers.mainThread())
not subscribeOn(AndroidSchedulers.mainThread())
. Use as
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
subscribeOn used to specify the Scheduler on which an Observable will operate. In your case it will be an IO scheduler.
ObserveOn is used specify the Scheduler on which an observer will observe this Observable i.e the completion in this case it will be Main thread
How to fix android.view.ViewRootImpl$CalledFromWrongThreadException
You are updating Views in a different thread
removeContent();
initView();
Call this two methods in a UI thread like.
runOnUiThread(new Runnable() {
@Override
public void run() {
removeContent();
initView();
}
});
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();
}
});
Related Topics
Open Gallery App from Android Intent
Reading in from System.In - Java
How to Find How Much Disk Space Is Left Using Java
Why Does a Try/Catch Block Create New Variable Scope
Check Chains of "Get" Calls for Null
How to Create My Own Appender in Log4J
How to Increase the Number of Displayed Lines of a Java Stack Trace Dump
Spring Boot - Handle to Hibernate Sessionfactory
Reading Properties File in Java
Setting the Default Font of Swing Program
Converting Utf-8 to Iso-8859-1 in Java - How to Keep It as Single Byte
Java Hotspot(Tm) 64-Bit Server Vm Warning: Ignoring Option Maxpermsize
Setting a Timeout for Socket Operations
How to Get a String Between Two Characters