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();
    }
Damiii
  • 1,363
  • 4
  • 25
  • 46
  • 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 – Raghunandan May 21 '13 at 07: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) – Damiii May 21 '13 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 – Raghunandan May 21 '13 at 15:59
  • and how do we do that ? – Damiii May 21 '13 at 16:13
  • http://stackoverflow.com/questions/15739635/how-to-return-value-from-async-task-in-android – Raghunandan May 21 '13 at 16:29
  • humm i saw what you said and didnt understand... Your mHandler is created on my UI thread ?? – Damiii May 21 '13 at 18:03
  • http://stackoverflow.com/questions/13815807/return-value-from-asynctask-class-onpostexecute-method. Another way. I don't know in what way i can explain more to help you. – Raghunandan May 21 '13 at 18:20
  • If you still don't understand. Ask a new question with a relevant code and someone can give a better explanation and probably more alternatives – Raghunandan May 21 '13 at 18:23

3 Answers3

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.

Raghunandan
  • 132,755
  • 26
  • 225
  • 256
  • 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 ? – Damiii May 18 '13 at 17:57
  • 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 – Raghunandan May 18 '13 at 18:08
  • 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 – Raghunandan May 18 '13 at 18:11
  • So if i have a java class which implements all the methods for my postgresql, i must extends it ? And put these methods above ? – Damiii May 18 '13 at 19:28
  • 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() – Raghunandan May 18 '13 at 19:32
  • on the method doBackground , does it return the value ? I mean, the AsyncTask receives three parameters right ? The first one is a parameter which i want to give , the second one refers to progression and the last one is the type of the result right ? How am i able , to send to my UI thread that result ? – Damiii May 20 '13 at 22:48
  • no no ! i wasnt accept it ! x) just i thought, in not accepting you wont see my question ! have you seen my edit post which i made above ? I included the asynctask code and i have a problem which i mentioned it on the edit post... Why it isn't doing the network stuff ? P.S.: i thought that if i accept your answer, the topic will be closed ( im a little new on stackoverflow) – Damiii May 21 '13 at 07:05
  • it should i am not aware of what your codes are doing coz its not part of what i have done. But any network related operation is done on the backgroudn thread. And you update ui on the ui thread. From what i see you are not updating ui in doinbackground so it should work if your code is right. Does your log statement log anything in logcat?? – Raghunandan May 21 '13 at 07:09
  • No my logcat isn't doing nothing :/ it is saying that there is no result – Damiii May 21 '13 at 07:17
  • @Damiii then there is something wrong with your code in doInBackground(). Cross check everything and try again. – Raghunandan May 21 '13 at 07:18
  • it's a little weird, because my code which i have in my background is equal in an other class, and it works perfectly hummmm – Damiii May 21 '13 at 07:24
  • @Damiii i don't know what your code is doing so i can't help with that. But if you do it right. it should work – Raghunandan May 21 '13 at 07:28
  • So let me understand if i am right, onDobackground i make all the connection and work right? After doing the work, it results on a Hashmap so i return on my doBackground method my hashmap. My onPostExecute method receive a parameter, which is the Hashmap ? The result of my doBackground ? – Damiii May 21 '13 at 07:31
  • ok, and on my onPostExecute can't i assigne the reference of my parameter to the variable of my UI thread direclty ? – Damiii May 21 '13 at 07:35
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

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
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.

Viacheslav
  • 5,443
  • 1
  • 29
  • 36