Lab8 Network Client reading text file over the net (Part 1)


LAB 8: Mobile Device Application  [Networking, uses-permission]


Objective: To develop application to access network data in Android mobile devices




1.    Create a new Android Project called NetworkClient with package mdad.networkdata and Activity name: NetworkClient.

Select Phone and Tablet. Click Next 
Choose Empty Activity. Click Next
Name as NetworkClient
Click Finish
2.    Create a subfolder called data in c:\wamp64 and create a config.txt file with 3 values

shown below and save it in C:\wamp64\www\data
Red: 255 Green: 255 Blue: 0

3.    Start the wampserver

      Find your IP address using windows>cmd>ipconfig

For example if your IP address is   IPv4 Address. . . . . . . . . . . : 172.30.103.238

Goto Chrome Browser type: http://172.30.103.238/data/config.txt

For those students using phone you may test it as this address:
http://mdad.atspace.cc/data/config.txt

      
   You should see this. 
         This means you are able to access the network data from a client.


4.    Goto Android Studio, edit the layout file, activity_network_client.xml. 

Components
Name
LinearLayout
customise
TextView
tvNet2
Button
btnGetConfig
Use proper naming convention (btn for Button, tv for TextView, et for EditText)


5.    Goto Android Studio, edit the java file, NetworkClient.java. 

Given the partial codes, place them in the correct sections of NetworkClient.java

private LinearLayout customise;

private TextView tvNet2;
private Button btnGetConfig;
int c1=255c2=255c3=255;

String[] 
s=new String[3];

findViews();

  

  tvNet2.setTextColor(Color.BLUE);

  tvNet2.setText("Red:"+c1+" Green:"+c2+" Blue:"+c3);

  customise.setBackgroundColor(Color.rgb(c1, c2, c3));

private void findViews() {

    customise = (LinearLayout)findViewById( R.id.customise );

    tvNet2 = (TextView)findViewById( R.id.tvNet2 );

    btnGetConfig = (Button)findViewById( R.id.btnGetConfig );

    btnGetConfig.setOnClickListener( this );

}

@Override

  public void onClick(View v) {

    if ( v == btnGetConfig ) {

        // Handle clicks for btnGetConfig

  

        tvNet2.setTextColor(Color.YELLOW);

        Log.i("Clicked =====>", c1+" "+c2+"  "+c3+" ");

        new NetworkTask().execute("http://152.226.146.33:81/data/config.txt");

    }

}


public class NetworkClient extends AppCompatActivity implements View.OnClickListener{


6.    Continue edit the java file, NetworkClient.java.
Now we will create an inner class called NetworkTask
This inner class will be enclosed by the main class public class NetworkClient

For example:

public class NetworkClient extends AppCompatActivity implements View.OnClickListener{

         @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_network_client);

     }

  

  //AsyncTask inner class needed because of StrictMode to ensure network

// tasks are on separate threads

    private class NetworkTask extends AsyncTask<String, Void, String> {

  

        protected String doInBackground(String... params) {

  

 

        }//end of doInBackground method

        protected void onPostExecute(String result) {
 


           }//end onPostExecute method

    }//end of inner class NetworkTask
 
}// end of main class NetworkClient


7.    Continue edit the java file, NetworkClient.java.


Given the partial codes, place them in the correct sections of NetworkClient.java
protected String doInBackground(String... params) {

  
    try{
  

System.out.println("NetworkTask started……"); //print to logcat for debugging

        URL url = new URL(params[0]);

        Log.i("URL =====> ", url+ "color : "+c1+" "+c2+"  "+c3);

        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) {

            s[i]=line;  i++;

        }

        c1 = Integer.parseInt(s[0]);//convert to integer

        c2 = Integer.parseInt(s[1]);

        c3 = Integer.parseInt(s[2]);

  

  

        con.disconnect();

    }

    catch(IOException e){ Log.e("error", "error in reading", e); }

    return "Red:"+s[0]+" Green:"+s[1]+" Blue:"+s[2];

}//end of doInBackground method




protected void onPostExecute(String result) {
    
tvNet2.setTextColor(Color.RED);
    
tvNet2.setText(result);
    LinearLayout layout = (LinearLayout) findViewById(R.id.
customise);
    layout.setBackgroundColor(Color.rgb(
c1c2c3));

    Log.i(
"Color =====>""Color: "+c1+" "+c2+" "+c3);
}
//end onPostExecute method

8.    Run>run app. You should this output. (something went wrong… unable to get data from network)


9.    Goto View>Tool Windows>Logcat to see the error (Or Press ALT+6)



10. You should see the Logcat view at the bottom of the screen as shown below


10-04 02:39:00.984 3803-3830/networkdata.mdad.networkclient E/error: error in reading

                                                                     java.net.SocketExceptionPermission denied

11.    This error means there is no permission granted for this app to access Internet or network data



12.    Edit AndroidManifest.xml

a.    We need read data from via the Internet so we need to set the permission.
b.    Edit AndroidManifest.xml. Add use-permission tag with android.permission.INTERNET
as shown below:
c. put this line in application tag in manifest file as shown below:



android:usesCleartextTraffic="true"

android:usesCleartextTraffic : Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".


<?xml version="1.0" encoding="utf-8"?>

  <manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="networkdata.mdad.networkclient">

    

    <uses-permission android:name="android.permission.INTERNET" />

    

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:usesCleartextTraffic="true"
        android:supportsRtl="true"         android:theme="@style/AppTheme">         <activity android:name=".NetworkClient">             <intent-filter>                 <action android:name="android.intent.action.MAIN" />                 <category android:name="android.intent.category.LAUNCHER" />             </intent-filter>         </activity>     </application> </manifest>



13.   

Run>run app.





Test it out/ Explanation of codes


No comments:

Post a Comment

Note: only a member of this blog may post a comment.