Java代码在逐步调试模式下运行良好,而不是在默认运行模式下
我开发了一个Andriod应用程序。我从DB中读取一些字符串,并在ListView中输出它们。我的问题是,如果我使用逐步模式,DB返回的字符串工作得很好。如果我处于运行模式,或者即使我将断点放在接收结果的行之后。字符串变量将为空
BackgroundWorker backgroundWorker = new BackgroundWorker( this);
backgroundWorker.execute("Names");
res = backgroundWorker.FinalRes;
res = res.replace("[","");
res = res.replace("]","");
res = res.replace("\"","");
ParsedStringsResult = PasrString(res);
ArrayList<ListNames> NameSs= new ArrayList<ListNames>();
int size = ParsedStringsResult.length;
for ( int i=0; i<size;i++ )
NameSs.add(new ListNames(ParsedStringsResult[i]));
如果我把断点放在res=backgroundWorker.FinalRes;
它运行良好,显示了它的价值
如果我把它放在这一行之后,甚至在默认运行模式下,res将为空
为什么会发生这种情况,我如何解决
我的背景课
public class BackgroundWorker extends AsyncTask<String , Void, String> {
Context context;
public String FinalRes="";
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
if (type == "Names") {
String url_login = "http://192.168.1.2/MyApp/getNames.php";
try {
URL url = new URL(url_login);
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("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8");// +"&"+ w nkml tany
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();
FinalRes = result;
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
else
return null;
}
@Override
protected void onPreExecute(){
// alertDialog = new AlertDialog.Builder(context).create();
// alertDialog.setTitle("Login Status");
}
@Override
protected void onPostExecute(String result){
//alertDialog.setMessage(result);
//alertDialog.show();
//FinalRes = result;
}
}
# 1 楼答案
试一试:
此处还显示了: Android, AsyncTask, check status?
# 2 楼答案
在启动后台工作程序和设置其最终结果之间存在竞争条件
通过设置断点,您只需等待足够长的时间即可完成流程
您只需要通过某种方式等待
FinalRes
被设置。如果看不到BackgroundWorker
类的代码,就不可能说如何最好地做到这一点