0

I am a newbie on android development and i am having this error message while testing to send an sms over http connection and get a return string. below is the http api:

http://server:port/CreditCheck/checkcredits?username=xxxxx&password=xxxx

I get java.io.ioexception, i dont know how to track further and it is really giving me headache.

public class Sender {
    // Username that is to be used for submission
    String username;
    // password that is to be used along with username
    String password;
    // Message content that is to be transmitted
    String message;
    /**
    * What type of the message that is to be sent
    * <ul>
    * <li>0:means plain text</li>
    * <li>1:means flash</li>
    * <li>2:means Unicode (Message content should be in Hex)</li>
    * <li>6:means Unicode Flash (Message content should be in Hex)</li>
    * </ul>
    */
    String type;
    /**
    * Require DLR or not
    * <ul>
    * <li>0:means DLR is not Required</li>
    * <li>1:means DLR is Required</li>
    * </ul>
    */
    String dlr;
    /**
    * Destinations to which message is to be sent For submitting more than one
    * destination at once destinations should be comma separated Like
    * 91999000123,91999000124
    */
    String destination;
    // Sender Id to be used for submitting the message
    String source;
    // To what server you need to connect to for submission
    String server;
    // Port that is to be used like 8080 or 8000
    int port;
    // urlParts is the excessive part of the URL
    //String urlParts;

    public Sender(String server, int port, String username, String password, 
            String message, String dlr, String type, String destination, String source) {

        this.username = username;
        this.password = password;
        this.message = message;
        this.dlr = dlr;
        this.type = type;
        this.destination = destination;
        this.source = source;
        this.server = server;
        this.port = port;

    }


    public String checkBalance() {
        try {

            // Url that will be called to submit the message
            URL sendUrl = new URL("http://" + this.server + ":" + this.port
            + "/CreditCheck/checkcredits");
            HttpURLConnection httpConnection = (HttpURLConnection) sendUrl
            .openConnection();
            // This method sets the method type to POST so that
            // will be send as a POST request
            httpConnection.setRequestMethod("POST");
            // This method is set as true wince we intend to send
            // input to the server
            httpConnection.setDoInput(true);
            // This method implies that we intend to receive data from server.
            httpConnection.setDoOutput(true);
            // Implies do not use cached data
            httpConnection.setUseCaches(false);

            // Data that will be sent over the stream to the server.
            DataOutputStream dataStreamToServer = new DataOutputStream(
            httpConnection.getOutputStream());
            dataStreamToServer.writeBytes("username="
            + URLEncoder.encode(this.username, "UTF-8") + "&password="
            + URLEncoder.encode(this.password, "UTF-8"));

            dataStreamToServer.flush();
            dataStreamToServer.close();
            // Here take the output value of the server.
            BufferedReader dataStreamFromUrl = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String dataFromUrl = "", dataBuffer = "";
            // Writing information from the stream to the buffer
            while ((dataBuffer = dataStreamFromUrl.readLine()) != null) {
                dataFromUrl += dataBuffer;
            }
            /**
            * Now dataFromUrl variable contains the Response received from the
            * server so we can parse the response and process it accordingly.
            */
            dataStreamFromUrl.close();
            //System.out.println("Response: " + dataFromUrl);
            return dataFromUrl;
        } catch (IOException ex) {

            ex.printStackTrace();
            return ex.toString();
        }catch(Exception ex){
            ex.printStackTrace();
            return ex.toString();
        }
    }

