2
I have a nested class that’s used for a new Thread
and it has some Toast
to present some information to the user depending on the error.
I 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.minhaempresa.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.com.minhaempresa.db, PID: 7007
java.lang.Runtimeexception: Can’t 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 br.com.minhaempresa.somdegustacao.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?
You have omitted the main part from the error log: the exception.
– Pablo Almeida