我开发了一个Andriod应用程序。我从数据库中读取了一些字符串,并将其输出到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;
}
}
答案 0 :(得分:4)
您在启动后台工作程序和设置其最终结果之间存在竞争条件。
通过设置断点,您只需等待足够长的时间即可完成该过程。
通过某种方式,您只需要等待FinalRes
的设置即可。没有看到您的BackgroundWorker
类的代码,就不可能说出如何做到最好。
答案 1 :(得分:0)
那样尝试:
BackgroundWorker backgroundWorker = new BackgroundWorker( this);
backgroundWorker.execute("Names");
while(backgroundWorker.getStatus() != AsyncTask.Status.FINISHED) // While the status is different from "FINISHED" you wait for the task to finished
Thread.sleep(100)
res = backgroundWorker.FinalRes;