httpclient (phpmyadmin) not working on Android 4.0

2020-05-03 08:38发布

问题:

I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+ it can't connect to database somehow. I saw some posts about you need to get it in a asynch class. I also tried that, but I can't seems it to work. I probably use it wrong, but it is hard for me to understand.

 public class connector extends Activity {
    /** Called when the activity is first created. */

       TextView txt;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getServerData(null);
    }
     //i use my real ip here

    public String getServerData(String returnString) {
        System.out.println("going to connector class");
       InputStream is = null;
       final String KEY_121 = "http://10.0.0.128/connector.php";
       String result = "";
        //the year data to send
      //  ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
      //  nameValuePairs.add(new BasicNameValuePair("year","1970"));

        //http post
        try{
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(KEY_121);
               // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                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());
        }

        //convert response to string
        try{
                BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                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 json data
        try{
                JSONArray jArray = new JSONArray(result);
                for(int i=0;i<jArray.length();i++){
                        JSONObject json_data = jArray.getJSONObject(i);
                        Log.i("log_tag","ID: "+json_data.getInt("ID")+
                                ", \nActara: "+json_data.getString("Actara")
                        );
                        //Get an output to the screen
                        returnString += "\n\t" + jArray.getJSONObject(i); 
                }
        }catch(JSONException e){
                Log.e("log_tag", "Error parsing data "+e.toString());
        }
        return returnString; 
    }    

    }

Logcat error (on 4.0+):

11-12 12:02:35.658: E/log_tag(14083): Error in http connection android.os.NetworkOnMainThreadException
11-12 12:02:35.658: E/log_tag(14083): Error converting result java.lang.NullPointerException
11-12 12:02:35.663: E/log_tag(14083): Error parsing data org.json.JSONException: End of input at character 0 of 

Only the first error line is important, because it can't connect to a database, it gives a nullPointer (2nd and 3rd error).

This is what I tried in Asynch:

    public class connector extends Activity {
    /** Called when the activity is first created. */

       TextView txt;
    @Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    new BackgroundAsyncTask().execute();

}

 public class BackgroundAsyncTask extends
    AsyncTask<Void, Integer, Void> {

        InputStream is = null;
        final String KEY_121 = "http://10.0.0.128/connector.php";
        String result = "";
        String returnString = "";

        protected void onPostExecute(Void result) {

        }

        @Override
        protected void onPreExecute() {
        System.out.println("onPreExecute");
        }

        protected Void doInBackground(String... params) {
             try{
                 System.out.println("background in progress");
                 HttpClient httpclient = new DefaultHttpClient();
                 HttpPost httppost = new HttpPost(KEY_121);
                // httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                 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());
         }

         //convert response to string
         try{
                 BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                 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 json data
         try{
                 JSONArray jArray = new JSONArray(result);
                 for(int i=0;i<jArray.length();i++){
                         JSONObject json_data = jArray.getJSONObject(i);
                         Log.i("log_tag","ID: "+json_data.getInt("ID")+
                                 ", \nActara: "+json_data.getString("Actara")
                         );
                         //Get an output to the screen
                         returnString += "\n\t" + jArray.getJSONObject(i); 
                 }
         }catch(JSONException e){
                 Log.e("log_tag", "Error parsing data "+e.toString());
         }
        return null;
        }

        protected void onProgressUpdate(Integer... values) {

        }

        @Override
        protected Void doInBackground(Void... params) {
            // TODO Auto-generated method stub
            return null;
        }

    }

}

Someone that can help me? I don't know for sure what the real cause is why it isn't working for 4.0+.
If you need more info, just say it, and I will post it.
Code can be a bit messy, I didn't really "clean" it up yet properly.

回答1:

Since Android 3.0 you are not allowed to do network stuff on the main thread. Why? because network problems will lead to a slow ui. So you have to do all the http stuff in a new thread. You are on the right path but you made a mistake in your AsyncTask. Delete the empty doInBackground method in you async task and write @Override over your method.



回答2:

android.os.NetworkOnMainThreadException

this eror comes With HoneyComb(3.0 or Later). you can not perform a networking operation on its main thread as documentation says. to getting ride of this you must use handler or asynctask. AFAIK There is no another way to do it.

you can See this for More Details WHY ICS Crashes your App

Try Using Below Code Snippet

new Thread(){
    public void run(){
        //do your Code Here    
    }
}.start();


回答3:

Ok right... After searching for few hours, making this question, then 10 minutes later, you find a solution...

Option 1:
I added this line:

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

But I reccomend NOT to use option 1, this is a bad solution for real. Use option 2!
//===========================================================================
Option 2:

Used this tutorial to make a proper ASyncTask: http://www.elvenware.com/charlie/development/android/SimpleHttpGetThread.html

//===========================================================================
Used ASyncTask as final (option 2).



回答4:

why you are passing null in function of web connection and web service .?

getServerData(null);