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"/>