0

Good Morning! I'm trying to get HTML code from a URL using AsyncTask & inputStreamReader. Becous this work trows an Exception I used try & catch but neither of the ry or the catch is happening.

    public void click (View v){
        Tasking task = new Tasking();
        task.execute();
    }

(I made sure that my button connected to the code)

    class Tasking extends AsyncTask<Integer, Integer, String>{
        @Override
        protected String doInBackground(Integer... integers) {
            InputStream inputStream;
            InputStreamReader inputStreamReader;
            char c = ' ';
            String s = "";
            URL u;

            try{
                u = new URL("https://www.google.com/");
            inputStream = u.openConnection().getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            do{
                c = (char) inputStreamReader.read();
                s += c;
            }while(c !=-1);

            }catch (Exception e){
                e.printStackTrace();
                return "Failed";
            }
            return "?!";
        }

        @Override
        protected void onPostExecute(String s) {
            TextView textView = (TextView) findViewById(R.id.textView);
            textView.setText(s);
            super.onPostExecute(s);
        }
    }

IMG you can see in the picture that even after clicking nothing changed and i get this message:

D/NetworkSecurityConfig: No Network Security Config specified, using platform default
I/System.out: (HTTPLog)-Static: isSBSettingEnabled false
    (HTTPLog)-Static: isSBSettingEnabled false
I/zygote64: Do partial code cache collection, code=61KB, data=40KB
I/zygote64: After code cache collection, code=61KB, data=40KB
    Increasing code cache capacity to 256KB
I/zygote64: Background concurrent copying GC freed 392(31KB) AllocSpace objects, 390(13MB) LOS objects, 50% free, 10MB/20MB, paused 6.137ms total 27.526ms

Thanks in Advance!

1 Answer 1

1
do{
   c = (char) inputStreamReader.read();
   s += c;
}while(c !=-1);

This goes as infinite loop because c is never equal to -1. And for best practise you should define your UI widgets like TextView, Button onCreate in Activities-onCreateView in Fragments.

So you can use StringWriter and BufferedReader for your purpose. This is the complete code for your question.

public class MainActivity extends AppCompatActivity {

public static final String LOG_TAG = MainActivity.class.getSimpleName();
private TextView resultTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    resultTextView = findViewById(R.id.textView);
    new Tasking().execute();
}

class Tasking extends AsyncTask<Integer, Integer, String> {
    @Override
    protected String doInBackground(Integer... integers) {
        StringWriter sw = new StringWriter();
        try {
            URL url = new URL("https://www.google.com/");
            InputStream inputStream = url.openConnection().getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(inputStreamReader);
            char[] buffer = new char[1024 * 16];
            int readLength;
            while (-1 != (readLength = br.read(buffer))) {
                sw.write(buffer, 0, readLength);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "Failed";
        }
        return sw.toString();
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.v(LOG_TAG, "Response:" + s);
        resultTextView.setText(s);
    }
}

}

Finally, you should Log your response or debug your entire class. This is what professional developers do. So the more code the more happiness. Enjoy!

2
  • Thank you very much! But why is the loop is not stopping whent the last charcter is comming the read give -1 and the loop should stop
    – Mayli
    May 14, 2019 at 18:49
  • 1
    Because the result of the inputStreamReader.read() in your code will be casted char. Since -1 is the integer your variable will be not equal to -1. You shouldn't make cast in reading. You should make your casting operation s += c; line. May 14, 2019 at 19:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.