Hello everyone, I started programming for Android recently. That day I suffer with the simplest code. I even decided to ask uvas for help, because I myself can not comprehend it. This program should read the contents of the file on the Internet and display it in Toast (pop-up message). For example, in the remote file it says "Hello world!" And this message is displayed in the toast when you click on the button. I tried all possible code options. When you press a button, either nothing happens or the application crashes. Help, very necessary! It is advisable to paint everything in detail so that I can figure it out =)

Here is the full code of main_activity

package com.example.byfile; import android.os.Bundle; import com.example.byfile.R; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import java.net.URL; import java.io.*; public class MainActivity extends Activity { Button btnSend; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnSend = (Button) findViewById(R.id.btnSend); btnSend.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { try { URL myURL = new URL("http://my-site.ru/file.txt"); InputStream dataStream = myURL.openConnection().getInputStream(); InputStreamReader isr = new InputStreamReader(dataStream, "UTF-8"); StringBuffer data = new StringBuffer(); int c; while ((c = isr.read()) != -1){ data.append((char) c); } String phoneNumber = new String (data.toString()); Toast toast = Toast.makeText(getApplicationContext(), phoneNumber, Toast.LENGTH_SHORT); toast.show(); } catch (IOException ie) { ie.printStackTrace(); } } }); } } 

Accordingly, in the manifesto Internet access is open.

 <uses-permission android:name="android.permission.INTERNET"/> 
  • one
    Is this a real file link? This code is working if the file is accessible from the outside (checked on its own). and by the way, close the streams. - afiki
  • No, the link is made up of course. but was checked on the working file on the site. I don’t know what is stream = ( - Rammsteinik

2 answers 2

  //метод, который получает данные по ссылке public static String executeHttpGet(String uri) throws Exception { String result = ""; try { URL url = new URL(uri); BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null) { result +=str; } in.close(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return result; } //читать данные лучше в фоновом потоке, а по завершению выводить сообщение private class ReadInBackground extends AsyncTask<Void, Void, String> { String url = ""; public ReadInBackground(String ur) { url = ur; } @Override protected String doInBackground(Void... voids) { //тут все выполняется в фоновом потоке return executeHttpGet(url); } @Override protected void onPostExecute(String params) { //тут выполняется после завершения фонового потока в основном //так же тут можно делать операции с интерфейсом, если нужно Teoast.makeText(getApplicationContext(), params,Toast.LENGTH_SHORT).show(); } } //что бы запустить фоновый поток, которые описан выше //нужно сделать следующее new ReadInBackground("ваша ссылка").execute(); 

UPD:

 new ReadInBackground("ваша ссылка").execute(); 

It's like calling some kind of method. Here an instance of the ReadInBackground class is created and the execute method is immediately called, which starts the background thread. The ReadInBackground is inherited from AsyncTask, and accordingly, in the ReadInBackground all available non-private methods that execute are. I advise you to read examples from Google. If challenge
new ReadInBackground ("your link"). execute ();
complex, you can do it differently:

  //создание объекта и вызов его метода //а это можете вставлять куда вам нужно будет ReadInBackground read = new ReadInBackground("ваша ссылка"); read.execute(); 
  • Thank. I tried to figure it out, but it didn't work out ... Here, for example, I could not figure out where to insert the new ReadInBackground ("your link"). execute (); Could you show a newbie this full activation code with "import"? This example is useful to many novice android writers, because there is no worthy example on any forum, only pieces of codes, of which I collected this code =) - Rammsteinik
  • updated his answer, tried to explain - andreich
  • I figured it out ... now I can not display the content of 2 files in 1 toast. That created a new question hashcode.ru/questions/194761 - Rammsteinik

It is impossible to climb into the main stream in the main stream!

Here is the simplest example with a good description of how to climb tyrnets in another thread .