Reputation: 470
Basically i'm trying to create a class that processes a users login for an app.
The following code is what I have so far:
public class LoginProcess extends MainActivity {
public class GetLoginInformation extends AsyncTask<String, Void, String> {
Context context = MainActivity.this;
protected String doInBackground(String... params){
/**
* It passes the information as 3 parameters
* @Param 1: URL
* @Param 2: Username
* @Param 3: Password
*/
try {
URL url = new URL(params[0]);
} catch(MalformedURLException e){
Mint.logException(e);
e.printStackTrace();
Log.e("LoginProcess", "Malformed URL");
Toast.makeText(context, "Error sending login to URL", Toast.LENGTH_LONG);
}
return "Message received";
}
protected void onPostExecute(String response){
Toast.makeText(context, response, Toast.LENGTH_SHORT).show();
}
}
}
The class is then called by calling (for example) new LoginProcess().new GetLoginInformation().execute("http://www.google.com/", "username", "password");
With this code, i've attempted to extend MainActivity (which is my main android activity) so that I can get the application context using MainActivity.this
, rather than having to pass context as an argument.
I'm wondering whether this is the correct way of doing it - having an outer class which extends your main class, and then the sub class that does the work. At the moment its giving me an error upon trying to show Toast.makeText (which is just an example), but i'm wondering whether i'm on the right track with this or whether there is a better way of doing it (IE passing context as an argument or using getApplicationContext()
* etc)
*I have read the issues surrounding memory leaks and problems when using getApplicationContext()
Upvotes: 0
Views: 74
Reputation: 4620
This is simply a wrong solution to your problem. Extending another class to gain access to its inner state is a bad idea. It's always better to rely on composition instead of inheritance, but in this case you need to organise how to pass dependencies.
If you need a reference to the context (or any other type of object), pass it in the constructor. Also, if you really don't need the context, don't pass it around, it will help you prevent memory leaks as you stated.
Create a new class, called "DataManager" or something like that, and let it worry about data fetching. Create an instance of that class in your Activity, and pass the Context through constructor.
Upvotes: 1