-1

I have started to use Android Studio just two days back and I don't have much experience in java too. I have made a simple log in app to connect to Sql server as database for checking. I have written this code referred from http://seotoolzz.com/android/android-login-app-with-mssql-server.php. but in the following line it shows an error :method gettext must be called from the ui thread. Please do help since m very new to android app development. Thanks a lot.

String usernam = username.getText().toString();

String passwordd = password.getText().toString();

 public class MainActivity extends AppCompatActivity

{

Button login;
EditText username,password;
ProgressBar progressBar;



Connection con;
String un,pass,db,ip;


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    login = (Button) findViewById(R.id.button);
    username = (EditText) findViewById(R.id.editText);
    password = (EditText) findViewById(R.id.editText2);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);



    ip = "1IP";
    db = "ADB";
    un = "your username for that database here";
    pass = "your password for that database here";
     login.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            CheckLogin checkLogin = new CheckLogin();
                checkLogin.execute("");
        }
    });

}

public class CheckLogin extends AsyncTask<String,String,String>
{
    String z = "";
    Boolean isSuccess = false;

    @Override
    protected void onPreExecute()
    {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onPostExecute(String r)
    {
        progressBar.setVisibility(View.GONE);
        Toast.makeText(MainActivity.this, r, Toast.LENGTH_SHORT).show();
        if(isSuccess)
        {
            Toast.makeText(MainActivity.this , "Login Successfull" , Toast.LENGTH_LONG).show();
            //finish();
        }
    }
    @Override
    protected String doInBackground(String... params)
    {
        String usernam = username.getText().toString();
        String passwordd = password.getText().toString();
        if(usernam.trim().equals("")|| passwordd.trim().equals(""))
            z = "Please enter Username and Password";
        else
        {
            try
            {
                con = connectionclass(un, pass, db, ip);       
                if (con == null)
                {
                    z = "Check Your Internet Access!";
                }
                else
                {
                                           String query = "select * from Login where UserName= '" + usernam.toString() + "' and Password = '"+ passwordd.toString() +"'  ";
                    Statement stmt = con.createStatement();
                    ResultSet rs = stmt.executeQuery(query);
                    if(rs.next())
                    {
                        z = "Login successful";
                        isSuccess=true;
                        con.close();
                    }
                    else
                    {
                        z = "Invalid Credentials!";
                        isSuccess = false;
                    }
                }
            }
            catch (Exception ex)
            {
                isSuccess = false;
                z = ex.getMessage();
            }
        }
        return z;
    }
}


@SuppressLint("NewApi")
public Connection connectionclass(String user, String password, String database, String server)
{
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
    Connection connection = null;
    String ConnectionURL = null;
    try
    {
        Class.forName("net.sourceforge.jtds.jdbc.Driver");
        ConnectionURL = "jdbc:jtds:sqlserver://" + server + database + ";user=" + user+ ";password=" + password + ";";
        connection = DriverManager.getConnection(ConnectionURL);
    }
    catch (SQLException se)
    {
        Log.e("error here 1 : ", se.getMessage());
    }
    catch (ClassNotFoundException e)
    {
        Log.e("error here 2 : ", e.getMessage());
    }
    catch (Exception e)
    {
        Log.e("error here 3 : ", e.getMessage());
    }
    return connection;
}

}
Vishal Yadav
  • 3,642
  • 3
  • 25
  • 42
ARU
  • 17
  • 2
  • 7
  • 2
    Hi have a look over here, i think the aysnc task cannot access the text box but you can pass the values in. https://stackoverflow.com/questions/32324769/error-method-gettext-must-be-called-from-the-ui-thread-currently-inferred-t – Paul Harris Oct 25 '17 at 12:56
  • First thing to do when encountering an error or exception is to search for existing answers. When you don't understand some words from exception message (and considering you are new to Java - you are in this situation), you should first learn about what those words mean first, then read the message again. Once you understand what is wrong, it will be very easy to fix the problem. – M. Prokhorov Oct 25 '17 at 13:04

2 Answers2

1

The problem you're experiancing is due to accessing current view elements in an outside class (edit: or rather in another, non-UI thread).

A workaround is to use Activity.runOnUIThread(Runnable), like so:

String usernam, passwordd;
getActivity().runOnUIThread(new Runnable(){
    usernam = username.getText().toString();
    passwordd = password.getText().toString();
}

You could also pass Strings as input to AsyncTask while calling it:

@Override
public void onClick(View v)
{
    CheckLogin checkLogin = new CheckLogin();
    checkLogin.execute(usernam.getText(),passwordd.getText());
}

and accessing it in AsyncTask.doInBackground:

@Override
protected String doInBackground(String... params)
{
    usernam = params[0];
    passwordd = params[1];
    ....
}

Hope this is helpful.

0

Asyntask is a separate thread and cannot access the UI thread elements.instead store the values as global member variables and access them.

 String usernam,password;

Then inside your onclickListener store the values to them.

login.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            usernam=username.getText().toString();
            password=password.getText().toString();
            CheckLogin checkLogin = new CheckLogin();
            checkLogin.execute("");
        }
    });
Sharath kumar
  • 4,064
  • 1
  • 14
  • 20