有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓如何从Java中的asynctask访问外部类中的公共变量?

我正在编写一个安卓应用程序,它应该在另一个线程中使用httpclient连接到我的Web服务器。我想在asynctask中使用mainactivity类中的变量,以便httpclient可以将这些变量发布到我的服务器。当我在asynctask中使用公共变量时,httppostmethod会发布空值

这是我的更新代码,我现在可以检索asynctask参数,但当我尝试在向服务器发布的帖子中使用它们时,它仍然会发布空字符串。只有当我用硬编码字符串替换变量phostur、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;
        }
    }
}

共 (1) 个答案

  1. # 1 楼答案

    标准做法是将它们传递到异步任务的参数中。 看起来你想要这样的东西:

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