I wants to create a custome Input Method with word suggestions from a webservice in an asynchronous way. If it is not asysnchronouse , phone get stuck while connecting to internet. If I use Thread it cause an excpetion "ui can be touch only by the tread created ". I don't know runOnUIthread can be used or how. I understood that runOnUiThread activity method. Anybody please help. I used android Example app softkeybord.
I'm not sure I understand,
If the definition of the Thread is inside the Activity,
You can just call:
new Thread() {
public void run() {
while (i++ < 1000) {
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
btn.setText("#" + i);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
Related
I'm building a simple Android Application. I want to parse JSON. I have everything working using Button. But I want call it without using Button. It need to be get the JSON first from url and then Parse it. I have function getJson() and parseJSON(). First I want getJSON to be called and after 5 second parseJSON(). here is my code:
Runnable[] methods = new Runnable[]{
new Runnable() {
#Override
public void run() {
Toast.makeText(SheduleActivity.this, "This is gettin JSON", Toast.LENGTH_LONG).show();
getJSON();
}
},
new Runnable() {
#Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
},
new Runnable() {
#Override
public void run() {
Toast.makeText(SheduleActivity.this, "This is Parsing JSON", Toast.LENGTH_LONG).show();
parseJSON();
}
}
};
for(Runnable r : methods)
//r.run();
service.submit(r);
service.shutdown();
while (!service.isTerminated()) {}
Toast.makeText(SheduleActivity.this,"Finished all threads", Toast.LENGTH_LONG).show();
Everytime I run my app only getJSON() method calls and stops. Any suggetions?
I think you need to use AsyncTask. put getJson() in doInBackground block and parseJSON() on onPostExecute block. hope this help.
Android does not suggest to use sleep(5000) for delay. Use handler to do this. See the documentation of Handler.
For example in your code,
Handler handler = new Handler( /* --- */ );
handler.postDelayed(methods[i], 5000);
Also for getting json from web, it is suggested to use Asynctask to make the UI responsive. Best tutorial for Asynctask is here.
Good day everyone.
I'm working with AsyncTasks and calling publishProgress(); from doInBackground() method. I'm pretty sure there's no error until here.
I need to change an ImageView's source, e.g. in every 3 seconds from onProgressUpdate() method.
If i only do this;
agiz.setImageResource(R.drawable.image1);
initial image successfully changes to image1.
But if i try to do this (which is my goal actually)
imageView.setImageResource(R.drawable.image1);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
imageView.setImageResource(R.drawable.image2);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
imageView.setImageResource(R.drawable.image3);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
}
imageView WAITS 6 SECONDS, THEN turns to image3, without showing image2.
What am i missing ?
Thanks in advance.
I think you need a postDelayed method. It will be more readable and effective, because this method works in UI thread.
imageView.postDelayed(new Runnable(){
#Override
public void run() {
imageView.setImageResource(R.drawable.image1);
}}
,3000);
imageView.postDelayed(new Runnable(){
#Override
public void run() {
imageView.setImageResource(R.drawable.image2);
}}
,6000);
imageView.postDelayed(new Runnable(){
#Override
public void run() {
imageView.setImageResource(R.drawable.image3);
}}
,9000);
Explantation your problem.
I suppose that you block UI thread. Thread.sleep() method block current thread immediatly without waiting while your imageView was repainted, so you getting a lock result.
so I am building an experiment app where the background will change colour at random intervals.
I am stuck on the background change.
I have working code that changes the background colour, but when I put it in a thread/ try and catch bracket, the application is forced to close and doesnt give me an error?
Here is the code that works when used in the oncreate method:
View view = this.getWindow().getDecorView();
view.setBackgroundColor(Color.RED);
But when I want to make it "sleep" for 1 second and then change it to red, it bombs out.
Please note that this method is a separate method from the oncreate and is called from within there and will not work for some reason?
public void changeBackground(final View v){
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
v.setBackgroundColor(Color.RED);
}
}
};
timer.start();
}
What am I doing wrong?
What I need:
when the app starts, it must wait for 1 second and then change the background colour without it bombing out.
Thanks in advance!
You cannot access UI thread from your custom thread. You have to run your runnable in UI thread. Change your changeBackground method to the following,
public void changeBackground(final View v) {
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
v.setBackgroundColor(Color.RED);
}
}
};
this.runOnUiThread(timer);
}
Or you can use Asynctask, this handles that issue for you. Here, and here.
Manipulate view state on UI thread:
v.post(new Runnable() {
#Override
public void run() {
v.setBackgroundColor(Color.RED);
}
});
More about it: http://developer.android.com/guide/components/processes-and-threads.html
UI operations can't be done in a Thread
v.setBackgroundColor(Color.RED);
Remove above line from finally and Use a runOnUIthread() to update UI in Finally.
and your final code will look like this
public void changeBackground(final View v){
Thread timer = new Thread(){
public void run(){
try{
sleep(1000);
}catch (InterruptedException e) {
e.printStackTrace();
}finally{
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
v.setBackgroundColor(Color.RED);
}
});
}
}
};
timer.start();
}
Solutions to fix this issue:-
Update you App
Clear Gmail Storage Data
Clear App Cache and Data
Reset App Preferences
Reset Smartphone Factory Settings
I found these steps with the help of YouTube.
Here is that link:-
youtube.com/watch?v=fx8Fv8RXag8
So, I have a code:
((Button) findViewById(R.id.run)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
progDialog = ProgressDialog.show(WaggActivity.this,
"", "Loading...", true, true);
new Thread(new Runnable() {
public void run() {
try {
urlTxt.setText(findUrl(String.valueOf(search.getText())));
} catch (Exception e) {
Log.e("MainActivity", e.getMessage());
}
progDialog.dismiss();
}
}).start();
I cannot find a mistake. :(
Error is: Only the original thread created a view hierarchy can touch its vews.
In Android you have a UI-Thread, in which is created by your activity. This is the only thread in which you can modify the Views, which in your case is the ProgressDialog.
So you can't modify it from other threads, you must call it from within your Ui-thread.
You should call : Activity.runOnUiThread(Runnable)
; As explained here.
Isn't the error message quiet clear? Only the main thread may access the Views.
You are accessing urlTxt in another, custom thread.
To solve this issue, use the following snippet
urlTxt.post(new Runnable() {
public void run() {
urlTxt.setText(findUrl(String.valueOf(search.getText())));
}
});
I was trying to run a small worker thread in the middle of an activity which would get some stuff from a web service and fill a container when it returned.
new Thread() {
#Override
public void run() {
Log.w("thread", "can read from thread");
try {
MyActivity.this.runOnUiThread(new Runnable() {
public void run() {
Log.w("internal thread", "running");
}
});
}
catch (Exception e) {
// etc
}
}
}.start();
The "internal thread: running" would never print in the log, and when I ripped out the contents and just pasted it into the main body of the method, it worked. My conclusion is that the doubly nested thread never ran. Why would that happen? Am I misusing runOnUiThread?
Thanks!
Why would that happen? Am I misusing runOnUiThread?
Yeas ! runOnUiThread is other thread than Main thread. i suggest to have a look at Android Handler.