2

I'm having an issue with my android application and don't know how to resolve it.... I'm trying to make a connection throw my external database (postgreSQL) and taking some informations on there .... I made some code on java and the connection worked perfectly (also i was able to do some queries and receive the results)! The problem is, if i import to my android application the code which i made on my java class, it throws me an error which i do not understand ....

05-18 16:09:10.273: W/System.err(5395): org.postgresql.util.PSQLException: Something unusual has occured to cause the driver to fail. Please report this exception.
05-18 16:09:10.273: W/System.err(5395):     at org.postgresql.Driver.connect(Driver.java:287)
05-18 16:09:10.273: W/System.err(5395):     at java.sql.DriverManager.getConnection(DriverManager.java:175)
05-18 16:09:10.273: W/System.err(5395):     at java.sql.DriverManager.getConnection(DriverManager.java:209)
05-18 16:09:10.273: W/System.err(5395):     at com.mlab.android.basicoverlays.PostgreSQL.setConnection(PostgreSQL.java:55)
05-18 16:09:10.273: W/System.err(5395):     at com.mlab.android.basicoverlays.PostgreSQL.<init>(PostgreSQL.java:18)
05-18 16:09:10.273: W/System.err(5395):     at com.example.basicmaponline.MainActivity.onCreate(MainActivity.java:31)
05-18 16:09:10.273: W/System.err(5395):     at android.app.Activity.performCreate(Activity.java:5250)
05-18 16:09:10.273: W/System.err(5395):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1097)
05-18 16:09:10.283: W/System.err(5395):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2210)
05-18 16:09:10.283: W/System.err(5395):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2296)
05-18 16:09:10.283: W/System.err(5395):     at android.app.ActivityThread.access$700(ActivityThread.java:151)
05-18 16:09:10.283: W/System.err(5395):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1281)
05-18 16:09:10.283: W/System.err(5395):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-18 16:09:10.283: W/System.err(5395):     at android.os.Looper.loop(Looper.java:137)
05-18 16:09:10.283: W/System.err(5395):     at android.app.ActivityThread.main(ActivityThread.java:5293)
05-18 16:09:10.283: W/System.err(5395):     at java.lang.reflect.Method.invokeNative(Native Method)
05-18 16:09:10.283: W/System.err(5395):     at java.lang.reflect.Method.invoke(Method.java:511)
05-18 16:09:10.283: W/System.err(5395):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
05-18 16:09:10.283: W/System.err(5395):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
05-18 16:09:10.283: W/System.err(5395):     at dalvik.system.NativeStart.main(Native Method)
05-18 16:09:10.283: W/System.err(5395): Caused by: android.os.NetworkOnMainThreadException
05-18 16:09:10.293: W/System.err(5395):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
05-18 16:09:10.293: W/System.err(5395):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-18 16:09:10.293: W/System.err(5395):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-18 16:09:10.293: W/System.err(5395):     at java.net.InetAddress.getByName(InetAddress.java:289)
05-18 16:09:10.293: W/System.err(5395):     at java.net.InetSocketAddress.<init>(InetSocketAddress.java:105)
05-18 16:09:10.293: W/System.err(5395):     at java.net.InetSocketAddress.<init>(InetSocketAddress.java:90)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.core.PGStream.<init>(PGStream.java:60)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:101)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.Driver.makeConnection(Driver.java:393)
05-18 16:09:10.293: W/System.err(5395):     at org.postgresql.Driver.connect(Driver.java:267)
05-18 16:09:10.293: W/System.err(5395):     ... 19 more

P.S: i downloaded throw the postgreSQL website the .jar("postgresql-9.2-1002.jdbc4.jar") which i included on my android project ... And my java version is "java version "1.6.0_45". Help please. :/

I did tried with the class ActiveSync but it seems it doesnt work and i have no idea ...

//@SuppressWarnings("rawtypes")
public class loadDatabase extends AsyncTask<Void, Void, HashMap>{

