为了账号安全,请及时绑定邮箱和手机立即绑定

Java 代码在逐步调试模式下运行良好,而不是在默认运行模式下

Java 代码在逐步调试模式下运行良好,而不是在默认运行模式下

一只萌萌小番薯 2021-08-19 17:36:02
我在一个 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;}@Overrideprotected 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();*/        } 
查看完整描述

2 回答

?
慕侠2389804

TA贡献1719条经验 获得超6个赞

您在启动后台工作程序和设置其最终结果之间存在竞争条件。

通过设置断点,您只是在等待足够长的时间来完成该过程。

您只需要FinalRes通过某种方式等待设置即可。如果没有看到你的BackgroundWorker类的代码,就不可能说如何最好地做到这一点。


查看完整回答
反对 回复 2021-08-19
?
炎炎设计

TA贡献1808条经验 获得超4个赞

像这样尝试:


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;


查看完整回答
反对 回复 2021-08-19
  • 2 回答
  • 0 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信