Domanda

I'm new at Android app. development and I am trying to develop an app. that can reach ms sql 2008 r2 with jtds.

I have used sqllite database for creating connection string.

I am getting android os.NetworkOnMainThreadException error, PLEASE HELP ME my code is below,

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


}

}
È stato utile?

Soluzione

Always use an asynctask to wrap the DB calls or Network calls. These calls may take long to process and there will be a chance to block the application UI if ran from main thread. In an asynctask, whatever you do in doInBackground() method will be run in background thread.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top