I have a nested class that is used for a new Thread
and has some Toast
to display some user information depending on the error.
I already tried to pass the context through the constructor, I already created a context variable in the main class but the error persists with the message:
br.com.mycompany.teste.AccountAccessActivity $ LoginRunnable.run (AccountAccessActivity.java:97)
Code:
public class AccountAccessActivity extends Activity implements AccountAccess
{
private EditText account;
private EditText pass;
private Spinner spinner;
private ProgressBar progressBar;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account_access);
account = (EditText)findViewById(R.id.accountInput);
pass = (EditText)findViewById(R.id.passInput);
spinner = (Spinner)findViewById(R.id.accTypeSpinner);
progressBar = (ProgressBar)findViewById(R.id.progressCircle);
context = this;
if(!InternetConnectionStatus.isOnline(context))
{
Toast.makeText(context ,R.string.noInternet, Toast.LENGTH_LONG).show();
}
}
@Override
public void login(View v)
{
LoginForm form = new LoginForm(account.getText(), pass.getText(), spinner.getSelectedItemPosition());
Runnable runnable = new LoginRunnable(form, this);
new Thread(runnable).start();
}
@Override
public void forgotPassword(View v)
{
}
@Override
public void newAccount(View v)
{
}
public class LoginRunnable implements Runnable
{
private LoginForm form;
public LoginRunnable(LoginForm form, Context context)
{
this.form = form;
}
@Override
public void run()
{
try
{
UserDAO userDAO = new UserDAO(new ConnectionFactory().getConnection());
userDAO.validadeLogin(form);
}
catch (SQLTimeoutException e)
{
Toast.makeText(context, R.string.timeLimitExceded, Toast.LENGTH_LONG).show();
}
catch (SQLException e)
{
Toast.makeText(context, R.string.erroUserOrPass, Toast.LENGTH_LONG).show();
}
catch (ClassNotFoundException e)
{
Toast.makeText(context, R.string.internalErro, Toast.LENGTH_LONG).show();
}
}
}
}
Line 97:
FATAL EXCEPTION: Thread-3642 Process: br.mycompany.db, PID: 7007
java.lang.RuntimeException: Can not create handler inside thread that has not called Looper.prepare ()
at android.os.Handler. (Handler.java:200)
at android.os.Handler. (Handler.java:114)
at android.widget.Toast $ TN. (Toast.java:372)
at android.widget.Toast (Toast.java:105)
at android.widget.Toast.makeText (Toast.java:264)
at android.widget.Toast.makeText (Toast.java:313)
at www.yourweb.com.support.AccountAccessActivity $ LoginRunnable.run (AccountAccessActivity.java:98)
at java.lang.Thread.run (Thread.java:841)
What is the best way to pass Context to a nested class in this case?