我在创建警报对话框时遇到问题,该对话框显示 - 无法添加窗口 - 令牌 null 不适用于应用程序
public class Authenticator {
public static final String TAG = "Authenticator";
public static int getUserId(final String username, final String password) {
int retVal = 0;
final QuickTexterApplication qta = QuickTexterApplication.getQuickTexterApplication();
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
public void run() {
Runnable displayGUIRun = new Runnable() {
public void run() {
int userId = 0;
HttpURLConnection urlConnection = null;
String urlAuthenticator = qta.getResources().getString(R.string.urlAuthenticator);
try{
URL url = new URL(urlAuthenticator);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
wr.writeBytes("username=" + username + "&");
wr.writeBytes("password=" + password);
wr.flush();
wr.close();
urlConnection.connect();
if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK){
Log.d(TAG,"HTTP OK");
InputStream inStream = urlConnection.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inStream));
String inLine = in.readLine();
in.close();
Log.d(TAG,"inLine: " + inLine);
userId = Integer.parseInt(inLine);
}
else {
Log.d(TAG,"HTTP NOT OK");
}
String alertMsg = "Unable to establish connection to server";
switch(userId){
case -1 :
alertMsg = "You entered an invalid username or password";
case 0 : // This is where the exception occurs
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(qta.getApplicationContext());
Log.d(TAG, alertMsg);
alertBuilder.setMessage(alertMsg)
.setNeutralButton("Ok", new DialogInterface.OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
break;
我不能使用“this”作为上下文,因为 Authenticator 不是 Avitvity。
但随后 getApplicationContext() 也不起作用......
我想做的是从 Activity 类调用方法:getUserId() 。