0

I worked on an Andriod App. I read some strings from DB and output them in ListView. My problem is the return string from DB worked well if I in step by step mode. If I in run mode or even if I put the breakpoint after the line which I receive the result in. The string variable will be empty.

 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]));

If I put the breakpoint in res=backgroundWorker.FinalRes;
It works well and shows the value If I put it after this line or even in the default run mode, res will be empty!

Why this happens and how can I solve it?

my Background class

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;
}

}

Eman Fateen
  • 171
  • 1
  • 1
  • 10
  • Try to debug inside the doInBackground checking first if it returns results or not,why don't you set the finalRes value in onPostExcuete? – Sayed El-Abady Aug 29 '18 at 13:55

2 Answers2

4

You have a race condition between starting the background worker, and it setting its final result.

By setting the break point, you are simply waiting long enough for the process to complete.

You just need to wait for FinalRes to be set, by some means. Without seeing the code of your BackgroundWorker class, it is impossible to say how best to do that.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243
0

Try like that :

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;

Also shown here : Android, AsyncTask, check status?

CodeKiller
  • 67
  • 1
  • 7