我有一个java类,我在其中存储了一个字符串,例如:
public class MyStrings
{
public static String test = "";
}
该字符串的值是使用数据库中的值设置的,使用 Debug模式我可以看到该字符串具有我想要的值。
现在我想使用 java 类中的这个 test 字符串设置 TextView 的文本。
不幸的是,这样做不起作用,并且 TextView 文本结果为空:
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 中设置文本,这就是它仅设置空文本的原因, 您可以在 AsyncTask 的 onPostCreate() 中设置文本,然后它会设置文本。
protected void onPostExecute(String result){
MyStrings.test = result; //if you want to assign then you can assign
title.setText(MyStrings.test);
}
关于java - 使用另一个类中的字符串设置 TextView 文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50662074/