I have my login. The user types his username and password in EditText and press onClick login button.
public void onClick(View v) {
String username = ((EditText) findViewById(R.id.typeUsername)).getText().toString();
String password = ((EditText) findViewById(R.id.typePassword)).getText().toString();
Controller handler = new Controller(getBaseContext());
if (!username.equals("") || !password.equals("")) {
//new LoginTask().execute(((EditText)findViewById(R.id.typeUsername)).getText().toString(),
// ((EditText)findViewById(R.id.typePassword)).getText().toString());
LoginTask load = new LoginTask(context);
load.execute();
} else {
Toast.makeText(getApplicationContext(), "Please fill in all fields", Toast.LENGTH_SHORT).show();
return;
}
}
Now when the login button is clicked. It executes LoginTask in the same class.
In the LoginTask when the login button is clicked a dialog should show, and in the background the user input is checked with the SQL. executeLog is a method in my DatabaseHelper it is a rawQuery to the SQL checking if username and password matches. saveLogin() is another method in my sharedpref class that saves the username and password in sharedPreference.
My issue is how can I execute? LoginTask properly in the Login class? Do i need to pass anything? What should I use in LoginTask instead of getApplicationContext
The correct way to use a Context reference in your AsyncTask is like this:
private static class ExampleTask extends AsyncTask<Void, Void, String> {
private final WeakReference<Context> contextReference;
private ExampleTask(Context context) {
this.contextReference = new WeakReference<Context>(context);
}
#Override
protected String doInBackground(Void... params) {
final Context context = this.contextReference.get();
if(context != null) {
// Inside this if you can safely use the context variable
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
final Context context = this.contextReference.get();
if(context != null) {
// Inside this if you can safely use the context variable
}
}
}
What the WeakReference does is it allows the garbage collector to destroy the Activity or Context even though your AsyncTask still has a reference to it and as such prevents the creation of memory leaks. If you want to use the Context inside your AsyncTask you need to call get() on the WeakReference like in the example above and perform a null check. If the Context you get from get() is not null you can safely use it.
Your LoginTask is declared as static class, so you don't have acces to instance of Login. Althrough you are trying to access Intent log member.
LoginTask is declared static and it has not access to the outer environment. So neither Intent log or getApplicationContext() are visible from your AsyncTask. Also notice that your AsyncTask try to access not-intialized class member. E.g Controller handler; in the AsyncTask's scope, is never intialized. When doInBackground will be executed it will cause a NPE
Related
I am getting a warning in my code that states:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
The complete warning is:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.
This is my code:
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
return null;
}
}.execute();
How do I correct this?
How to use a static inner AsyncTask class
To prevent leaks, you can make the inner class static. The problem with that, though, is that you no longer have access to the Activity's UI views or member variables. You can pass in a reference to the Context but then you run the same risk of a memory leak. (Android can't garbage collect the Activity after it closes if the AsyncTask class has a strong reference to it.) The solution is to make a weak reference to the Activity (or whatever Context you need).
public class MyActivity extends AppCompatActivity {
int mSomeMemberVariable = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start the AsyncTask, passing the Activity context
// in to a custom constructor
new MyTask(this).execute();
}
private static class MyTask extends AsyncTask<Void, Void, String> {
private WeakReference<MyActivity> activityReference;
// only retain a weak reference to the activity
MyTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(Void... params) {
// do some long running task...
return "task finished";
}
#Override
protected void onPostExecute(String result) {
// get a reference to the activity if it is still there
MyActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
// modify the activity's UI
TextView textView = activity.findViewById(R.id.textview);
textView.setText(result);
// access Activity member variables
activity.mSomeMemberVariable = 321;
}
}
}
Notes
As far as I know, this type of memory leak danger has always been true, but I only started seeing the warning in Android Studio 3.0. A lot of the main AsyncTask tutorials out there still don't deal with it (see here, here, here, and here).
You would also follow a similar procedure if your AsyncTask were a top-level class. A static inner class is basically the same as a top-level class in Java.
If you don't need the Activity itself but still want the Context (for example, to display a Toast), you can pass in a reference to the app context. In this case the AsyncTask constructor would look like this:
private WeakReference<Application> appReference;
MyTask(Application context) {
appReference = new WeakReference<>(context);
}
There are some arguments out there for ignoring this warning and just using the non-static class. After all, the AsyncTask is intended to be very short lived (a couple seconds at the longest), and it will release its reference to the Activity when it finishes anyway. See this and this.
Excellent article: How to Leak a Context: Handlers & Inner Classes
Kotlin
In Kotlin just don't include the inner keyword for the inner class. This makes it static by default.
class MyActivity : AppCompatActivity() {
internal var mSomeMemberVariable = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// start the AsyncTask, passing the Activity context
// in to a custom constructor
MyTask(this).execute()
}
private class MyTask
internal constructor(context: MyActivity) : AsyncTask<Void, Void, String>() {
private val activityReference: WeakReference<MyActivity> = WeakReference(context)
override fun doInBackground(vararg params: Void): String {
// do some long running task...
return "task finished"
}
override fun onPostExecute(result: String) {
// get a reference to the activity if it is still there
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
// modify the activity's UI
val textView = activity.findViewById(R.id.textview)
textView.setText(result)
// access Activity member variables
activity.mSomeMemberVariable = 321
}
}
}
Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.
To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.
This AsyncTask class should be static or leaks might occur because
When Activity is destroyed, AsyncTask (both static or non-static) still running
If inner class is non-static (AsyncTask) class, it will have reference to the outer class (Activity).
If a object has no references point to it, Garbage Collected will release it. If a object is unused and Garbage Collected can not release it => leak memory
=> If AsyncTask is non-static, Activity won't release event it is destroyed => leak
Solution for update UI after make AsyncTask as static class without leak
1) Use WeakReference like #Suragch answer
2) Send and remove Activity reference to (from) AsyncTask
public class NoLeakAsyncTaskActivity extends AppCompatActivity {
private ExampleAsyncTask asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// START AsyncTask
asyncTask = new ExampleAsyncTask();
asyncTask.setListener(new ExampleAsyncTask.ExampleAsyncTaskListener() {
#Override
public void onExampleAsyncTaskFinished(Integer value) {
// update UI in Activity here
}
});
asyncTask.execute();
}
#Override
protected void onDestroy() {
asyncTask.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
static class ExampleAsyncTask extends AsyncTask<Void, Void, Integer> {
private ExampleAsyncTaskListener listener;
#Override
protected Integer doInBackground(Void... voids) {
...
return null;
}
#Override
protected void onPostExecute(Integer value) {
super.onPostExecute(value);
if (listener != null) {
listener.onExampleAsyncTaskFinished(value);
}
}
public void setListener(ExampleAsyncTaskListener listener) {
this.listener = listener;
}
public interface ExampleAsyncTaskListener {
void onExampleAsyncTaskFinished(Integer value);
}
}
}
I want to use common function in multiple activity. How can I achieve this?
In my application I am displaying a Dialog box which have some data coming from some api. And this Dialog box, used in multiple activities. Right now I have implemented same Dialog box in all activities. Now I want common Dialog box for all activities. I am using this Dialog box in activity as well in adapter.
How could I do this? Using extends or using fragment.
I am already extending some class so I can not extend again( As I read, we can not extends more than one class.).
Also I want to pass some value to this function and based on return value I want to call another function.
private boolean allGroupsEdit(final String type) {
String allGroups = "allGroups";
final String url = Constants.CONSTANT_SERVER_URL + Constants.CONSTANT_GET_GROUPS_URL;
final ProgressDialog dialog = new ProgressDialog(context);
dialog.setMessage(context.getResources().getString(R.string.please_wait));
dialog.show();
StringRequest allGroupsRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
#Override
public void onResponse(String s) {
final SharedPreferences sharedPreferencesRemember = PreferenceManager.getDefaultSharedPreferences(context);
sessionGroupId = sharedPreferencesRemember.getString(Constants.CONSTANT_session_group_id, "");
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.optJSONArray(Constants.CONSTANT_data);
int a = jsonArray.length();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject schObj = jsonArray.optJSONObject(i);
schData = schObj.optJSONArray(Constants.CONSTANT_data);
}
dialog.dismiss();
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_checkbox_options);
Window window = dialog.getWindow();
window.setLayout(DrawerLayout.LayoutParams.MATCH_PARENT, DrawerLayout.LayoutParams.WRAP_CONTENT);
if(..someting){
editPublicComments(type);
}else{
editPublicPosts(type);
}
}catch(){}
}
}
Note: This a very long function so I am pasting some code for basic understand. If u need anything more detail let me know. Thanks in advance and editing and suggestions are welcome.
Edit_1: I want this whole function to be common.
Edit_2: How to return value to activity from utils ?
Edit_3: Now I created a static function in a class and I am able to call it from my activity. Now I want call another function based on common function result. (I am using SharedPreferences to store value of common function).
But in my activity where I called a common function, I doesn't execute common function first. It call another function then It call common function and after completing common method, it doesn't call another method again.
All I want to call another function based on result of common function which is true or false
boolean abab = CommonGroupBox.allGroupsEdit(context,"share", selectedPostId, localGrpArray);
if (abab){
boolean pubFlag = pref.getBoolean("isPublicFlag", false);
String qType = pref.getString("questionType","0");
if (pubFlag) {
editPublicComments(qType);
}else{
ediComments(qType);
}
else{
boolean pubFlag = pref.getBoolean("isPublicFlag", false);
String qType = pref.getString("questionType","0");
if (pubFlag) {
PublicComments(qType);
}else{
Comments(qType);
}
}
Here it doesn't call CommonGroupBox.allGroupsEdit firsts. It is called after if and else loop.
Just create a normal java class
public class Utility {
//your common method
public static void showDialog(Context context,int type){
//TODO task
}
}
Now you can use the showDialog method any where in your application
Utility.showDialog(ctx,type);
You can create an abstract class which extends AppCompatActivity, implement your method there and make all your other activities extend this class:
public abstract class BaseActivity extends AppCompatActivity {
protected boolean allGroupsEdit(final String type) {
// ...
}
// Other methods
}
Then implement your activity as :
public class MainActivity extends BaseActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
allGroupsEdit("Some type");
}
...
To create a Utility Class:
1) Create a Java file with name AppUtil which extends Activity.
2) Select a common method that you are going to use in your Application.
3) Write the function in AppUtil java file
4) Make all the function as static in your Java file so it can be easy to call inside your activity (example: AppUtil.yourMethod() )
5) Pass the context of your Activity.
Here is a simple example to check internet connection:
public class AppUtilities extends Activity {
public static boolean isInternetConnected(Context context) {
ConnectivityManager cm = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting() &&
netInfo.isAvailable();
}
}
And you can easily call this method from anywhere in your Application
example ::
AppUtilities.isInternetConnected(YourActivity.this);
I am getting a warning in my code that states:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
The complete warning is:
This AsyncTask class should be static or leaks might occur (anonymous android.os.AsyncTask)
A static field will leak contexts. Non-static inner classes have an implicit reference to their outer class. If that outer class is for example a Fragment or Activity, then this reference means that the long-running handler/loader/task will hold a reference to the activity which prevents it from getting garbage collected. Similarly, direct field references to activities and fragments from these longer running instances can cause leaks. ViewModel classes should never point to Views or non-application Contexts.
This is my code:
new AsyncTask<Void,Void,Void>(){
#Override
protected Void doInBackground(Void... params) {
runOnUiThread(new Runnable() {
#Override
public void run() {
mAdapter.notifyDataSetChanged();
}
});
return null;
}
}.execute();
How do I correct this?
How to use a static inner AsyncTask class
To prevent leaks, you can make the inner class static. The problem with that, though, is that you no longer have access to the Activity's UI views or member variables. You can pass in a reference to the Context but then you run the same risk of a memory leak. (Android can't garbage collect the Activity after it closes if the AsyncTask class has a strong reference to it.) The solution is to make a weak reference to the Activity (or whatever Context you need).
public class MyActivity extends AppCompatActivity {
int mSomeMemberVariable = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// start the AsyncTask, passing the Activity context
// in to a custom constructor
new MyTask(this).execute();
}
private static class MyTask extends AsyncTask<Void, Void, String> {
private WeakReference<MyActivity> activityReference;
// only retain a weak reference to the activity
MyTask(MyActivity context) {
activityReference = new WeakReference<>(context);
}
#Override
protected String doInBackground(Void... params) {
// do some long running task...
return "task finished";
}
#Override
protected void onPostExecute(String result) {
// get a reference to the activity if it is still there
MyActivity activity = activityReference.get();
if (activity == null || activity.isFinishing()) return;
// modify the activity's UI
TextView textView = activity.findViewById(R.id.textview);
textView.setText(result);
// access Activity member variables
activity.mSomeMemberVariable = 321;
}
}
}
Notes
As far as I know, this type of memory leak danger has always been true, but I only started seeing the warning in Android Studio 3.0. A lot of the main AsyncTask tutorials out there still don't deal with it (see here, here, here, and here).
You would also follow a similar procedure if your AsyncTask were a top-level class. A static inner class is basically the same as a top-level class in Java.
If you don't need the Activity itself but still want the Context (for example, to display a Toast), you can pass in a reference to the app context. In this case the AsyncTask constructor would look like this:
private WeakReference<Application> appReference;
MyTask(Application context) {
appReference = new WeakReference<>(context);
}
There are some arguments out there for ignoring this warning and just using the non-static class. After all, the AsyncTask is intended to be very short lived (a couple seconds at the longest), and it will release its reference to the Activity when it finishes anyway. See this and this.
Excellent article: How to Leak a Context: Handlers & Inner Classes
Kotlin
In Kotlin just don't include the inner keyword for the inner class. This makes it static by default.
class MyActivity : AppCompatActivity() {
internal var mSomeMemberVariable = 123
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// start the AsyncTask, passing the Activity context
// in to a custom constructor
MyTask(this).execute()
}
private class MyTask
internal constructor(context: MyActivity) : AsyncTask<Void, Void, String>() {
private val activityReference: WeakReference<MyActivity> = WeakReference(context)
override fun doInBackground(vararg params: Void): String {
// do some long running task...
return "task finished"
}
override fun onPostExecute(result: String) {
// get a reference to the activity if it is still there
val activity = activityReference.get()
if (activity == null || activity.isFinishing) return
// modify the activity's UI
val textView = activity.findViewById(R.id.textview)
textView.setText(result)
// access Activity member variables
activity.mSomeMemberVariable = 321
}
}
}
Non-static inner classes holds a reference to the containing class. When you declare AsyncTask as an inner class, it might live longer than the containing Activity class. This is because of the implicit reference to the containing class. This will prevent the activity from being garbage collected, hence the memory leak.
To solve your problem, either use static nested class instead of anonymous, local, and inner class or use top-level class.
This AsyncTask class should be static or leaks might occur because
When Activity is destroyed, AsyncTask (both static or non-static) still running
If inner class is non-static (AsyncTask) class, it will have reference to the outer class (Activity).
If a object has no references point to it, Garbage Collected will release it. If a object is unused and Garbage Collected can not release it => leak memory
=> If AsyncTask is non-static, Activity won't release event it is destroyed => leak
Solution for update UI after make AsyncTask as static class without leak
1) Use WeakReference like #Suragch answer
2) Send and remove Activity reference to (from) AsyncTask
public class NoLeakAsyncTaskActivity extends AppCompatActivity {
private ExampleAsyncTask asyncTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
// START AsyncTask
asyncTask = new ExampleAsyncTask();
asyncTask.setListener(new ExampleAsyncTask.ExampleAsyncTaskListener() {
#Override
public void onExampleAsyncTaskFinished(Integer value) {
// update UI in Activity here
}
});
asyncTask.execute();
}
#Override
protected void onDestroy() {
asyncTask.setListener(null); // PREVENT LEAK AFTER ACTIVITY DESTROYED
super.onDestroy();
}
static class ExampleAsyncTask extends AsyncTask<Void, Void, Integer> {
private ExampleAsyncTaskListener listener;
#Override
protected Integer doInBackground(Void... voids) {
...
return null;
}
#Override
protected void onPostExecute(Integer value) {
super.onPostExecute(value);
if (listener != null) {
listener.onExampleAsyncTaskFinished(value);
}
}
public void setListener(ExampleAsyncTaskListener listener) {
this.listener = listener;
}
public interface ExampleAsyncTaskListener {
void onExampleAsyncTaskFinished(Integer value);
}
}
}
I have this private class that is within my main activity, and I am using it pull a JSon object off of my server into my app. The code below works fine and will display the JSon object as a string.
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return httpBuild(urls[0]);
}
// onPostExecute displays the results of the AsyncTask.
#Override
protected void onPostExecute(String result) {
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(result);
}
}
what I am trying to do is place change the onPostExecute() method so it acts like webResult = result where webResult is an instance variable of the class mainActivity The problem is once I do this when I try to put the below code into the onCreate() method after HTTpAsyncTask has been called the app fails to display the object and crashes.
public class MainActivity extends Activity {
private static final String mainSite = "http://mysitehere";
private String webResult;
// private JSONArray floorsInBuilding, roomsInGender;
// private JSONObject room;
// private JSONArray arrayOfFloors;
// private JSONObject room, arrayOfRooms;
EditText etResponse;
TextView tvIsConnected;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get reference to the views
etResponse = (EditText) findViewById(R.id.etResponse);
tvIsConnected = (TextView) findViewById(R.id.tvIsConnected);
// check if you are connected or not
if(isConnected()){
tvIsConnected.setBackgroundColor(0xFF00CC00);
tvIsConnected.setText("You are conncted");
}
else{
tvIsConnected.setText("You are NOT conncted");
}
// call AsynTask to perform network operation on separate thread
new HttpAsyncTask().execute(this.buildBuildingAddress(8));
Toast.makeText(getBaseContext(), "Received!", Toast.LENGTH_LONG).show();
etResponse.setText(WebResult);
}
I'm wondering what makes the part of the code that displays the result dependent on the HttpAsyncTask. I'm also wondering how I can get the result of the HttpAsyncTask and store it as a string in the main class.
A good chunk of my code is based of of this example.
http://hmkcode.com/android-parsing-json-data/
I'm sorry If my knowledge of android isn't so great but my experience lies in more in java.
If you want to wait till the task is over so that you can override the result with webResult then you may use the asyncTask method onProgressUpdate which runs on UI thread. You may refer android developer site to know how to use that method.
The answer to this is that the asynchronous task runs alongside onCreate(). So you have to create some piece of code that waits for the task to complete or you have to manipulate the result of the async task in the onPostExecute() method
Related to my previous question about ANR problem (Android - Strings.xml versus text files. Which is faster?).
I tried using AsyncTask as advised by the respondents but i'm at a loss now.
I need to pass a string from my menu activity to an Asynctask but it's really confusing me. I've been searching and studying for 5 hours already but still cannot do it.
Here's a snippet of my code:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
/** Create an option menu from res/menu/items.xml */
getMenuInflater().inflate(R.menu.items, menu);
/** Get the action view of the menu item whose id is search */
View v = (View) menu.findItem(R.id.search).getActionView();
/** Get the edit text from the action view */
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
/** Setting an action listener */
txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
final EditText txtSearch = ( EditText ) v.findViewById(R.id.txt_search);
String enhancedStem = txtSearch.getText().toString();
TextView databaseOutput = (TextView)findViewById(R.id.textView8);
new AsyncTaskRunner().execute();
// should I put "enhancedStem" inside execute?
}
});
return super.onCreateOptionsMenu(menu);
}
Here's the Async part: UPDATED
public class AsyncTaskRunner extends AsyncTask<String, String, String> {
String curEnhancedStem;
private ProgressDialog pdia;
public AsyncTaskRunner (String enhancedStem)
{
this.curEnhancedStem = enhancedStem;
}
#Override
protected void onPreExecute() {
// Things to be done before execution of long running operation. For
// example showing ProgessDialog
super.onPreExecute();
pdia = ProgressDialog.show(secondactivity.this, "" , "Searching for words");
}
#Override
protected String doInBackground(String... params) {
if(curEnhancedStem.startsWith("a"))
{
String[] wordA = getResources().getStringArray(R.array.DictionaryA);
String delimiter = " - ";
String[] del;
TextView databaseOutput1 = (TextView)findViewById(R.id.textView8);
for (int wordActr = 0; wordActr <= wordA.length - 1; wordActr++)
{
String wordString = wordA[wordActr].toString();
del = wordString.split(delimiter);
if (curEnhancedStem.equals(del[0]))
{
databaseOutput1.setText(wordA[wordActr]);
pdia.dismiss();
break;
}
else
databaseOutput1.setText("Word not found!");
}
}
return null;
}
#Override
protected void onProgressUpdate(String... text) {
// Things to be done while execution of long running operation is in
// progress. For example updating ProgessDialog
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
}
}
Retrieval now works. I saw it display the word being looked for but it terminated suddenly.
Maybe because, like what you mentioned, UI stuff should be done on the post execute.
If that's the case, what should I return on the doInBackground() part then pass on the onPostExecute()?
(Thanks a lot guys! I'm close to making this work properly now!)
That's the problem, they are local to the method that you declared them in then you are declaring an AsyncTask class which doesn't have access to them. If the AsyncTask is an inner class of your menu activity then you can declare them as member variables.
public class MenuActivity extends Activity
{
String enhancedStem;
....
If it is a separate class then you can create a constructor in your Async class and pass the variable to the constructor.
public class AsyncTaskRunner extends AsyncTask<String, String, String> {
String curEnhancedStem;
private ProgressDialog pdia;
public void AsyncTaskRunner (String variableName)
{
this.curEnhancedStem = variableName;
}
And call it like
AsyncTaskRunner newTask = new AsyncTaskRunner(enhancedStem);
newTask.execute();
Also, you can't do UI stuff in doInBackground so this will need to be changed in the Activity class or one of your other methods in the Async class such as onPostExecute() if it is an inner class. Otherwise, you can pass a value back to your menu activity to update your TextView
Edit
You are still trying to change the UI in doInBackground() with this
TextView databaseOutput1 = (TextView)findViewById(R.id.textView8);
then again when you call setText(). This needs to be put in your onPostExecute() but then you will need to pass a reference of your TextView to the AsyncTask. You could just pass back the String that you want to set the text as from your onPostExecute() and set it in your Activity. Hope this helps
Create a constructor for your AsyncTaskRunner class.
Pass both a Context (your Activity Context) and the databaseOutput TextView as arguments to your AsyncTaskRunner class constructor.
Save references to those two objects in AsyncTaskRunner.
Pass enhancedStem to the execute() method.
Use the Context you passed to the constructor as the first argument to ProgessDialog.show()
You cannot access databaseOutput from the doInBackground() method. You must only access it in onPostExecute(), which runs on the UI thread. So, use the reference to databseOutput which you passed to the constructor to update the TextView in the onPostExecute() method accordingly.
As a note, anything you return from the doInBackground() method will be available to you as the parameters of the onPostExecute() method.
Please refer to http://developer.android.com/reference/android/os/AsyncTask.html
I would recommend you pass the required data rather than accessing it using the enclosing class - this makes your ASyncTaskRunner much more flexible, and is generally better practice.