簡體   English   中英

如何從Java中的asynctask訪問外部類中的公共變量?

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

我正在編寫一個android應用程序,該應用程序應使用另一個線程中的httpclient來連接到我的網絡服務器。 我想在asynctask中使用mainactivity類中的變量,以便httpclient可以將這些變量發布到我的服務器上。 當我在asynctask中使用公共變量時,httppostmethod將發布空值。

這是我更新的代碼,現在我可以檢索asynctask參數,但是當我嘗試在服務器中使用它們時,它仍然會發布空字符串。 僅當我用硬編碼字符串替換變量pHosturl,pUsername和pPassword時,它才有效,並且已正確發布。

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;
        }
    }
}

標准做法是將它們傳遞給AsyncTask的參數。 看起來您想要這樣的東西:

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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM