簡體   English   中英

使用另一個類的字符串設置TextView文本

[英]Set TextView text with string from another class

我有一個Java類,我在其中存儲了如下字符串:

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

該字符串的值是使用數據庫中的值設置的,使用調試模式,我可以看到該字符串具有所需的值。

現在,我要使用java類中的此測試字符串設置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();
        }
    }
  }

提前致謝

根據提供的信息,當myString.text值為空時,您正在textView中設置文本,這就是為什么它僅設置了Empty Text,您可以在AsyncTask的onPostCreate()中設置文本,然后它將設置Text。

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

暫無
暫無

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

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