    public String submitMessage() {
        try {
            // Url that will be called to submit the message
            URL sendUrl = new URL("http://" + this.server + ":" + this.port + "/bulksms/bulksms");
            HttpURLConnection httpConnection = (HttpURLConnection) sendUrl.openConnection();

            // This method sets the method type to POST so that
            // will be send as a POST request
            httpConnection.setRequestMethod("GET");
            // This method is set as true wince we intend to send
            // input to the server
            httpConnection.setDoInput(true);
            // This method implies that we intend to receive data from server.
            httpConnection.setDoOutput(true);
            // Implies do not use cached data
            httpConnection.setUseCaches(false);

            // Data that will be sent over the stream to the server.
            DataOutputStream dataStreamToServer = new DataOutputStream(httpConnection.getOutputStream());
            dataStreamToServer.writeBytes("username="
            + URLEncoder.encode(this.username, "UTF-8") + "&password="
            + URLEncoder.encode(this.password, "UTF-8") + "&type="
            + URLEncoder.encode(this.type, "UTF-8") + "&dlr="
            + URLEncoder.encode(this.dlr, "UTF-8") + "&destination="
            + URLEncoder.encode(this.destination, "UTF-8") + "&source="
            + URLEncoder.encode(this.source, "UTF-8") + "&message="
            + URLEncoder.encode(this.message, "UTF-8"));

            dataStreamToServer.flush();
            dataStreamToServer.close();

            // Here take the output value of the server.
            BufferedReader dataStreamFromUrl = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
            String dataFromUrl = "";
            String dataBuffer = "";

            // Writing information from the stream to the buffer
            while ((dataBuffer = dataStreamFromUrl.readLine()) != null) {
                dataFromUrl += dataBuffer;
            }
            /**
            * Now dataFromUrl variable contains the Response received from the
            * server so we can parse the response and process it accordingly.
            */
            dataStreamFromUrl.close();
            //System.out.println("Response: " + dataFromUrl);
            return dataFromUrl;

        } catch (IOException ex) {
            //ex.printStackTrace();
            return ex.toString();
        }catch(Exception ex){
            return ex.toString();
        }
    }

Below is my calling script for the button onClicklistener

public void onClick(View v) {
        Sender s = new Sender("server", port, "username", "password", "test for unicode", "1", "0", "23481111111", "Update");
        switch(v.getId()){
            case R.id.btnSaveSettings:
                Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();
                break;
            case R.id.btnBalance:
                Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show();

                break;
            default:
                Toast.makeText(getActivity(), "No button Captured", Toast.LENGTH_SHORT).show();

        }
}

Please help me out on what I am doing wrong!

@Angad I have edited the code and below is what it looks like and the error i am getting.

My Calling method

public String checkBalance() {
    try {
        HttpClient client=new DefaultHttpClient();

        HttpPost request=new HttpPost("http://" + this.server + ":" + this.port + "/CreditCheck/checkcredits");

        BasicNameValuePair username=new BasicNameValuePair("username", this.username);
        BasicNameValuePair password=new BasicNameValuePair("password", this.password);

        List<NameValuePair> list=new ArrayList<NameValuePair>();
        list.add(username);
        list.add(password);

        UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list);
        request.setEntity(urlentity);

        HttpResponse response=client.execute(request);

        HttpEntity entity=response.getEntity();
        String tmp=EntityUtils.toString(entity);
        return tmp;

    }catch(Exception ex){
        ex.printStackTrace();
        return ex.toString();
    }
}

My Onclick action implementing method checkBalance()

