0

I have a aspx page that I am calling from my android app that is returning JSON text but the java code below breaks here BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

with this error.

error android.os.NetworkOnMainThreadException

ARe you able to help plesae? Thanks

default.aspx return json
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Response.ContentType = "text/plain";

        //Write the message
        Response.Write("{'testvar':'testtext'}");
        //End the response causing it to be sent
        Response.End();
    }
}

android java

   public void connectWCF() {

        try {
            URL json = new URL("http://localhost:50851/Default.aspx");

            URLConnection jc = json.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(jc.getInputStream()));

            String line = reader.readLine();

            reader.close();

        } catch(Exception e){

        }

links where I got the code ideas from http://wyousuf.wordpress.com/2012/03/01/android-with-wcf-services/ http://matijabozicevic.com/blog/android-development/android-with-wcf-service

Hello-World
  • 9,277
  • 23
  • 88
  • 154

2 Answers2

1

You are placing network communication on the main thread. You should use AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html 

here's a nice video that explains JSON Parsing using AsyncTask.

http://www.youtube.com/watch?v=qcotbMLjlA4 

For testing ONLY you can add the following in your Main Activity but it is consider bad practice.

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy); 
android_dev_
  • 412
  • 2
  • 6
1

Since android 3.0, you can't put any calls to webpages or similar external resources in the main thread (in other words, any part of the activity) unless you do it with an AsyncTask, in order to avoid apps to look "locked" and unresponsive when waiting for a response from an external datasource. Therefore, you'll need to implement the webservice call with and AsyncTask.

Example class for AsyncTask:

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;




public class cargaDatosRest extends AsyncTask<Context, Void, Void> {


    private Context c;
    private boolean resul = false;
    private String control = "";
    private String respStrS = "";

    public cargaDatosRest(Context C)
    {
        c = C;      
    }

    public String getStr()
    {
        return respStrS;
    }

    public String getControl()
    {
        return control;
    }

    @Override
    protected void onPreExecute() {     
        super.onPreExecute();
        //mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Context... params) {         

        HttpClient httpClient = new DefaultHttpClient();   

        HttpGet get = new HttpGet("url");                
        HttpResponse resp;

        get.setHeader("content-type", "application/json");

        try
        {

                        /*resp contains the response from the webService. respStr and respJSON allows to read that resp in JSON format. Just delete them if you don't need them. You can asign the values returned by the webservice to local variables in the AsyncTask class and then read them with public methods, like the resul variable.*/

                resp = httpClient.execute(getUsuarios);
            String respStr = EntityUtils.toString(resp.getEntity());

            JSONArray respJSON = new JSONArray(respStr);    

            this.resul = true;
        }
        catch(Exception ex)
        {           
            Log.e("ServicioRest","Error!", ex);
            this.resul = false;
        }           

    }           
    public boolean getResul()
    {
        return this.resul;
    }

    protected void onProgressUpdate(String... progress) {
         Log.d("ANDRO_ASYNC",progress[0]);
         //mProgressDialog.setProgress(Integer.parseInt(progress[0]));
    }

    @Override
    protected void onPostExecute(Void unused) {
        //mProgressDialog.dismiss();
    }   
}

//calling the AsyncTask from the activity:

        CargaDatosRest CallRest = new CargaDatosRest(this.getApplicationContext());
        CallRest.execute();                     
        Log.v("WebService", "Just trying "+arest.getResul());
Fco P.
  • 2,486
  • 17
  • 20