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 7808751
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T03:13:21+00:00 2026-06-02T03:13:21+00:00

I am trying to run this activity in order to query a database for

  • 0

I am trying to run this activity in order to query a database for populating a table.
I have tried to follow a snippet I found online, the only problem is, no matter what, I get “connectionandroid.os.NetworkOnMainThreadException” error.

I have tried to put in an handler, as suggested in many forums, using AsyncTask and do it in background, but still nothing.
I know the error appears when a long query is sent to a database, but this query takes 0.1s, probably. I have the db locally, although accessing it with public IP, and the db is extremely small.

Here my PHP code:

<?php

$hostname_localhost ="localhost";
$database_localhost ="DB";
$username_localhost ="root";
$password_localhost ="pwd";

mysql_connect($hostname_localhost,$username_localhost,$password_localhost);

mysql_select_db($database_localhost);

$sql=mysql_query("select * from friendlist where Id1 = 1");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>

The code works, as if I go to the page, I see displayed the results (I only have 3 rows for the moment).

Here is the java part:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MySQLAndroidActivity extends ListActivity {

JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb=null;
HttpResponse response;
HttpEntity entity;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//http post
try{
HttpClient httpclient = new DefaultHttpClient();

 HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");

 httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
response = httpclient.execute(httppost);

 entity = response.getEntity();


 is = entity.getContent();

 }catch(Exception e){
     Log.e("log_tag", "Error in http connection"+e.toString());
     System.exit(1);
}

//convert response to string
try{
  BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
   sb = new StringBuilder();
   sb.append(reader.readLine() + "\n");

   String line="0";
   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());
    }
//parsing data
String idfriend;
String id1;
String id2;
try{
  jArray = new JSONArray(result);
  JSONObject json_data=null;
  for(int i=0;i<jArray.length();i++){
         json_data = jArray.getJSONObject(i);
         idfriend=json_data.getString("Idfriend");
         id1=json_data.getString("Id1");
         id2=json_data.getString("Id2");


         System.out.println("id1: " + id1);
     }
  }
  catch(JSONException e1){
   Toast.makeText(getBaseContext(), "No Id found" ,Toast.LENGTH_LONG).show();
  } catch (ParseException e1) {
   e1.printStackTrace();
 }
}
}

I tried also using a simple Activity and not a ListActivity.

I have an almost similar code, but that one uses a different method. In fact, it doesnt get the result, on php, it just returns a characters whether there are 0 or more rows retrieved. In this case I need something on a higher level, as I will need to get the values of some specific fields.

EDIT:

As requested, the stacktrace:

  Error in http connectionandroid.os.NetworkOnMainThreadException
  04-17 06:44:17.921: W/System.err(24207): java.lang.Exception
  04-17 06:44:17.921: W/System.err(24207):  at       com.mysql.android.MySQLAndroidActivity.onCreate(MySQLAndroidActivity.java:56)
  04-17 06:44:17.921: W/System.err(24207):  at       android.app.Activity.performCreate(Activity.java:4465)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
  04-17 06:44:17.921: W/System.err(24207):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
  04-17 06:44:17.921: W/System.err(24207):  at android.os.Handler.dispatchMessage(Handler.java:99)
  04-17 06:44:17.921: W/System.err(24207):  at android.os.Looper.loop(Looper.java:137)
  04-17 06:44:17.931: W/System.err(24207):  at android.app.ActivityThread.main(ActivityThread.java:4424)
  04-17 06:44:17.931: W/System.err(24207):  at java.lang.reflect.Method.invokeNative(Native Method)
  04-17 06:44:17.931: W/System.err(24207):  at java.lang.reflect.Method.invoke(Method.java:511)
  04-17 06:44:17.931: W/System.err(24207):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  04-17 06:44:17.931: W/System.err(24207):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  04-17 06:44:17.931: W/System.err(24207):  at dalvik.system.NativeStart.main(Native Method)

EDIT2:

Here is something very similar to the version I did with the AsyncTask (I am creating it on the fly, without a compiler, so it might not be perfect; but it is very similar to the one I did before):

  @Override
   public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
   setContentView(R.layout.main);

      new LoadTask().execute();

  }



 private class LoadTask extends AsyncTask<Void, Integer, Void> {
            @Override
            protected void onPreExecute() {

            }

            @Override
            protected Void doInBackground(Void... params) {
                    synchronized (this) {

                    Looper.prepare();       
                    doStuff() //this method basically contains what it is inside the onCreate.

                    }

                    return null;
            }

       }
       }

– I recall that I was forced to use ‘Looper.prepare();’.
So I added it before ‘doStuff();’

EDIT 2:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

public class MySQLAndroidActivity extends ListActivity {

