Im following the android docs on asynctask, trying to get an asynctask going that can perform actions on wifi in background, the issue im running into is at Asynctask in the code below, void and boolean or whatever i put there keep showing up as errors with the message "Dimensions expected after token". I dont know what this is referring to, everything above this section looks fine and works fine, couldnt find much on google either.
public class MainActivity extends Activity{
.......
class wifilistener extends AsyncTask<WifiManager,void,boolean> //trouble spot {
protected void onPreExecute(){
//show info on UI thread
}
protected boolean doInBackground(WifiManager...wifi1) {
//do stuff
}
protected void onProgressUpdate(){
}
protected void onPostExecute(boolean result) {
}
}
}
Try Void and Boolean; you have to use Object instead of primitive type for Asynctask. So, use uppercase V and B, and that should work.
Related
I am getting all the dates between two given dates and then creating fragments for each date in between. The problem is when I use Asynctask and put the method in the doinbackground sometime it works and sometime it doesn't.
Specially when I open Asynctask containing activity from another activity. But on button click inside activity it works with a progressbar.
public class WaitForLoad extends AsyncTask<String, Integer, String>{
#Override
protected void onPreExecute() {
super.onPreExecute();
pro_bar.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
pro_bar.setVisibility(GONE);
}
#Override
protected String doInBackground(String... strings) {
get_con_fro_sta_to_end(dat_ran_sta, dat_ran_end);
return null;
}
}
So according to Asynctask documentation it should be 3 sec. But if I put a entire year in the method it takes about 8 sec to load or so.
So is there any workthrough Asynctask or Can you suggest me an example alternative Like maybe using a handler or so.
I think you're changing Interface from your "get_con_fro_sta_to_end()" method...This is not allowed from a Background Thread and then it should be changed somehow.
AsyncTasks have the "void onProgressUpdate()" that is used to execute code in the UiThread/MainThread every time "publishProgress()" is called from "doInBackground()".
DoInBackground() should NOT touch Interface but just prepare Data/Things to be displayed using "onPostExecute()" (which runs code in the UiThread/MainThread)
So as the title probably suggests - I've done a lot of research on the topic, but I am still confused and unable of achieving what I want.
In very simplified scenario, I have a LoginActivity in which is method boolean validateUserInput(String mail, String password) and I want to do the check input in the separate thread. I suppose I will extend it in the future to do the log-in itself as well (http request). Naturally I would like to get boolean value if the operation was successful or not - and in the process of operation I want to show progressbar dialog.
Make a thread, run the code, return its result, show the progress bar in a meantime, piece of cake right?
Should I use asynctask or runnable? How do I do this so I do not block the UI thread?
This is code I tried to use in LoginActivity:
new Thread(new Runnable() {
#Override
public void run() {
mUserInputValidated = validateUserInput(inputEmail.getText().toString(), inputPassword.getText().toString());
}
}).start();
if(mUserInputValidated)
{
attemptUserLogin(inputEmail.getText().toString(), inputPassword.getText().toString());
}
I also tried asynctask approach, but ended up with various errors since I started progress dialog in onPreExecute() and ended it in onPostExecute(), using reference like LoginActivity.this where was the problem with memory leak which I was also unable to fix?
I assume this is pretty usual scenarios, since almost every app use it, so - what are common approaches? How do I fix my code?
You have to use asynctask this will take the work off from main-thread and place it on background thread once the work is done
This is a sample that shows how to do it
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.interrupted();
}
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
TextView txt = (TextView) findViewById(R.id.output);
txt.setText("Executed"); // txt.setText(result);
// might want to change "executed" for the returned string passed
// into onPostExecute() but that is upto you
}
#Override
protected void onPreExecute() {}
#Override
protected void onProgressUpdate(Void... values) {}
}
Reference
I have been trying to change textView after I'm done networking in an another thread with AsyncTask. I've tried countless solutions, but none have worked so far.
The only way I was able to achieve my goal was to use .get(), but it stops the UI thread for a while, and that's something I don't want.
I've also tried using the AsyncTask as an outer class, and using a wrapper class in the middle.
So my question here is, what is the easiest way to get hold of a variable used in doInBackground() and onPostExecute(), without freezing the main thread?
Here is a way to do it. You can give a callback in parameter of your async task, do whatever you want and them get the value back from the async task.
Callback interface :
public interface AsyncTaskCompleteListener<T> {
public void onTaskComplete(T result, int number);
}
AsyncTask :
public class LoadURL extends AsyncTask<String, Process, String> {
private AsyncTaskCompleteListener<String> callback;
public LoadURL(AsyncTaskCompleteListener<String> cb) {
this.callback = cb;
}
protected void onPreExecute() {}
protected String doInBackground(String... arg0) {
// do something
return content;
}
protected void onPostExecute(String content) {
if (callback != null)
callback.onTaskComplete(content,number);
}
}
Activity :
public class LoginActivity extends Activity implements AsyncTaskCompleteListener<String> {
#Override
protected void onCreate(Bundle savedInstanceState) {
LoadURL loadUrl = new LoadURL(LoginActivity.this);
loadUrl.execute(...);
}
#Override
public void onTaskComplete(String result, int number) {...}
}
in onTaskComplete, you can easily modify your TextView
Just update the UI in the following code inside the AsyncTask:
#Override
protected void onPostExecute(Int result) {
textView.setText(result.toString());
}
Check this link if you need extra help.
You should return the variable from doInBackground(). Framework will make sure you will get the returned value in onPostExecute().
onPostExecute runs on the UI thread so you should be able to refresh any UI element here.
So I am using parse framework in my Android app and everything works great except for one little thing. When I push the app into the background and resume it after while. I am getting
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
at com.android.org.conscrypt.OpenSSLSocketImpl.close(OpenSSLSocketImpl.java:1009)
at org.apache.http.impl.SocketHttpClientConnection.close(SocketHttpClientConnection.java:205)
at org.apache.http.impl.conn.DefaultClientConnection.close(DefaultClientConnection.java:161)
at org.apache.http.impl.conn.tsccm.AbstractConnPool.closeConnection(AbstractConnPool.java:320)
at org.apache.http.impl.conn.tsccm.AbstractConnPool.shutdown(AbstractConnPool.java:296)
at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.shutdown(ConnPoolByRoute.java:670)
at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager.shutdown(ThreadSafeClientConnManager.java:256)
at com.parse.ParseRequest.initialize(ParseRequest.java:104)
at com.parse.Parse.initialize(Parse.java:108)
I am not sure how to prevent that and it only happens when the application comes back after beeing a very long time in the background.
I heard from somewhere that, this behaviour only happens on KitKat but this is by no means a reassurance. I already thought about performing the initialization in a separate thread but I couldn't get it to work (I am new to this)
I initiliaze parse by performing this code in my Activity:
#Override
public void onCreate()
{
super.onCreate();
Parse.initialize(this, "xxxx", "xxxxx");
}
I hope someone who is using the parse framework has a solution to this.
You should not call this method from a new thread in your Activity. In fact, the official Parse documentation advises you not to call this method from an Activity at all. Rather, you should call parse.initialize from the Application.onCreate() method, instead of your Activity.onCreate() method. I didn't think this was a big deal to just call it from Activity.onCreate(), but apparently it is, especially in KitKat. This is fairly simple to implement, though. Create a new java class file that extends android.app.Application. The file should have the exact same name as your project (case sensitive). Something like:
package com.your_package.your_project_name;
import com.parse.Parse;
import android.app.Application;
public class your_project_name extends Application {
#Override
public void onCreate(){
super.onCreate();
Parse.initialize(this, "your application id", "your client key");
//if you need to, initialize ParseFacebookUtils, etc. here
}
}
Its becuase you are using Networkservice in your main thread and that is not allowed in the android so create a new thread and call a netwokservice from that. some thing like this.
new Thread(new Runnable() {
#Override
public void run() {
// your logic for network service
}
}).start();
You could try just sticking that line in an AsyncTask:
new AsyncTask<Void, Void, Void>() {
#Override
public Void doInBackground(Void... params) {
Parse.initialize();
}
}.execute();
You can do it with AsyncTask. Write AsyncTask class in your main class that you want to do your operations. If you want, you can create the progress dialog in preexcecute of your async class and dismiss in onpostexecute of async class to show a loading indicator while your AsyncClass does parsing operation. Here is how you will do this:
class MyAsync extends AsyncTask<String, Void, Void> {
ProgressDialog pd;
Context co;
MyActivity ma;
public MyAsync (MyActivity ma){
this.ma= ma;
this.co = ma;
pd= new ProgressDialog(co);
}
#Override
protected void onPreExecute() {
this.pd.show();
super.onPreExecute();
}
#Override
protected Void doInBackground(String... params) {
Parse.initialize(this, "xxxx", "xxxxx");
return null;
}
#Override
protected void onPostExecute(Void result) {
// show results after parse and dismiss progress dialog pd.dismiss();
super.onPostExecute(result);
}
}
in MyActivity call as :
MyActivity ma = this;
new MyAsync(ma).execute();
I have this code for android to open a url, but I can't make it to run in the background. Is it possible?
Can someone help me with this? Thanks.
public void goToSu (View view) {
goToUrl("http://192.168.2.66/index.html?o0=0");
}
private void goToUrl (String url) {
Uri uriUrl = Uri.parse(url);
Intent background = new Intent(Intent.ACTION_VIEW, uriUrl);
startActivity(background);
}
You cannot make network operations in your main UI, because that would block your program execution with a very disgusting experience for your users. For this, you have to separate network operations inside a Thread, or even better, an AsyncTask if you're just starting with the thread world.
This is the structure you would use:
final class MyNetworkOperation extends AsyncTask<URL, Integer, Void> {
#Override
protected void onPreExecute(final Void param) {
...
}
#Override
protected Void doInBackground(final URL... args) {
...
return null;
}
#Override
protected void onPostExecute(final Void param) {
...
}
}
Even the method names are very self explanatory. When you define your AsyncTask, and call .execute(url_object) on it, the first called method will be .onPreExecute(), there you may initialize variables and prepare everything for the network operation you want to do. The hard part of your network operation should be done inside doInBackground(). There you connect, do the data transfer and disconnect from the host. Finally, onPostExecute() is called: Once you're done, you can process here your results (transfer it to the main Activity, show a Dialog, etc.).
For more on AsyncTasks (and know what does those parameters mean) I strongly recommend reading the reference.
A very good example might be found here.