public void onClick(View v) {
    Sender s = new Sender("111.211.211.111", 8080, "user",
            "pass", "test for unicode", "1", "0", "234811111111", "Update");
    // TODO Auto-generated method stub
    switch(v.getId()){
        case R.id.btnSaveSettings:
            //this.savePreferences();
            Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show();
            break;
        case R.id.btnBalance:

            Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show();

            break;
        default:
            Toast.makeText(getActivity(), "No button Captured", Toast.LENGTH_SHORT).show();

    }

My Manifest file

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="19" />
    <uses-permission android:name="android.permission.READ_CONTACTS" />
    <uses-permission android:name="android.permission.INTERNET" />
<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>


</manifest>

Exception error Android.os.NetworkOnMainThreadException

Error message logcat including StackTrace()

10-19 14:22:20.285: E/SoundPool(1273): error loading /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: E/SoundPool(1273): error loading /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: E/SoundPool(1273): error loading /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: E/SoundPool(1273): error loading /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.285: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.295: E/SoundPool(1273): error loading /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.295: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/Effect_Tick.ogg 10-19 14:22:20.305: E/SoundPool(1273): error loading /system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/KeypressStandard.ogg 10-19 14:22:20.305: E/SoundPool(1273): error loading /system/media/audio/ui/KeypressSpacebar.ogg 10-19 14:22:20.315: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/KeypressSpacebar.ogg 10-19 14:22:20.315: E/SoundPool(1273): error loading /system/media/audio/ui/KeypressDelete.ogg 10-19 14:22:20.315: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/KeypressDelete.ogg 10-19 14:22:20.325: W/System.err(1854): android.os.NetworkOnMainThreadException 10-19 14:22:20.325: E/SoundPool(1273): error loading /system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/KeypressReturn.ogg 10-19 14:22:20.325: E/SoundPool(1273): error loading /system/media/audio/ui/KeypressInvalid.ogg 10-19 14:22:20.325: W/AudioService(1273): Soundpool could not load file: /system/media/audio/ui/KeypressInvalid.ogg 10-19 14:22:20.335: W/AudioService(1273): onLoadSoundEffects(), Error -1 while loading samples 10-19 14:22:20.335: W/System.err(1854): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145) 10-19 14:22:20.335: W/System.err(1854): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84) 10-19 14:22:20.335: W/System.err(1854): at libcore.io.IoBridge.connectErrno(IoBridge.java:127) 10-19 14:22:20.335: W/System.err(1854): at libcore.io.IoBridge.connect(IoBridge.java:112) 10-19 14:22:20.345: W/System.err(1854): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192) 10-19 14:22:20.345: W/System.err(1854): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459) 10-19 14:22:20.345: W/System.err(1854): at java.net.Socket.connect(Socket.java:843) 10-19 14:22:20.345: W/System.err(1854): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119) 10-19 14:22:20.345: W/System.err(1854): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144) 10-19 14:22:20.355: W/System.err(1854): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 10-19 14:22:20.355: W/System.err(1854): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119) 10-19 14:22:20.355: W/System.err(1854): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 10-19 14:22:20.355: W/System.err(1854): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555) 10-19 14:22:20.365: W/System.err(1854): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 10-19 14:22:20.365: W/System.err(1854): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465) 10-19 14:22:20.375: W/System.err(1854): at com.example.sleeksmsmobile.Sender.checkBalance(Sender.java:96) 10-19 14:22:20.375: W/System.err(1854): at com.example.sleeksmsmobile.SettingsTab.onClick(SettingsTab.java:86) 10-19 14:22:20.375: W/System.err(1854): at android.view.View.performClick(View.java:4438) 10-19 14:22:20.385: W/System.err(1854): at android.view.View$PerformClick.run(View.java:18422) 10-19 14:22:20.385: W/System.err(1854): at android.os.Handler.handleCallback(Handler.java:733) 10-19 14:22:20.385: W/System.err(1854): at android.os.Handler.dispatchMessage(Handler.java:95) 10-19 14:22:20.385: W/System.err(1854): at android.os.Looper.loop(Looper.java:136) 10-19 14:22:20.395: W/System.err(1854): at android.app.ActivityThread.main(ActivityThread.java:5017) 10-19 14:22:20.395: W/System.err(1854): at java.lang.reflect.Method.invokeNative(Native Method) 10-19 14:22:20.395: W/System.err(1854): at java.lang.reflect.Method.invoke(Method.java:515) 10-19 14:22:20.405: W/System.err(1854): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779) 10-19 14:22:20.405: W/System.err(1854): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 10-19 14:22:20.415: W/System.err(1854): at dalvik.system.NativeStart.main(Native Method) 10-19 14:22:20.925: I/Choreographer(1273): Skipped 36 frames! The application may be doing too much work on its main thread.

