3

Ok so, here is the deal, I've coded an app that requests via HTTP (post) data from a web url, the data is returned using JSon arrays and i parse those arrays to get what i want.

Up until there there's no problem using android 2.3.x but when i test it in Android 4 it just does not work at all.

Here is my code:

public boolean testConexio(){

    boolean status = false;

    String rutaServer = "URL.php";
    //Log.e("log_tag", "Ruta server: "+rutaServer);
    InputStream is = null;
    String result = "";
    String temporal;

    //Valors a demanar/enviar
    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    nameValuePairs.add(new BasicNameValuePair("param1",config.getUserDB())); // parametros POST!
    nameValuePairs.add(new BasicNameValuePair("param2",config.getPassDB())); // parametros POST!

    //http post
    try{
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(rutaServer);
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8")); // valors POST UTF 8 coded <-- I KNOW! this is the way i need them spanishfag here
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    }catch(Exception e){
        Log.e("log_tag", "Error in http connection "+e.toString());
    }

    //Convierte la respuesta a String
    try{
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8); // again, spanishfag here
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result=sb.toString();
    }catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
    }

    //Parse la respuesta JSon
    try{
        JSONObject jArray = new JSONObject(result);
        temporal = jArray.getString("status");
        if(temporal.equals("true")){
            status = true;
        }
        Log.i("log_tag","Status: "+jArray.getString("status"));
    }catch(JSONException e){
        Log.e("log_tag", "Error parsing data "+e.toString());
    }

    return status;
}

Can anyone tell me what i'm doing wrong? or what i need to change, i've been searching for a little bit now and i can't make it work on android 4.

THANKS!

Dunnow
  • 414
  • 1
  • 5
  • 22
  • 2
    assuming that you're getting `android.os.NetworkOnMainThreadException` ... you shouldn't do internet operation on main thread ... use Threads (fx.: AsyncTask) – Selvin Apr 20 '12 at 11:54
  • As a alternative to use AsyncTask, check out the answer [here](http://stackoverflow.com/questions/8706464/defaulthttpclient-to-androidhttpclient/8706961#8706961) to see if it helps. – yorkw Apr 20 '12 at 12:20
  • @yorkw That answer is really really really bad practice, it would be 100% better to do it in an Async task. – FabianCook Apr 20 '12 at 12:28
  • @SmartLemon, exactly, as I mentioned in my answer in the end. Also note that the really really bad practice you talking about is existed and allowed for long time until API level 11. – yorkw Apr 20 '12 at 13:02

2 Answers2

7

You need to put this in an Async task, it will not run in the main thread in 3.0 >

use this:

public class PostTask extends AsyncTask<Void, String, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean result = false;

            //All your code goes in here 

            //If you want to do something on the UI use progress update

            publishProgress("progress");
            return result;
        }

        protected void onProgressUpdate(String... progress) {
            StringBuilder str = new StringBuilder();
                for (int i = 1; i < progress.length; i++) {
                    str.append(progress[i] + " ");
                }

        }
    }

You need a reference to it outside the async task

PostTask posttask;

then you need to start it

posttask = new PostTask();
posttask.execute();

I had the exact same problem a couple of days ago, goodluck

FabianCook
  • 20,269
  • 16
  • 67
  • 115
1

With Android 4.0 you cant use http connection without using a Thread (with a runnable, asyinctask ... )

The best you can do is implements a Thread but if you cant do it you cant delete in the android manifest android:targetVersion="14".

If you need some elements of the version 14/higher like Holo theme or something you can configure in

Right clink in the project --> Propierties --> Android --> Project Built Target = 14 or that you want

Aracem
  • 7,227
  • 4
  • 35
  • 72
  • 2
    This wouldn't be a very good idea, the reason they have done this is that when you do any networking requests it can block the main UI thread which can cause a FC, we dont want that happening so we need to do it in a thread, they let it slide because it didn't seem like developers would do that I think. – FabianCook Apr 20 '12 at 12:04
  • I know but i mark the best to do is implement a thread but there are some times that is imposible to do it for some reason and this is a momentary solution. The best, i repit, is implement a AsyncTask to make HTTP petitions Allways how you say. I vote up you answer but i think is good put thit "bad" solution too. – Aracem Apr 20 '12 at 12:07
  • @Aracem you can also disable strict mode .... but is really, really, really, ..., really bad practice – Selvin Apr 20 '12 at 12:07
  • 1
    I know @Selvin but, how i say before, perhaps help somebody in some situation. Repit, the best is SmartLemon solution! – Aracem Apr 20 '12 at 12:11