We need to read an txt file online,
in wait time, we want to show Dialog Progress.
Declare a textView and a
progressdialog to above Override.
TextView t;
ProgressDialog mProgressDialog;
In xml file create a textView.
<TextView
android:id="@+id/te"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15sp"
android:text="@string/hello_world"
/>
Copy to below setContentView.
t = (TextView) findViewById(R.id.te);
mProgressDialog = new ProgressDialog(this);
mProgressDialog.setMessage("Loading, please wait...");
mProgressDialog.show();
Create a thread.
new Thread() {
@Override
public void run() {
String path
= "http://www.oracle.com/technetwork/java/readme-2-149793.txt";
URL u = null;
try {
u = new
URL(path);
HttpURLConnection c =
(HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream
in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
@Override
public void run() {
String a=bo.toString();
t.setText(a);
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(mProgressDialog.isShowing())
{
mProgressDialog.dismiss();
}
}
}.start();
We need internet permission, copy to
Androidmanifest.
<uses-permission android:name="android.permission.INTERNET"
/>
Run to see result.
No comments:
Post a Comment