Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
When using AsyncTask in android, I have to use like this,
new MyAsyncTask().execute()
I have to make new instance If I want to use AsyncTask.
But I wonder why I have to do.
I just want to use it like,
private MyAsyncTask task;
...
private void foo()
{
...
task.excute();
}
BUT I can't.
And I want to know why it doesn't work.
If you give me answer, I'm very appreciated.
Java is not RAII. You always need to create an instance of a class, because you cannot execute methods on a class directly unless the method is static. But then still the syntax would be different.
What you can do is more like this:
private MyAsyncTask task;
…
private void foo() {
task = new MyAsyncTask();
…
task.execute();
}
execute() is a method of AsyncTask. If you want to invoke then you need to create an instance of Asynctask.
If you want to execute a method of a class you need to instantiate and then call the appropriate methods.
task.excute(); will give you NUllPointerException.
task = new MyAsyncTask();
task.execute();
You may also want to check
http://docs.oracle.com/javase/tutorial/java/javaOO/objectcreation.html
Look at the public methods as suggested by prosper k it is not a static method
http://developer.android.com/reference/android/os/AsyncTask.html
This is a matter of Java not Android. In java, something like:
MyAsynkTask task;
doesn't create an object. In this step you have only declared a variable. To use any method of your object (e.g. task.execute()) you have to instantiate an object (i.e. actually create one); like:
task = new MyAsyncTask();
Check this link for basics of "new" keyword. Basically it is use for Instantiating a Class.The new operator instantiates a class by allocating memory for a new object and returning a reference to that memory. The new operator also invokes the object constructor.
Hope this helps you.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 months ago.
Improve this question
I was always facing this memory leak warning without paying much attention to it, but now I'm looking into how to deal with it and, as I know I shouldn't use WeakReference and that sort of "tricks" to avoid it, come to what I think could be a possible and simple solution.
My idea is as follows:
I have a singleton class (object) which holds all my app configuration, where I initialize a context from the Application class like this:
object AppSettings {
lateinit var context: Context
fun init(appContext: Context){
this.context = appContext
}
/* OTHER STUFF */
}
typealias aw = AppSettings
#HiltAndroidApp
class AWApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
AppSettings.init(this)
}
/* OTHER STUFF */
}
I initialize that context not only in ApplicationClass, but in every activity OnCreate (which inherits from BaseActivity):
#AndroidEntryPoint
open class BaseActivity {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
AppSettings.init(this)
}
}
And finally, I can access context wherever it is needed as follows:
object RandomObject {
fun DoWhatever() {
PlayAFreddieMercurySong(aw.context,)
}
}
Well, this is my possible solution and I would like to know Android gurus from SO opinion about it.
Maybe I'm leaking memory in my App Settings -where I had initially store context-, but Android Studio is not complaining about it, so I am not sure.
In the end, I'm trying to avoid passing context as a method parameter in every place it is needed for code simplicity.
"other stuff" are common between all activities and they need just ApplicationContext, then why you don't use application context in AppSettings. and thats it. BTW your solution will not leak, if and only if you call your AppSettings.init(this) in all activities.
and you don't guarantee that .
in other words "the code doesn't leak now but may be in the future" - vulnerable
if you have functions thats related to activities, fragments or any
class you want, you can use extension functions for that
you should create a kotlin file with name for ex ActivityExt. and write all of your cases that you need for activities . if you need functions for fragments you should also create another kotlin file with name FragmentExt..etc
I have a small Android application in which I need to do some FTP stuff every couple of seconds.
After learning the hard way that running network stuff on the UI thread is something Android does not really like, I've come to this solution:
// This class gets declared inside my Activity
private class CheckFtpTask extends AsyncTask<Void, Void, Void> {
protected Void doInBackground(Void... dummy) {
Thread.currentThread().setName("CheckFtpTask");
// Here I'll do the FTP stuff
ftpStuff();
return null;
}
}
// Member variables inside my activity
private Handler checkFtpHandler;
private Runnable checkFtpRunnable;
// I set up the task later in some of my Activitiy's method:
checkFtpHandler = new Handler();
checkFtpRunnable = new Runnable() {
#Override
public void run() {
new CheckFtpTask().execute((Void[])null);
checkFtpHandler.postDelayed(checkFtpRunnable, 5000);
}
};
checkFtpRunnable.run();
Is this good practice to perform a recurring task that cannot run on the UI thread directly?
Furthermore, instead of creating a new AsyncTask object all the time by calling
new CheckFtpTask().execute((Void[])null);
would it be an option to create the CheckFtpTask object once and then reuse it?
Or will that give me side effects?
Thanks in advance,
Jens.
would it be an option to create the CheckFtpTask object once and then reuse it? Or will that give me side effects?
No, there will be side-effects. Quoting the docs Threading Rules:
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
You will just need to create a separate instance of the task each time you want to run it.
And I'm not sure why you need the Runnable or Handler. AsyncTask has methods that run on the UI Thread (all but doInBackground(), actually) if you need to update the UI.
Check this answer if you need a callback to update the UI when the task has finished.
You should create a new Async task for every call.
See the Android Documentation: AsyncTask. According to this documentation:
The task can be executed only once (an exception will be thrown if a second execution is attempted.)
Specifically check out the threading rules section. There is a similar answer here, https://stackoverflow.com/a/18547396/2728623
Java ThreadPools and the ExecutorFramework allows you to execute threads as needed and reduces thread creation overhead. Check out the singleThreadExecutor. The thread pool usage is pretty easy too!
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have been given an assignment to develop an application that send server request and get response and then using JSON parsing, display the data content into a ListView.
I don't understand about AsyncTask and how to integrate all classes. Hope you will accommodate.
regards
What should you do?
The first, send a request to server
The second, get response
The thirds, Parse data from InputStream which you got from Response
The fourth, show on ListView
Oh, done.
Right now,
Look into the first step.
How to send a request to server?
You can use HttpURLConnection or HttpClient
So, What's problem when you send a request to server?
I think you know when you send a request to server, you will get some problem: Network bad, InputStream from Server too large, ...
And how to resolve?
With single statement, you can't take along time to do. So with task which will takes along time to do, you have to handle in other thread. That's reason why we should use Thread or AsyncTask.
What's AsyncTask?
You can read more by search on Google. I just tell you: How to use AsyncTask to solve your spec.
What does AsyncTask do?
When you create an instance of AsyncTask,
It's will follow:
-> Create -> PreExecute -> Execute (DoInBackground) - PostExecute
Ok.
Right now, I will answer your question:
Create an object which extends AsyncTask.
public class DownloadFile extends AsyncTask<String, Void, InputStream> {
#Override
public void onPreExecute() {
// You can implement this method if you want to prepare something before start execute (Send request to server)
// Example, you can show Dialog, or something,...
}
#Override
public InputStream doInBackground(String... strings) {
// This is the important method in AsyncTask. You have to implements this method.
// Demo: Using HttpClient
InputStream mInputStream = null;
try {
String uri = strings[0];
HttpClient mClient = new DefaultHttpClient();
HttpGet mGet = new HttpGet(uri);
HttpResponse mResponse = mClient.execute(mGet);
// There are 2 methods: getStatusCode & getContent.
// I dont' remember exactly what are they. You can find in HttpResponse document.
mInputStream = mReponse.getEntity().getContent();
} catch (Exception e) {
Log.e("TAG", "error: " + e.getMessage());
}
return mInputStream;
}
#Override
public void onPostExecute(InputStream result) {
//After doInBackground, this method will be invoked if you implemented.
// You can do anything with the result which you get from Result.
}
}
Ok. Now we have to use this class
In your MainActivity or where you want to invoke this class, create an instance of this class
DownloadFile mDownloader = new DownloadFile();
mDownloader.execute("your_url");
Using method mDownloader.get(); to get InputStream if you want to get. But you have to surround by try-catch
I know, if you want to use Dialog, you will search on Google how to show Dialog while download file from server.
And I suggest you that you should remember, you nead runOnUiThread if you want to Update UI.
Because an AsyncTask is Thread. So you can not Update UI if you are in another Thread which is not MainThread.
AsyncTask
AsyncTask enables proper and easy use of the UI thread. It is used when you want to perform long awaited task in background.
It publish result on the UI thread(display result to the UI) without having to manipulate any threads or handlers.It means that user doesn’t bother about Thread management, everything is managed by itself. And thats why it is known as Painless Threading, see below point.
It is also known as Painless Threading.
The result of AsyncTask operation is published on UI thread. It has basically 4 methods to override: onPreExecute, doInBackground, onProgressUpdate and onPostExecute
Never expect to be a programmer by referring short notes, study deep..
Look here for more detail.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the meaning of “this” in Java?
I'm still very new to learning Android programming, and I noticed that "this" was used often in parameters for method calls in the language. I'm following The New Boston tutorials through YouTube, but he never really explains quite detailed enough what the 'this' statement means. Can somebody please explain it to me? Maybe dumb it down a bit?
this refers to the instance of the class you are currently coding within.
You cannot use it in a static context because in this situation you are not within any object context. Therefore this doesn't exist.
public class MyClass {
public void myMethod(){
this.otherMethod(); // Here you don't need to use 'this' but it shows the concept
}
private void otherMethod(){
}
public static void myStaticMethod(){
// here you cant use 'this' as static methods don't have an instance of a class to refer to
}
}
In android class.this is used to pass context around.
Formal definition of context: It allows access to application-specific resources and classes, as well as up-calls for application-level operations such as launching activities.
That means if you need to access resources (including R and user interface) you will have to use context.
In java this means the instance of the class that you are in. For example MainActivity.this points to the current instance of the MainActivity. So by using MainActivity.this.foo you are accessing the foo field of MainActivity class.
public class YourClass {
private int YourInt;
public setTheInt(int YourInt) {
this.YourInt = YourInt;
}
}
"this" is used to see whether an attribute or function belongs to the class we're working on, clearer.
Also, you see that setTheInt operation gets an integer named as the same as your attribute. In that function's namespace, YourInt is not this class's YourInt, but a reflection of the integer coming from setTheInt's calls. "this" helps here to divide the outer and the inner "YourInt"s.
I am using the TextToSpeech API and I want to seperate some logic into another class.
In the separate class I have put the following method:
public static void sayHello() {
// Select a random hello.
int helloLength = SoundGameScore.Questions.length;
String hello = SoundGameScore.Questions[currentHelloIndex];
currentHelloIndex = (currentHelloIndex + 1) % helloLength;
mTts.speak(hello, TextToSpeech.QUEUE_FLUSH, // Drop all pending entries
// in the playback queue.
null);
I have then created a variable in the main class: static mainclass object;
Within a button in the main class I call the method through this object by using:
object.sayHello();
I am quite new to android, and I know I am doing something wrong as this gives me a process closed error in the emulator. This also shows a nullexception error in logcat. Please help me, thanks.
I think you are getting a NullPointerException because the reference object is null. You would need to initialise the object in order to call an instance method on it.
However since sayHello() is a static method, you do not need to create an instance of the class in order to call the method. Just use mainclass.sayHello().
Your question and code suggests to me that you do not have much experience with Java. Perhaps you should do some tutorials to brush up on your Java coding before jumping into Android development. For example, Java convention is for class names to be capitalised (MainClass) and for references to have meaningful names (i.e. not things like object).