2013-04-04 62 views
-5

我是Android应用程序新手。开发和我正在尝试开发一个应用程序。可以通过jtds到达ms sql 2008 r2。如何修复NetworkOnMainThreadException?

我已经使用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

使用'AsyncTask'或其他构造来完成主(UI)线程的网络操作。或者,关闭严格模式。 – Tushar 2013-04-04 03:17:56

+0

你在哪里叫giris()?它不应该从主线程调用。 – sandrstar 2013-04-04 03:20:10

+1

只需搜索一下。这比输入一个问题更省力 - 更好的是,你将学会如何自己做! – 323go 2013-04-04 03:21:31

回答

0

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

+0

谢谢asfsafgsf,我现在正在寻找我如何使用asynctasck,我之前说我是在Android和Java新的,但你的答案是真正的照明。 – user2238956 2013-04-04 04:23:52

+0

很高兴help.please也看看这个http://developer.android.com/training/articles/perf-anr.html – afadfadf 2013-04-04 05:43:11