-3

I wanna to write an app that need to recive some text from server this is my code :

String db = ""
new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    // Create a URL for the desired page
                    URL url = new URL("http://chemvaaj.xzn.ir/test/words.txt");

                    // Read all the text returned by the server
                    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
                    String str;
                    while ((str = in.readLine()) != null) {
                        // str is one line of text; readLine() strips the newline character(s)
                        db+=str;
                    }
                    in.close();
                } catch (MalformedURLException e) {
                } catch (IOException e) {
                }

            }
        }).start();

        searchEditText.setText(dbd);

it seems right but the variable db is stil "" in the end .

Erfan Bagheri
  • 638
  • 1
  • 8
  • 16

1 Answers1

2

Try below code:

Hope that will solve your problem.

Note : Firstly you must do networking operation in another thread because networking in main thread makes your application unresponsive for duration of any request. So put this code in AsyncTask.

DefaultHttpClient  httpclient = new DefaultHttpClient();

HttpGet httppost = new HttpGet("http://chemvaaj.xzn.ir/test/words.txt");
HttpResponse response = httpclient.execute(httppost);
        HttpEntity ht = response.getEntity();

        BufferedHttpEntity buf = new BufferedHttpEntity(ht);

        InputStream is = buf.getContent();


        BufferedReader r = new BufferedReader(new InputStreamReader(is));

        StringBuilder text = new StringBuilder();
        String data;
        while ((data= r.readLine()) != null) {
            text .append(line + "\n");
        }

        searchEditText.setText(text );
Community
  • 1
  • 1
KishuDroid
  • 5,411
  • 4
  • 30
  • 47