java - 无法实例化 Activity

标签 java android android-asynctask

我在 LoginActivity 中有登录方法,它调用 AsyncTask 类方法。

该方法采用 UserName 并从 SharedPrefrences 传递,通过 SOAP Web 服务执行 someQuery 并返回结果 THE TeacherID if == 1 go Next Activity 。

但是一旦我在启动屏幕后打开 LoginActivity 就会收到此日志错误:

日志错误:

             FATAL EXCEPTION: main
     java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.hesham.sams/com.hesham.sams.LoginActivity}: java.lang.NullPointerException
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2034)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
        at android.app.ActivityThread.access$700(ActivityThread.java:140)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:137)
        at android.app.ActivityThread.main(ActivityThread.java:4921)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:511)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
        at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
        at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:139)
        at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:65)
        at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
        at android.app.AlertDialog$Builder.<init>(AlertDialog.java:359)
        at com.hesham.sams.LoginActivity.<init>(LoginActivity.java:79)
        at java.lang.Class.newInstanceImpl(Native Method)
        at java.lang.Class.newInstance(Class.java:1319)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2025)
        ... 11 more

登录 Activity :

 loginBtn.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            ProgressDialog progressDialog = new ProgressDialog(
                    LoginActivity.this);
            progressDialog.setMessage("جاري تسجيل الدخول الرجاء الانتظار");
            progressDialog.show();

            AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
                    LoginActivity.this, progressDialog,
                    getApplicationContext());
            MyTask.execute();

        }
    });

完整的 AsnckTask 类:

public class AsyncTaskWebServiceCaller extends AsyncTask<Void, Void, String> {

Activity mActivity;
Context context;

// LoginActivity MyClass = new LoginActivity();
// public static Context contextOfApplication;
ProgressDialog progressDialog;

// Context applicationContext = LoginActivity.getContextOfApplication();

// Constractor
public AsyncTaskWebServiceCaller(Activity activity,
        ProgressDialog progressDialog, Context context) {
    super();
    this.progressDialog = progressDialog;
    this.mActivity = activity;
    this.context = context;
}

// BackGround Process
@Override
protected String doInBackground(Void... voids) {
    // this is executed in a background thread.
    // the result is returned to the UI thread via onPostExecute

    try {
        final String NAMESPACE = "http://ws.sams.com";
        final String URL = "http://88.198.82.92:8080/sams1/services/LoginActvityWs?WSDL"; // usint
                                                                                            // //
                                                                                            // localhost
        final String METHOD_NAME = "login";
        final String SOAP_ACTION = "http://ws.sams.com/login";
        final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        final HttpTransportSE androidHttpTransport = new HttpTransportSE(
                URL);

        SharedPreferences prefs = PreferenceManager
                .getDefaultSharedPreferences(this.mActivity);
        String user = prefs.getString("login", null);
        String pass = prefs.getString("password", null);
        // Calling Login Method
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

        // First Reques for USER NAME .
        PropertyInfo pi = new PropertyInfo();
        pi.setName("username");
        pi.setValue(user);
        pi.setType(String.class);
        request.addProperty(pi);

        // Second Reques for USER NAME .
        PropertyInfo pi2 = new PropertyInfo();
        pi2.setName("password");
        pi2.setValue(pass);
        pi2.setType(String.class);
        request.addProperty(pi2);

        // Getting Request Result , Will get TID .
        envelope.setOutputSoapObject(request);
        androidHttpTransport.call(SOAP_ACTION, envelope);
        SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

        return response.toString();

    } catch (XmlPullParserException e) {

        return e.toString();

    } catch (IOException e) {

        return e.toString();
    }

    catch (NullPointerException e) {

        return e.toString();

    }

}

@Override
protected void onPostExecute(String result) {

    Toast.makeText(mActivity.getApplicationContext(), result,
            Toast.LENGTH_LONG).show();

    // If any error oceeared duaring get TID
    if (result.equalsIgnoreCase("error")) {
        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                mActivity);

        alertDialog.setTitle("يوجد مشكلة بالاتصال او السيرفر");
        alertDialog.setMessage("هل تود المحاولة مجددا ؟ ");
        // Retry Button Action
        alertDialog.setPositiveButton("نعم",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        AsyncTaskWebServiceCaller asynTask = new AsyncTaskWebServiceCaller(
                                mActivity, progressDialog, mActivity
                                        .getApplicationContext());
                        asynTask.execute();
                    }
                });

        // No Button Action
        alertDialog.setNegativeButton("لا",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        progressDialog.dismiss();
                    }
                });

        alertDialog.show();

    }
    // IF pass or user Filed .
    else if (Integer.parseInt(result.toString()) == 0) {

        final AlertDialog.Builder alertDialog = new AlertDialog.Builder(
                mActivity);

        alertDialog.setTitle("اسم المستخدم او كلمة المرور خاطئة");
        alertDialog.setMessage("هل تود اعادة تسجيل الدخول ");

        alertDialog.setPositiveButton("نعم",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {

                        progressDialog.dismiss();

                    }
                });
        alertDialog.setNegativeButton("لا",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        progressDialog.dismiss();
                        Toast.makeText(mActivity.getApplicationContext(),
                                "thank you for using SAMS app",
                                Toast.LENGTH_LONG).show();
                        mActivity.finish();
                    }
                });

        alertDialog.show();

    }

    // For correct Login !
    else {
        Toast.makeText(mActivity.getApplicationContext(),
                result.toString(), Toast.LENGTH_LONG).show();
        progressDialog.dismiss();
        if (Integer.parseInt(result.toString()) == 1) {

            Intent intent1 = new Intent(mActivity, DashBoard.class);
            mActivity.startActivity(intent1);

        }
    }

}

}

最佳答案

Caused by: java.lang.NullPointerException
    at android.content.ContextWrapper.getApplicationInfo(ContextWrapper.java:139)
    at android.view.ContextThemeWrapper.getTheme(ContextThemeWrapper.java:65)
    at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
    at android.app.AlertDialog$Builder.<init>(AlertDialog.java:359)
    at com.hesham.sams.LoginActivity.<init>(LoginActivity.java:79)

从下往上阅读。您的 LoginActivity 初始化(构造函数或成员变量初始化)会实例化 AlertDialog.Builder。它接受一个Context 参数。但是, Activity 初始化在生命周期中还为时过早,无法将 Activity 对象用作Context。您必须将 AlertDialog.Builder 初始化(以及需要 Context 的其他所有内容)延迟到 onCreate()

关于java - 无法实例化 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18704492/

相关文章:

android - 如何实现更灵活的AsyncTask?

android - 使用 HttpClient 和 Progressbar 的异步任务

java - 从代码覆盖中排除枚举类?

java - 给定两个 vector 在opengl中绘制3d平面

java - 移动客户端登录Spring REST服务器

java - Edittext - 如何只允许添加一个点?

android - 切换 fragment 时跳转滚动

AsyncTask 中的 Android getCacheDir

java - 通过 Java 解锁智能卡的 PIN (SunPKCS11)

java - java中单词之间添加空格并使每个单词除了第一个小写之外