如何修复NetworkOnMainThreadException?

时间:2013-04-04 03:14:31

标签: android sql-server eclipse jtds

我是Android应用的新手。开发,我正在尝试开发一个应用程序。可以通过jtds到达ms sql 2008 r2。

我使用了sqllite数据库来创建连接字符串。

我收到android os.NetworkOnMainThreadException错误,请帮助我,我的代码在下面,

private void giris() {

    DB db = new DB(this);
    db.open();
    Cursor c = db.Query();
    String ipAdresi = null, Port = null, veriTabaniAdi = null, kullaniciAdi = null, sifre = null;

    while (c.moveToNext()) {
        ipAdresi = c.getString(c.getColumnIndex("IpAdresi"));
        Port = c.getString(c.getColumnIndex("PORT"));
        kullaniciAdi = c.getString(c.getColumnIndex("KullaniciAdi"));
        sifre = c.getString(c.getColumnIndex("Sifre"));
    }

    url = "jdbc:jtds:sqlserver://" + ipAdresi + ":" + Port + ";databaseName=";
    driver = "net.sourceforge.jtds.jdbc.Driver";
    userName = kullaniciAdi;
    password = sifre;
    db.close();
    ResultSet results = null;
    try {
        EditText txtTest = (EditText)findViewById(R.id.editTextip);
        EditText txtName = (EditText)findViewById(R.id.editTextport);
        String user = txtTest.getText().toString();
        String pass = txtName.getText().toString();

        Class.forName(driver).newInstance();
        Connection conn = DriverManager.getConnection(url, userName, password);
        Statement statement = conn.createStatement();
        results = statement.executeQuery("Select * From Kullanıcı where KULLANICI = '" + user + "' and SIFRE = '"+ pass + "'");

        if(!results.next())
        {
            Toast.makeText(this, "Hoşgeldiniz ", Toast.LENGTH_SHORT).show();
            try {
                Class d = Class.forName("com.example.endustrinetbistro.Girismenu");
                Intent intent = new Intent(this, d);
                startActivity(intent);
            } catch (ClassNotFoundException e) {
                Toast.makeText(this, "Hata : " + e.toString(),
                        Toast.LENGTH_SHORT).show();
            }
        }
        else
        {
          do{
                Toast.makeText(this, "Hata : " + "Kullanıcı Adınız, Şifreniz veya Baglantı Ayarlarınızda Bir Sorun var ", Toast.LENGTH_SHORT)
                .show();
          }while(results.next());
        }
    } catch (Exception e) {
        Toast.makeText(this, "Hata : " + e.toString(), Toast.LENGTH_SHORT)
                .show();
    }


}

}

1 个答案:

答案 0 :(得分:0)

始终使用asynctask来包装数据库调用或网络调用。 这些调用可能需要很长时间才能处理,如果从主线程运行,将有机会阻止应用程序UI。在asynctask中,无论你在doInBackground()方法中做什么都将在后台线程中运行。