here's a portion of my code:
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
DialogSelectAccount dsa=new DialogSelectAccount(getParent());
dsa.show();
}
}
}
public class DialogSelectAccount extends Dialog implements android.view.View.OnClickListener {
public DialogSelectAccount(Activity a) {
super(a);
}
}
but when I run the app, it get a NPE error at the "super(a)" under the public DialogSelectAccount();
but when I changed my code to
public class Login extends Activity {
private class LoginUser extends AsyncTask<String, String, Boolean> {
#Override
protected void onPostExecute(Boolean returnResult) {
test();
}
}
public void test(){
DialogSelectAccount dsa=new DialogSelectAccount(this);
dsa.show();
}
}
it works. So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
Thanks
So what if I don't want to create a separate method like above and calls DialogSelectAccount directly inside the onPostExecute, what should I pass as the argument?
answer:
DialogSelectAccount dsa=new DialogSelectAccount(Login.this);
This is rather general java question, for more on inner classes read here: Getting hold of the outer class object from the inner class object
The dialog class needs a Context attribute.
When you say getParent() - I suppose it does not return context.
You can keep the context attribute in a global class and retrieve it - though I will not recommend that.
Related
I have been looking for a long time for a simple way to pass data (string type) from class to activity.
I found some tutorials about passing data from activity to class but is it possible to do the opposite, passing data from class to activity ?
if you import the class in your activity (which is also a class by the way) you can easily access the classes attributes.
example: MyClass.java
package edu.user.yourappname;
public class MyClass {
public string infoToPass = "whatever";
}
MyActivity.java
package edu.user.yourappname;
import edu.user.yourappname.MyClass
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String myString = MyClass.infoToPass;
}
}
i have no IDE to type this in atm it might contain some errors :S but i hope you get the idea.
if you need more specific help you have to provide a code sample.
also, what do you want to achieve exactly? maybie there's a different approach.
cheers!
Create Interface and implement that in your activity. Pass the activity instance in your class and and call that instance with interface method whenever you like.
To be more clear, create an interface and use it as following:
public interface SomeInterface{
public void passValue(String value);
}
public SomeActivity extends Activity implements SomeInterface{
// place any code you want in your activity, onCreate, onResume, etc.
private void someMethod(){
// Wherever in your activity, initialize your class with your activity.
SomeClass someClass = new SomeClass(this);
someClass.someMethod();
}
public void passValue(String value){
// do whatever you want with your value
}
}
public class SomeClass{
private SomeInterface someInterfaceInstance;
public SomeClass(SomeInterface someInterfaceInstance){
this.someInterfaceInstance = someInterfaceInstance;
}
public void someMethod(){
// Some code...
someInterfaceInstance.passValue("Hello World!");
// Some more code...
}
}
Here is a easy way of doing it -
By defining static variables
In your class, make the String whose value you want to pass public static like this -
public static String pass;
And then in you activity, you can directly access it since it's a public variable like this -
String receive = className.pass;
I'm having trouble implementing a delegate in my android app.
In my GetData class I have nested asynctask, and I need to notify my main activity when all the work has actually finished.
I came up with this answer from Mohd Mufiz
What is the best way for AsyncTask to notify parent Activity about completion?
But I always get stuck at the same point:
in my GetData class I call a constructor with the delegate as only argument:
public class GetData {
private TaskDelegate delegate;
public GetData(TaskDelegate delegate) {
this.delegate = delegate;
}
...
}
In my main activity I don't know what I have to pass to get it working:
GetData getData = new GetData(**???**);
Going from the question you linked to, that defined TaskDelegate as :
public interface TaskDelegate {
public void taskCompletionResult(String result);
}
You can pass GetData any instance of a class that implements TaskDelegate - but typically, that would be the object that creates it - ie. your main activity (and so, therefore, it would also implement "void taskCompletionResult(String result);"). That then means you can pass "this" to GetData's constructor, so :
public class MyMainActivity implements TaskDelegate {
public void someMethod() {
GetData getData = new GetData(this);
}
public void taskCompletionResult(String result) {
// do stuff
}
}
I have a class inside which there is another class that extends AsyncTask. As,
public class Dashboard extends Activity {
-------------
--------------
--------------
public class getUnreadMessageCount extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(){
*********some database stuff************
}
protected void onPostExecute(JSONObject json) {
count = Integer.parseInt(json.getString("messsage_count"));
// Set Text to the textview
messageCount.setText(count);
}
}
}
Now I am using GCMIntentService Class for notification. How can I call and execute the getUnreadMessageCount in the following
private void sendNotification(String content_id, int type, String msg) {
}
I tried as
private void sendNotification(String content_id, int type, String msg) {
Dashboard dashboard = new Dashboard;
dashboard.Dashboard dashboard----
}
But it does not work. How could I solve this problem.
What I see here is very bad style and not according to the Java-Code-Conventions. You are naming a class like a method. In java generally, all Class names are written in capital letters and should be nouns.
public class getUnreadMessageCount extends AsyncTask
should be called (at least):
public class GetUnreadMessageCount extends AsyncTask
or much better:
// make clear it is an async task
public class GetUnreadMessageCountTask extends AsyncTask
This is how to start the AsyncTask:
private void sendNotification(String content_id, int type, String msg) {
new GetUnreadMessageCountTask().execute();
}
The execute(...) method can also take parameters, depending on your specification of the AsyncTask. For a general explaination of the AsyncTask, have a look here: How to use AsyncTask
I would like to call an Activity method after the onPostExecute of my AsyncTask.
Do you know how I can do that?
I want to call in the sendSMS(String phoneNumber, String message) method in the onPostExecute.
One way is to pass an instance of the Activity through PostTask constructor, something like:
private class PostTask extends AsyncTask<String, Integer, String>
{
private AsyncBigCalculActivity activity;
public PostTask(AsyncBigCalculActivity activity)
{
this.activity = activity;
}
// ...
}
and on creating the PostTask instance, pass the activity instance:
new PostTask(this).execute();
Now you can invoke sendSMS() from within PostTask, like:
activty.sendSMS(...);
Also note that if you are defining the PostTask as a private class inside the activty, then you can invoke sendSMS() like:
AsyncBigCalculActivity.this.sendSMS(...);
Add a constructor and a global variable to your AsyncTask like this:
AsyncBigCalculActivity mActivity;
public PostTask(AsyncBigCalculActivity a) {
mActivity = a;
}
Then simply use mActivity.sendSMS("test", "test") when you need it.
However, you should really have methods like sendSMS() in a utility class.
If your AsyncTask is an inner class of your Activity then you should be able to call the Activity method from your onPostExecute(). Otherwise, you can send the Context to a constructor of your AsyncTask and uses that to call the method
Write a Callback
You can create a CallBack using an interface. This way you can use your AsyncTask with any activity. (Loosely coupled code)
1) Create a Callback
interface MyAsyncTaskCallBack{
public void doStuff(String arg1,String arg2);
}
2) Initialize the callback in your AsyncTask
private class MyTask extends AsyncTask<String, Void, Void>
{
private MyAsyncTaskCallBackactivity callback;
public MyTask(MyAsyncTaskCallBackactivity callback)
{
this.callback = callback;
}
//Call callback.doStuff(....phonenum, ....message); in your postExecute
}
3) Implement the Callback in your Activity and override doStuff() method
public YourActivity extends AppCompatActivity implements MyAsyncTaskCallBack{
// Your Activity code
// new MyTask(this).execute("phonenum","msg"); //<--- This is how you run AsyncTask
private void sendMessage(String num, String msg){
// send msg logic
}
#Override
public void doStuff(String arg1,String arg2){
sendMessage(arg1,arg2); // invoke activity method
}
}
I am developing an application in which i need to send the value of the asynctask's onPostExecute method's result in to the previous activity , ie the activity in which the aync task is being called.pls put some codes. Anyhelp is appreciated
Two ways:
Declare class extending AsyncTask as private class in parent Activity
Pass Handler or Activity itself as param of class extending AsyncTask
If I were you, I'd follow the first option.
Look at DOCS:
class MyActivitySubclass extends Activity {
function runOnPostExecute(){
// whatever
}
private class MyTask extends AsyncTask<Void, Void, Void> {
void doInBackground(Void... params){
// do your background stuff
}
void onPostExecute(Void... result){
runOnPostExecute();
}
}
}
Note 1
Code placed in body of function onPostExecute is already run on Activity thread, you should just mention that this keywords leads to MyTask.this and not MyActivitySubclass.this
Well if your AsyncTask is an inner class, you could simply call a method in your activity from onPostExecute():
public class MyActivity extends Activity {
public void someMethod(String someParam) {
// do something with string here
}
public class InnerTask extends AsyncTask<...> {
protected void onPostExecute(result) {
someMethod(Send parameters);
}
}
}
The onPostExecute method is fired on the main UI thread, so anything done there is already on the AsyncTasks caller.
http://developer.android.com/reference/android/os/AsyncTask.html
Fire an event in the OnPostExecute.
Its an add on to the answer by Marek Sebera, he pointed to use a handler. To keep the code simple and intuitive use an interface. This isn't alien concept, we use it all the time for callback functions (eg: OnClickListner etc..). The code would look some thing like this.
public class InnerTask extends AsyncTask<...>
{
interface ResultHandler
{
void gotResult(<> result);
}
private ResultHandler myResult;
//constructor
public InnerTask(....params...,ResultHandler callback)
{
...
this.myResult = callback;
}
protected void onPostExecute(<>result)
{
...
myResult.gotResult(result);
}
}
public class MyActivity extends Activity implements InnerTask.ResultHandler
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
//do something
//if you want the InnerTask to execute here
InnerTask i = new InnerTask(....params...,this); //send 'this' as parameter
i.execute();
}
#Override
public void gotResult(<> result)
{
//from onPostExecute
}
}
If we want to use the same AsynTask class at multiple sites we can use this type of implementation instead of using nested classes implementation.