#1 Create an About.txt
and save it in the C:\wamp64\www\data folder of the WampServer.
Networking
Activity
Version: 2.01
Author: Your Name
An Android
Program to illustrate networking capabilities of Android
Copyright of TP
|
Create a Menu folder
Right-clicked on res folder> New> Folder> Res folder
#3 Create a Menu resource file menu_main.xml
menu_main.xml
Type the followings in the xml file<?xml version="1.0" encoding="utf-8"?><menu xmlns:android="http://schemas.android.com/apk/res/android"> <item android:id="@+id/item1" android:title="About Us"/> </menu>
#4 Add this method in MainActivity.java
@Overridepublic boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id){ case R.id.item1: Toast.makeText(getApplicationContext(),"About Us Selected",Toast.LENGTH_LONG).show(); // Intent i = new Intent(getApplicationContext(), AboutActivity.class); // startActivity(i); return true; default: return super.onOptionsItemSelected(item); } }
#5 Create a new Activity called AboutActivity.java
Given the partial codes, place them in the correct sections of AboutActivity.java
TextView tvAbout;
tvAbout = (TextView)findViewById( R.id.txtAbout ); new NetworkTask().execute("http://172.30.103.238:81/data/About.txt");
//AsyncTask inner class needed because of StrictMode to ensure network // tasks are on separate threads private class NetworkTask extends AsyncTask<String, Void, String> { String testMsg=""; protected String doInBackground(String... params) { try{ System.out.println("NetworkTask started……"); //print to logcat for debugging URL url = new URL(params[0]); HttpURLConnection con = (HttpURLConnection)url.openConnection(); con.setRequestProperty("Accept", "text/plain"); BufferedReader br =new BufferedReader(new InputStreamReader(con.getInputStream())); String line; int i=0; //read values from config.txt in the server over the network while((line=br.readLine())!=null) { testMsg+=line+"\n"; } con.disconnect(); } catch(IOException e){ Log.e("error", "error in reading", e); } return testMsg; }//end of doInBackground method protected void onPostExecute(String result) { tvAbout.setText(result); }//end onPostExecute method }//end of inner class NetworkTask
For Part 2 you may also use the about.txt from atspace.com too.
// new AboutTask().execute("http://10.0.2.2:8080/MDAD/html/about.txt");
new AboutTask().execute("http://mdad.atspace.cc/data/About.txt");
For those students using phone you may test it as this address:
http://mdad.atspace.cc/data/About.txt
No comments:
Post a Comment
Note: only a member of this blog may post a comment.