使用另一个类的字符串设置TextView文本

时间:2018-06-02 23:35:50

标签: java android android-studio

我有一个java类,我存储了一个字符串,如:

public class MyStrings
{
    public static String test = "";
}

这个字符串的值是用数据库中的值设置的,使用调试模式我可以看到该字符串具有我想要的值。

现在我想用java类中的 test 字符串设置TextView的Text。

不幸的是,这样做不起作用,TextView Text结果为空:

TextView title = (TextView) findViewById(R.id.labelTitle);
title.setText(MyStrings.test);

这是我初始化变量的函数:

@Override
protected void onPostExecute(String result)
{
    MyStrings.test = result;
}

此函数返回结果字符串:

@Override
protected String doInBackground(String... params)
{
    String action = params[0];
    String login_url = "login.php";

    if(action.equals("login"))
    {
        try
        {
            String email = params[1];
            String password = params[2];
            URL url = new URL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
            String post_data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8")+"&"
                    +URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");

            bufferedWriter.write(post_data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
            String result = "";
            String line = "";
            while((line = bufferedReader.readLine()) != null)
            {
                result += line;
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return result;
        }
        catch(MalformedURLException ex)
        {
            ex.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }
  }

提前致谢

1 个答案:

答案 0 :(得分:0)

根据您提供的信息,当myString.text值为空时,您在textView中设置文本,这就是为什么它只设置空文本, 您可以在AsyncTask的onPostCreate()中设置文本,然后设置Text。

 protected void onPostExecute(String result){
 MyStrings.test = result;  //if you want to assign then you can assign
title.setText(MyStrings.test);
}