简体   繁体   中英

How to access a public variable in the outer class from an asynctask in Java?

I'm writing an android app which should make a connection to my webserver using an httpclient in another thread. I would like to use the variables from my mainactivity class in the asynctask so the httpclient can post these to my server. When I use the public variables in my asynctask the httppostmethod posts empty values.

This is my updated code, I'm now able to retrieve the asynctask parameters but when I try to use them in my post to the server it still posts empty strings. Only if I replace the variables pHosturl, pUsername and pPassword by hardcoded strings it works and it's posted correctly.

public class MainActivity extends ActionBarActivity {
    private AlertDialog alertDialog;
    public String pHosturl;
    public String pUsername;
    public String pPassword;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AlertDialog.Builder Alertbuilder = new AlertDialog.Builder(this);
        Alertbuilder.setPositiveButton("Okay", null);
        alertDialog = Alertbuilder.create();
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        pHosturl = GetFileContentString("set1.txt");
        pPassword = GetFileContentString("set2.txt");
        pUsername = GetFileContentString("set3.txt");

        //These files are created in another part of the program and they contain a string value

    }

        public void ViewData(View v){
    HttpAsyncTask task = new HttpAsyncTask();
    task.execute(pHosturl, pUsername, pPassword);

}

private class HttpAsyncTask extends AsyncTask<String, Boolean, String> {

    @Override
    protected String doInBackground(String... params) {
        String pHosturl = params[0];
        String pUsername = params[1];
        String pPassword = params[2];
        Log.i("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);
        String Response = "";
        try {
            Log.i("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost("http://localhost/OnlineApi/GetCookie.aspx");
            List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
            nameValuePair.add(new BasicNameValuePair("sessurl", pHosturl));
            nameValuePair.add(new BasicNameValuePair("usn", pUsername));
            nameValuePair.add(new BasicNameValuePair("pass", pPassword));
            Log.i("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity responseEntity = response.getEntity();
            Response = EntityUtils.toString(responseEntity);
        } catch (Exception e) {

        }
        return Response;
    }

    @Override
    protected void onPostExecute(String s) {
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(s);
        alertDialog.show();
    }

}


        public String GetFileContentString(String FileName) {
            String RetString = "";
            try {
                InputStream in = openFileInput(FileName);

                if (in != null) {
                    InputStreamReader tmp = new InputStreamReader(in);
                    BufferedReader reader = new BufferedReader(tmp);
                    String str;
                    StringBuilder buf = new StringBuilder();

                    while ((str = reader.readLine()) != null) {
                        buf.append(str + "\n");
                    }
                    RetString = buf.toString();
                    in.close();
                }
            } catch (Exception e) {
                RetString = "";
            }
            return RetString;
        }
    }
}

Standard practice is to pass them into the params for the AsyncTask. Looks like you want something like this:

public void ViewData(View v) {
    HttpAsyncTask task = new HttpAsyncTask();

    Log.d("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);

    task.execute(pHosturl, pUsername, pPassword);


}

private class HttpAsyncTask extends AsyncTask<String, Boolean, String> {
    @Override
    protected String doInBackground(String... params) {
       String pHosturl = params[0];
       String pUsername = params[1];
       String pPassword = params[2];

       Log.d("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);


        String Response = "";
        try {
            Response = DoRequest(pHosturl, pUsername, pPassword);
        } catch (Exception e) {

        }
        return Response;
    }

    @Override
    protected void onPostExecute(String s) {
        alertDialog.setTitle("Alert");
        alertDialog.setMessage(s);
        alertDialog.show();
    }

    public String DoRequest(String pHosturl, String pUsername, String pPassword) throws Exception {

        Log.d("MyApp", "url: " + pHosturl + " username: " + pUsername + " password: " + pPassword);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://localhost/OnlineApi/ GetCookie.aspx");
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(3);
        nameValuePair.add(new BasicNameValuePair("sessurl", pHosturl));
        nameValuePair.add(new BasicNameValuePair("usn", pUsername));
        nameValuePair.add(new BasicNameValuePair("pass", pPassword));
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        String ResponseString = EntityUtils.toString(responseEntity);
        return ResponseString;
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM