我有一个问题,创建一个警告对话框,显示 - 无法添加窗口 - 令牌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() .
1 回答
您必须在Authenticator类中创建构造函数,它将为您的类提供上下文 . 并通过调用此构造函数将上下文传递给此类 .
通过这种方式,您可以获得此类的上下文 . 让我知道它是否有效 . :)