-7

The code in doInBackgroung works perfectly in java but on android it just won't work. The output is nothing not even the table. Using Android Studio. The complete code is here for the android app.

Now the app fires up an AsyncTask to connect to a server, the server just (PHP) echoes a few strings when done in java separately the strings are caught perfectly by the HttpURLConnection. However, in Android the same code (the one in doInbackbround() method of DownloadFilesTask) won't reproduce the same effect.

I have tried to catch any exceptions that might occur but there is no exception being thrown. The code is pretty self explanatory for anyone who actually knows Android development.

About the debugging, well the function showdata() does get called but the parameter string seems to be empty. I have added more comments in code to describe the problem a bit better.

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MyActivity";

    void showData(String s){ //gets called with an empty string
        TextView t = (TextView) findViewById(R.id.textView);
        t.setText(s);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        try {
            setContentView(R.layout.activity_main);

           // initAttendanceTable();
            DownloadFilesTask task = new DownloadFilesTask();

            task.execute();
            initAttendanceTable();//just generates a tableRow and add it to a Table Row

           // nothing fancy here but it actually is'nt doing anything after adding aynstask code
        }
        catch(Exception e) {
            TextView t = (TextView) findViewById(R.id.textView);
            t.setText(e.getLocalizedMessage()+"error");
        }
    }
    private class DownloadFilesTask extends AsyncTask<Void,Void, String> {

        protected String doInBackground(Void ...p) {

            String results = new String("");
            String temp = new String("");
            try {
                URL homeUrl = new URL("http://10.0.2.2:80/attendance/attendance_android.html");
                //returns a few names ending with a null at the end


                HttpURLConnection httpConn = (HttpURLConnection) homeUrl.openConnection();
                BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream()));
                if(br.ready()) {
                    results = br.readLine();
                    while(results!=null) {
                        results=br.readLine();
                        if(results!=null){
                            temp= temp + results;
                        }
                    }
                }
            }
            catch(Exception e){
                return null;
            }
            return temp;
        }

        //public ProgressDialog mProgressDialog;
        protected void onProgressUpdate(Void ...progress) {
super.onProgressUpdate(progress);

            //ProgressDialog.show(MainActivity.this, "loading", "wait...", true, true);

        }

        protected void onPostExecute(String result) {

            super.onPostExecute(result);
            if(result==null){ // to ctach error from doInbackground
                Toast.makeText(getApplicationContext(), (String)result,
                        Toast.LENGTH_LONG).show();
            }
            showData(result);
        }
    }

    private void initAttendanceTable() {
        try{
            TextView t=(TextView) findViewById(R.id.textView);

            TableLayout attendanceTable = (TableLayout) findViewById(R.id.attendanceTable);
            for (int j = 0; j < 3; j++) {
                TableRow tbRow = new TableRow(this);
                tbRow.setId(j);
                tbRow.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.MATCH_PARENT));
                tbRow.setGravity(View.FOCUS_LEFT);
                tbRow.setPadding(1, 1, 1, 1);
                for (int i = 0; i < 3; i++) {
                    TextView tbRowText = new TextView(this);
                    tbRowText.setLayoutParams(new TableRow.LayoutParams(0, TableRow.LayoutParams.WRAP_CONTENT, 0.33f));
            //        tbRowText.setText(br.readLine());
                    tbRow.addView(tbRowText);
                }
                attendanceTable.addView(tbRow);
            }
        }
        catch(Exception e){
            TextView t=(TextView) findViewById(R.id.textView);
            t.setText(e.getLocalizedMessage());
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Ankush soni
  • 1,439
  • 1
  • 15
  • 30
rahul tyagi
  • 643
  • 1
  • 7
  • 20
  • 1
    Did you have connection to the server? Log error in `catch ` statement. – dieter_h Aug 31 '15 at 17:50
  • well no error being caught in catch and the code works perfectly in java its just the async task complicate things and i have permission set in manifest file and why the downvotes ?? – rahul tyagi Aug 31 '15 at 18:03
  • and how is this question off-topic ? a lot arrogant peeps here – rahul tyagi Aug 31 '15 at 18:04
  • 1
    Can you describe what you found out when the code was executed in the debugger? Where does the execution deviate from your expectation? Dropping a bunch of code and only giving a very vague problem description is a waste of time for everybody. – Henry Aug 31 '15 at 18:10
  • as i said there is nothing in the output i will update the question a lil – rahul tyagi Aug 31 '15 at 18:11
  • Where is the showData() and TableRow codes? – Want2bExpert Aug 31 '15 at 18:12
  • showdata is at the top of mainactiviy class and what TableRow code ? – rahul tyagi Aug 31 '15 at 18:19
  • 1
    add trace statements to your code and trace its execution. when you say its "not working", well that doesn't mean a lot without additional detail. does `showData` get run? what value is passed to it? is `onPostExecute` receiving an empty string? you are getting downvotes because this question is light on the details needed to solve it. ... btw, I notice you are executing `initAttendanceTable();` twice, once before kicking off the AsyncTask, and again immediately afterwards... – trooper Aug 31 '15 at 18:57
  • @trooper the init call does not cause any error – rahul tyagi Aug 31 '15 at 19:35
  • gonna start a bounty – rahul tyagi Sep 01 '15 at 16:00

3 Answers3

4

well the line

  if(br.ready())

was causing the problems removing this check corrects everything.

rahul tyagi
  • 643
  • 1
  • 7
  • 20
  • In addition you should use a StringBuilder for temp and reduce your Loop to while((results = br.readLine()) != null) {temp.append(results);} – Udo Sep 09 '15 at 15:59
1
if(br.ready()) {
    results = br.readLine();

    while(results!=null) {

        results=br.readLine();
        if(results!=null){
            temp = temp + results;
        }
    }
}

change this to:

if(br.ready()) {
    results = br.readLine();

    while(results!=null) {
        temp= temp + results;
        results=br.readLine();                        
    }
}

As while(results!=null) { results=br.readLine(); ... // this is your 2nd time to execute readLine, and for the 2nd time, you may read empty string, because your server code just echo a few words.

Jared Rummler
  • 37,824
  • 19
  • 133
  • 148
LiuWenbin_NO.
  • 1,216
  • 1
  • 16
  • 25
1

Try

task.executeOnExecutor(Executors.newScheduledThreadPool(1));

instead of

task.execute();

Other tasks might not have been executed completely.

Nagama Inamdar
  • 2,851
  • 22
  • 39
  • 48
mikchen
  • 11
  • 3