ID man
  • 21
  • 5
  • 2
    can you provide the complete error message from ex.printStackTrace() ? – Arne Poths Oct 18 '14 at 11:38
  • 1
    ioexception at which line ? also tell me the line statement...' – Angad Tiwari Oct 18 '14 at 11:43
  • @angad tiwari ioexception comes during onclick operation, within the Toast.maketext operation on calling submitmessage and checkbalance Toast.makeText(getActivity(), s.checkBalance().toString(), Toast.LENGTH_SHORT).show(); Toast.makeText(getActivity(), s.submitMessage().toString(), Toast.LENGTH_SHORT).show(); – ID man Oct 18 '14 at 13:57
  • @ArnePoths i am having to test from my android device because i dont know how to get internet on my emulator so how can i implement a printStackTrace() or i cast it to string so i can display it on Toast.makeText() – ID man Oct 18 '14 at 14:05
  • The stacktrace will appear in the logcat output, no need for Toast – mjn Oct 18 '14 at 15:04
  • @mjn I cant test on my AVD because i need an internet device to test the reason i cant use 'ex.printStackTrace()'. How do i enable internet on my AVD so i can test without physical internet enabled device? every one's response is well appreciated as i am just newbie – ID man Oct 18 '14 at 15:24
  • pc/laptop(on which u're running your avd) is connected to internet...then avd will share that connection and then has access to internet... – Angad Tiwari Oct 18 '14 at 15:45
  • @AngadTiwari i am using a laptop connecting to a mobile hotspot wireless internet. it is not connecting to internet i have tested it for internet but no connection i guess i am not doing something right. thank you – ID man Oct 18 '14 at 15:57
  • does your app the INTERNET permission? and if your device or AVD would connect to INTERNET..then how could you test exception..also it seems that "dataStreamToServer.writeBytes" or "dataStreamFromurl" is throwing exception.....plz try the method i posted in the answer section... – Angad Tiwari Oct 18 '14 at 16:04
  • @Angad Tiwari i am using my android fone to test since i cant get internet on my avd – ID man Oct 19 '14 at 18:33
  • Ok can you provide me the service detail..such as url..method type..content type...request format..response format...i ll like to do by myself to understand actual problem – Angad Tiwari Oct 19 '14 at 19:37

4 Answers4

0

In Android, you have to run network operations on a separate thread from the user interface. Otherwise, the act of sending the HTTP request causes the interface to freeze.

Android documentation

mattm
  • 5,851
  • 11
  • 47
  • 77
  • my device does not freeze and everything seems to work fine but the error message just comes up when executing the the submitMessage and checkBalance. thank you – ID man Oct 18 '14 at 14:01
0

Your code has a contradiction between the comment and the actual coding:

        // This method sets the method type to POST so that
        // will be send as a POST request
        httpConnection.setRequestMethod("GET");

and then continues with setting both setDoInput and setDoOutput to true:

        // This method is set as true wince we intend to send
        // input to the server
        httpConnection.setDoInput(true);
        // This method implies that we intend to receive data from server.
        httpConnection.setDoOutput(true);

The setDoOutput(true) implicitly set the request method to POST because that's the default method whenever you want to send a request body. (see HttpURLConnection sends a POST request even though httpCon.setRequestMethod("GET"); is set). This might cause an error.

For further research please indicate the error location (source line).

Community
  • 1
  • 1
mjn
  • 36,362
  • 28
  • 176
  • 378
  • many thanks i had to change the request method during troubleshooting, i will change back to POST however the error persisted. The error location is this Toast.makeText(getActivity(), **s.submitMessage()**.toString(), Toast.LENGTH_SHORT).show(); or Toast.makeText(getActivity(), **s.checkBalance()**.toString(), Toast.LENGTH_SHORT).show(); – ID man Oct 18 '14 at 14:08
0

I am glad to inform every one who showed concern to my problem that it has been fixed.

My code works fine and the Angad Tiwari's works and much simpler.

After i was able to get internet on my avd then i could use the printStackTrace() error report to find cause which was the Strict mode policy

the fix was for me to put this code below in the mainActivity class;

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

I appreciate you all.....:)

ID man
  • 21
  • 5
-1

rather using httpconnection i would suggest you to use httpclient like

          try
            {
                HttpClient client=new DefaultHttpClient();
                HttpPost request=new HttpPost("your url");

                BasicNameValuePair email=new BasicNameValuePair("username", "your username");
                BasicNameValuePair password=new BasicNameValuePair("password", "your password");

                List<NameValuePair> list=new ArrayList<NameValuePair>();
                list.add(username);
                list.add(password);

                UrlEncodedFormEntity urlentity=new UrlEncodedFormEntity(list);
                request.setEntity(urlentity);

                HttpResponse response=client.execute(request);

                HttpEntity entity=response.getEntity();
                String tmp=EntityUtils.toString(entity);
                return tmp;
            }
            catch(Exception e)
            {
                return e.toString();
            }

try yourcode with this...and tell me ...i'll surelly work...and its also quite simple...there its all meshup with stream and all.. hope this will help... ;-)

Angad Tiwari
  • 1,738
  • 1
  • 12
  • 23
  • i have implemented the code please read above in my question the code and the error message including the printStackTrace(). Please just help me out! – ID man Oct 19 '14 at 18:35
  • Other than this.u can also first check the response on browser..using ADVANCE REST CLIENT chrome extension...hence ull known..where the problem is. – Angad Tiwari Oct 19 '14 at 20:12
  • the problem is fixed please read through my answer. i am glad with guys :) – ID man Oct 19 '14 at 20:34