user3155326
user3155326

Reputation: 53

Using outer class variable in async task

I am fairly new to using AsyncTask (and Java in general) so I apologize if I this is a noob question.

I am trying to use a class string inside of an async class that is in my main class. I hope I explained that correctly.

Basically, I need the string url5 to be available in my async task. I tried placing it into the PreExecute but it doesn't recognize it. I also tried putting it directly into doInBackground. It's not letting me set the string as public static inside of the class. It's let me do it outside of the class but it still can't be recognized by the async task.

Don't know what else to try.

Here is my code:

public class NewHomepage extends Activity {

    public static String url = "http://www.mywebsite.com/android/SQL.php?username=";
    public static String usernamefromlogin;
    public static TextView errorchecking; 
    public static JSONArray user = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reshomepage);
        //get data from previous screen
          Intent intent = getIntent();
          getIntent().getExtras();

          //convert intent (intent) to string called "usernamefromlogin"         //error checking in log cat to see value of "usernamefromlogin"      
          usernamefromlogin = intent.getExtras().getString("username2");         Log.d("log usernamefromlogin", usernamefromlogin);

          //take the string "url" and add string "usernamefromlogin" after it    //error checking in log cat to see value of url5
          String url5 = url.concat(usernamefromlogin);                           Log.d("log url5", url5);

        //start asynch task
         class PostTask extends AsyncTask<String, String, String> {
               @Override
               protected void onPreExecute() {
                  super.onPreExecute();

               }//end PreExecute

               @Override
               protected String doInBackground(String... params) {
                return null;

                // Creating new JSON Parser
                JSONParser jParser = new JSONParser();

                // Getting JSON from URL
                JSONObject json = jParser.getJSONFromUrl(url5);

               }//end doInBackground

               protected void onProgressUpdate(String... values) {
                  super.onProgressUpdate(values);

               }//end onProgressUpdate

               @Override
               protected void onPostExecute(String result) {
                  super.onPostExecute(result);

               }//end onPostExecute
       }//end Async task

       //execute the Async task
       PostTask task=new PostTask();
       task.execute();

    }

    @Override
    public void onBackPressed() {
        // do nothing on back press do nothing
    }

}//end class

Upvotes: 2

Views: 3114

Answers (5)

Kanak Sony
Kanak Sony

Reputation: 1560

Change your code in this way --

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;

public class NewHomepage extends Activity {

public static String url = "http://www.mywebsite.com/android/SQL.php?username=";
public static String usernamefromlogin;
public static TextView errorchecking; 
public static JSONArray user = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.reshomepage);
    //get data from previous screen
    Intent intent = getIntent();
    getIntent().getExtras();

    //convert intent (intent) to string called "usernamefromlogin"        

    //error checking in log cat to see value of "usernamefromlogin"      
    usernamefromlogin = intent.getExtras().getString("username2");         

    Log.d("log usernamefromlogin", usernamefromlogin);

    //take the string "url" and add string "usernamefromlogin" after it   
    //error checking in log cat to see value of url5
    String url5 = url.concat(usernamefromlogin);                          
    Log.d("log url5", url5);

    //execute the Async task
    PostTask task=new PostTask();
    task.execute(url5);
}

@Override
public void onBackPressed() {
    // do nothing on back press do nothing
}

//start asynch task
class PostTask extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }//end PreExecute

    @Override
    protected String doInBackground(String... url5) {
        // Creating new JSON Parser
        JSONParser jParser = new JSONParser();
        // Getting JSON from URL
        JSONObject json = jParser.getJSONFromUrl(url5);
        return null;
    }//end doInBackground



    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);

    }//end onProgressUpdate

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
    }//end onPostExecute
}//end Async task

}//end class

Upvotes: 0

soundsofpolaris
soundsofpolaris

Reputation: 596

    //get data from previous screen
    Intent intent = getIntent();
    getIntent().getExtras();

First off, that second line of code isn't doing anything. The return from getIntent(().getExtras() is not assigned to a variable.

Second off, why does url5 need to be a public static? The AsyncTask , because it operates on a different thread, can not guarantee that the variable is there. From an OOP point of view, you should pass the URL into the AsyncTask constructor like:

    //execute the Async task
    PostTask task=new PostTask();
    task.execute(url5);

Finally, doInBackground accepts an array (params) not a String. So you need to change it to:

    @Override
    protected String doInBackground(String... params) {

    ...    

    // Getting JSON from URL
    JSONObject json = jParser.getJSONFromUrl(params[0]);

Upvotes: 0

Nathan Walters
Nathan Walters

Reputation: 4126

For starters, your syntax is wrong. The AsyncTask should be declared outside of the onCreate(...) method. Second, regarding your AsyncTask, the class provides a very easy way to pass data to it. Notice how doInBackground(...) has the parameter String... params. That means you can pass strings to it. When you call execute(...) on your task, you can pass an unlimited numbers of strings as parameters. For example,

PostTask task = new PostTask();
task.execute(url5);

Then, in doInBackground(...), use this to retrieve the argument:

String url = params[0];

Hope this helps!

Upvotes: 0

Or Bar
Or Bar

Reputation: 1566

The easiest way will be to make the url5 variable global that way it can be accessed by the AsyncTask, however the proper way of passing variables to AsyncTasks is to pass them as parametes when you call the execute command

new PostTask().execute(url5);

and in doInBackgroud use that parameter

@Override
protected String doInBackground(String... params) {
return null;

String url5 = params[0];

// Creating new JSON Parser
JSONParser jParser = new JSONParser();

// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url5);

}//end doInBackground

Upvotes: 2

amit singh
amit singh

Reputation: 1422

Either make String url5 global, or, initialize it in your async task like this-

class PostTask extends AsyncTask<String, String, String> 
{
String url5 = url.concat(usernamefromlogin); 
// your other methods
}

Upvotes: 0

Related Questions