    JSONArray jArray;
    String result = null;
    InputStream is = null;
    StringBuilder sb = null;
    HttpResponse response;
    HttpEntity entity;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        new LoadTask.execute();

    }



    private class LoadTask extends AsyncTask < Void, Integer, Void > {@Override
        protected void onPreExecute() {

        }

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

            Looper.prepare();

            doStuff();



            return null;


        }
    }


    public void doStuff() {
        ArrayList < NameValuePair > nameValuePairs = new ArrayList < NameValuePair > ();
        //http post
        try {
            HttpClient httpclient = new DefaultHttpClient();

            HttpPost httppost = new HttpPost("http://X.X.X.X/test.php");

            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            response = httpclient.execute(httppost);

            entity = response.getEntity();


            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection" + e.toString());
            System.exit(1);
        }


        //convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
            sb = new StringBuilder();
            sb.append(reader.readLine() + "\n");

            String line = "0";
            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());
        }
        //parsing data
        String idfriend;
        String id1;
        String id2;
        try {
            jArray = new JSONArray(result);
            JSONObject json_data = null;

            System.out.println("Length " + jArray.length());
            Log.d("DB", "Length " + jArray.length());

            for (int i = 0; i < jArray.length(); i++) {

                System.out.println("counter " + i);
                json_data = jArray.getJSONObject(i);
                idfriend = json_data.getString("Idfriend");
                id1 = json_data.getString("Id1");
                id2 = json_data.getString("Id2");


                System.out.println("id1: " + id1);
            }
        } catch (JSONException e1) {
            Log.d("DB", "Error somewhere");
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
    }
}

Thanks in advance,

N.

  • 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-02T03:13:23+00:00Added an answer on June 2, 2026 at 3:13 am

    I heard that starting from ICS, it is not allowed to perform network operations on UI (main) thread. Therefore, you must need to perform this operation in a separate thread. So either use AsyncTask, Thread or HandlerThread with Looper and Handler to perform web operation. If you try it on a device running froyo or gingerbread, it would be fine but not on ICS.

    Regarding your attempt to run it via handler or AsyncTask, it depends on how you did it. Paste that code so i see the problem.


    Update

    public class MySQLAndroidActivity extends ListActivity {
    
        private static final String url = "http://X.X.X.X/test.php";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity2);
    
            LoadTask t = new LoadTask();
            t.execute(null);
    
        }
    
        private static class LoadTask extends AsyncTask<Void, Void, Void> {
            @Override
            protected void onPreExecute() {
    
            }
    
            @Override
            protected Void doInBackground(Void... params) {
                doStuff();
    
                return null;
            }
        }
    
    
    
    
    
        public static void doStuff() {
            JSONArray jArray;
            String result = null;
            InputStream is = null;
            StringBuilder sb = null;
            HttpResponse response;
            HttpEntity entity;
    
            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
            // http post
            try {
                HttpClient httpclient = new DefaultHttpClient();
    
                HttpPost httppost = new HttpPost(url);
    
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                response = httpclient.execute(httppost);
    
                entity = response.getEntity();
    
                is = entity.getContent();
    
            } catch (Exception e) {
                Log.e("log_tag", "Error in http connection" + e.toString());
                System.exit(1);
            }
    
            // convert response to string
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
                sb = new StringBuilder();
                sb.append(reader.readLine() + "\n");
    
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line);
                }
                is.close();
                result = sb.toString();
    
                Log.i("json string", result);
            } catch (Exception e) {
                Log.e("log_tag", "Error converting result " + e.toString());
            }
    
    
            // parsing data
            String idfriend;
            String id1;
            String id2;
            try {
                jArray = new JSONArray(result);
                JSONObject json_data = null;
    
                System.out.println("Length " + jArray.length());
                Log.d("DB", "Length " + jArray.length());
    
                for (int i = 0; i < jArray.length(); i++) {
    
                    System.out.println("counter " + i);
                    json_data = jArray.getJSONObject(i);
                    idfriend = json_data.getString("idfriend");
                    id1 = json_data.getString("id1");
                    id2 = json_data.getString("id2");
    
                    System.out.println("id1: " + id1);
                }
            } catch (JSONException e1) {
                Log.d("DB", "Error somewhere");
            } catch (ParseException e1) {
                e1.printStackTrace();
            }
        }
    
    }
    

    *There were some method calling issues and the most important was that you were fetching keys out from JSONObject as Idfriend, Id1, Id2 which is wrong because in your json string the keys are like idfriend, id1, id2. Its case-sensitive, thats why it was crashing.

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

Sidebar

Related Questions

I'm trying to run this query: select * from activity where id = 9348927
I have this problem when trying to run hello world program using android SDK.
I am trying to run this dreadfully simple command in Bash java -cp nasa-top-secret.jar
I'm trying to run this code: let coins = [50, 25, 10, 5, 2,1]
I'm trying to run this for loop; for (int col= 0; grid[0].length; col++) However
I'm trying to run this script: import re, os def build_pool(cwd): global xtn_pool, file_pool
I am trying to run this code: ItemTaxonomy iTaxonomy = from itemTaxonomy in connection.ItemTaxonomy
I am trying to run this SQL from ASP.NET 2005 but am getting an
I am trying to run this seemingly simple piece of code which is repeated
I am trying to run this code : exec myStoredProcedure Cast('c5b48202-36af-4597-9780-5366d4188f55' AS uniqueidentifier), 744,

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.