    @Override
    protected HashMap doInBackground(Void... params) {
        // TODO Auto-generated method stub

        HashMap<String,SQLloja>listaLojas = new HashMap<String, SQLloja>();
    try{    
        PostgreSQL pSQL = new PostgreSQL(host,database,username,password);
        String sql = pSQL.getLojasCidadao();
        Statement st = pSQL.getConnection().createStatement();
        ResultSet rs = st.executeQuery(sql);

        while(rs.next()){
            int lcId = Integer.parseInt(rs.getString(1));
            String lcNome=rs.getString(2);
            String lcCP = rs.getString(3);
            int lcDistrito = Integer.parseInt(rs.getString(4));
            int lcConselho = Integer.parseInt(rs.getString(5));
            double lcAltitude = Double.parseDouble(rs.getString(6));
            double lcLongitude = Double.parseDouble(rs.getString(7));
            String lcTelefone = rs.getString(8);
            boolean lcEstado = Boolean.parseBoolean(rs.getString(9));
            String lcRua = rs.getString(10);

            SQLloja loja = new SQLloja(lcId,lcNome,lcCP,lcDistrito,lcConselho,lcAltitude,lcLongitude,lcTelefone,lcEstado,lcRua);

            listaLoja.put(loja.getNome(),loja.clone());

            String informacoesLoja = "Rua : "+lcRua+"\nC.P. : "+lcCP+"\nTel. : "+lcTelefone;

            Log.d("ASYNC",lcNome+" Altitude = "+lcAltitude+" Longitude = "+lcLongitude+" Rua = "+lcRua);
        }
        //listaLoja = new SQLlistLoja(listaLojas);
        rs.close();
        st.close();

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (Exception e) {
    e.printStackTrace();
    }

    if(listaLoja!=null){
        for(SQLloja loja : listaLoja.values()){
            Log.d("ASYNC", loja.getNome() );
        }
    }
    else Log.d("ASYNC","listaLoja = null ! PQP !");


        return listaLojas;
    }

    @Override
    protected void onPostExecute(HashMap listaLojas){
        listaLoja = listaLojas;
    }
}

Even with the :

if(listaLoja!=null){
        for(SQLloja loja : listaLoja.values()){
            Log.d("ASYNC", loja.getNome() );
        }
    }
    else Log.d("ASYNC","listaLoja = null ! PQP !");

It shows me that listaLoja is nullable ... when normally, it should be not nullable... Due to my doBackground method ( which takes the informations from my external database and put them on my listaLoja ...

:/

/edited post/

Intro.java:

  public class Intro extends Activity{

//SQLlistLoja listaLoja;
HashMap<String, SQLloja> listaLoja;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.intro);
    //Intent openMainActivity = new Intent("com.example.basicmaponline.MAINACTIVITY"); //isto vem do ficheiro AndroidManifest.xml o "com.example....."
    //startActivity(openMainActivity);

    try {
        listaLoja = new loadDatabase().execute().get();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ExecutionException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
8
  • you can assign if its a inner class of your activity and you have declared the variable or array list a s a activity class member Commented May 21, 2013 at 7:36
  • yes, i made that class ( loadDatabase ) in my inner class (called Intro). Now it's working my code, but i just wanna an opinion and see if we can do this (see my post,i edited) Commented May 21, 2013 at 13:16
  • you can use a handler for returning the value to the actiivty. You cannot return the result the way you did in the above edit Commented May 21, 2013 at 15:59
  • and how do we do that ? Commented May 21, 2013 at 16:13
  • stackoverflow.com/questions/15739635/… Commented May 21, 2013 at 16:29

3 Answers 3

1

NetworkOnMainThread exception occurs when you are running network related operation on the main UI thread.

You use should use a asynctask for this purpose

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

Check the link above especially the topic under the heading The 4 steps.

Example:

  class TheTask extends AsyncTask<Void,Void,Void>
  {
      protected void onPreExecute()
      {           super.onPreExecute();
                //display progressdialog.
      } 

       protected void doInBackground(Void ...params)
      {  
            //Network related opearaiton. Do not update ui here

            return null;
      } 

       protected void onPostExecute(Void result)
      {     
                super.onPostExecute(result);
                //dismiss progressdialog.
                //update ui
      } 

}

You could also create your own thread. But you need to make sure you update UI on the UI thread.

Sign up to request clarification or add additional context in comments.

14 Comments

Well i dont understand how it is implemented :s But i made it with the creation of a thread :) And now it works perfectly ! Is there any difference in doing with threads or that class ?
asynctask is a helper class. Kind of easy to use since onPreExecute() and OnPostExecute() are invoked on the UI Thread. doInBackground() is invoked on the backgroun thread. result of which is a parameter to onPosExecute(). So its easy to use and show progress dialog. You can check the link in the answer for more info
If you create a new thread of your own you need to make sure you are not updating ui there. you need to update ui on the ui thread. Asynctask runs on a single thread. For parallel execution you can use executor
So if i have a java class which implements all the methods for my postgresql, i must extends it ? And put these methods above ?
the methods are for asynctask. if you wish to use the same. check the answer above. move all your connection to network and getting the data to doInbackground()
|
0

As the stack trace indicates, this exception is thrown because you're doing networking code (talking withg PostgreSQL) on the main UI thread. This should be done on a background thread to leave the UI responsive.

See http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

Comments

0

Look at this NetworkOnMainThreadException - you're doing some network calls from UI thread. Since android 4.0 it must be performed in separate thread. Look this for example.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.