0

This is my error message:

08-17 07:58:14.286 32620-32620/xxx.dk.xxx E/AndroidRuntime﹕ FATAL EXCEPTION: main Process: xxx.dk.xxx, PID: 32620 android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1239) at java.net.InetAddress.lookupHostByName(InetAddress.java:388) at java.net.InetAddress.getAllByNameImpl(InetAddress.java:239) at java.net.InetAddress.getAllByName(InetAddress.java:214) at com.android.okhttp.internal.Dns$1.getAllByName(Dns.java:28) at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:216) at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:122) at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:292) at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255) at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206) at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345) at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89) at xxx.dk.xxx.DAL.JsonConnection.checkSecret(JsonConnection.java:42) at xxx.dk.xxx.BLL.CheckCarrierData.checkSecret(CheckCarrierData.java:14) at xxx.dk.xxx.GUI.Login.onClick(Login.java:49) at android.view.View.performClick(View.java:4480) at android.view.View$PerformClick.run(View.java:18686) at android.os.Handler.handleCallback(Handler.java:733) at android.os.Handler.dispatchMessage(Handler.java:95) at android.os.Looper.loop(Looper.java:157) at android.app.ActivityThread.main(ActivityThread.java:5872) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:515) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) at dalvik.system.NativeStart.main(Native Method)

Im trying to use a httpGet method, which is working on API10, but it fails when im using it on an unit with 4.4.2 -> i need the support from API10 and up.

The code:

public class JsonConnection
{
private String secretJsonStr = null;
private String nameOfCarrier = "";
public String checkSecret(String secret)
{
    HttpURLConnection urlConnection = null;
    BufferedReader reader = null;



    final String QueryParam = "secret";

    try
    {
        final String httpUrl = "***SOMEURL***?";

        Uri builtUri = Uri.parse(httpUrl).buildUpon().
appendQueryParameter(QueryParam, secret.toString()).build();

        URL url = new URL(builtUri.toString());

        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setRequestMethod("GET");
        urlConnection.connect();
        // Read the input stream into a String
        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();
        if (inputStream == null)
        {
            // Nothing to do.
            return null;
        }
        reader = new BufferedReader(new InputStreamReader(inputStream));
        String line;
        while ((line = reader.readLine()) != null)
        {
            buffer.append(line + "\n");
        }
        if (buffer.length() == 0)
        {
            // Stream was empty. No point in parsing.
            return null;
        }
        secretJsonStr = buffer.toString();
    } catch (IOException e)
    {
        Log.e("Login", "Error", e);
        return null;
    } finally
    {
        if (urlConnection != null)
        {
            urlConnection.disconnect();
        }
        if (reader != null)
        {
            try
            {
                reader.close();
            } catch (final IOException e)
            {
                Log.e("Login", "Error closing stream", e);
            }
        }
    }
    try
    {
        JSONObject secretJson = new JSONObject(secretJsonStr);
        nameOfCarrier = getCarrierInfoFromJson(secretJson);

    }
    catch (JSONException e)
    {
        e.printStackTrace();
    }
    return nameOfCarrier;
}

private String getCarrierInfoFromJson(JSONObject secretJson)
        throws JSONException
{

    final String CARRIER_NAME = "Name";

    String nameOfCarrier2 = secretJson.getString(CARRIER_NAME);

    return nameOfCarrier2;


    }
}

Due to some protection, i cannot show you the URL, but everything is working like a charm when running in API 10 2.3.6 units..

I though there where complete backwards compatibility on all android devices.

Hope you have the knowledge to help me on, I for sure cannot see how. :-(

Kindest regards Rasmus

Rasmus Høy
  • 1
  • 1
  • 8
  • Forgot to mention that it jumps to the final when the urlConnection.connect() is runned - it never get into the inputstream. – Rasmus Høy Aug 17 '14 at 06:15

3 Answers3

0

The problem is that the http requests are executed on the main thread (NetworkOnMainThreadException), so you need to move the calls into a Thread. More info here.

update: actually, possible duplicate of this.

Community
  • 1
  • 1
mbmc
  • 5,024
  • 5
  • 25
  • 53
0

As error say you can't execute an HTTP connection on the MainThread that would froze the screen. which is not appropriate.

You can get that permission as the following:

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

StrictMode.setThreadPolicy(policy);

But, this is not a good practice. you must run the http connection on a background thread and display a loading msg to the user.

new Thread(new Runnable() {
            @Override
            public void run() {
                // code goes here ...
            }
        }).start();
hasan
  • 23,815
  • 10
  • 63
  • 101
0

As other answers are suggesting, you are getting this error because you are running network operation on main thread. I would suggest to use AsyncTask.

This link shows you structure of AsyncTask.

To call the AsyncTask, use

//getData() is name of class
new getData().execute();

More reference on Android Developer site.

Community
  • 1
  • 1
Paritosh
  • 2,097
  • 3
  • 30
  • 42