Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8815227
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T04:19:25+00:00 2026-06-14T04:19:25+00:00

I use this code below, it works perfectly in Android 2.3.3. However, in 4.0+

  • 0

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 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T04:19:26+00:00Added an answer on June 14, 2026 at 4:19 am

    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).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Please can anyone help me out with this problem? This code below works perfectly
This has been bothering me lately- when I use some code like below to
This code below works perfectly for all browsers except IE 7 or 8. <img
I use this code below to hide stream url of songs for my wordpress
I have this code below. I need to use a class id instead of
For this code example below, usually I would use [self fall]; instead of the
This code triggers the complaint below: #!/usr/bin/perl use strict; use warnings; my $s =
I use below code to show folder list in AlertDialog: ListDialog = new AlertDialog.Builder(MyActivity.this);
My code i use to parse HTMl is this below, and the 2nd code
I use this code to connect to SQL Server 2012, but it does not

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.