尝试连接外部数据库(postgreSQL)与我的Android应用程序

时间:2013-05-18 15:26:08

标签: java android postgresql

我的Android应用程序出现问题,并且不知道如何解决它.... 我试图建立连接抛出我的外部数据库(postgreSQL)并在那里获取一些信息.... 我在java上制作了一些代码并且连接完美(我也能够做一些查询并收到结果)!问题是,如果我导入我的Android应用程序我在我的java类上创建的代码,它会抛出一个我不明白的错误....

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
PS:我下载了postgreSQL网站上的.jar(&#34; postgresql-9.2-1002.jdbc4.jar&#34;),我把它放在我的android项目中...而且我的java版本是&#34 ; java版本&#34; 1.6.0_45&#34;。 请帮忙。 :/

我确实尝试使用ActiveSync类,但似乎它不起作用,我不知道......

//@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;
    }
}

即使是:

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

它告诉我listaLoja是可以为空的...通常情况下,它应该是不可为空的...由于我的doBackground方法(从我的外部数据库获取信息并将它们放在我的listaLoja上......

:/

/编辑帖子/

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();
    }

3 个答案:

答案 0 :(得分:1)

在主UI线程上运行网络相关操作时会发生NetworkOnMainThread异常。

你应该使用asynctask用于此目的

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

检查上面的链接,尤其是“4个步骤”标题下的主题。

示例:

  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
      } 

}

您也可以创建自己的主题。但是您需要确保在UI线程上更新UI。

答案 1 :(得分:0)

当堆栈跟踪指示时,抛出此异常是因为您正在主UI线程上执行网络代码(与PostgreSQL交谈)。这应该在后台线程上完成,以使UI响应。

请参阅http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html

答案 2 :(得分:0)

看看这个NetworkOnMainThreadException - 您正在从UI线程进行一些网络调用。从Android 4.0开始,它必须在单独的线程中执行。例如,查看this