我在LoginActivity中有一个Login方法,它调用AsyncTask类方法。

该方法采用UserName并从SharedPrefrences传递通过SOAP webservice做someQuery,如果== 1则返回重新解析教师ID进行下一步活动。

但是一旦我在启动屏幕后打开LoginActivity时收到此LOG错误:

日志错误:

             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


LoginActivity:

 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参数。但是,活动初始化在生命周期中还为时过早,无法将活动对象用作Context。您必须将AlertDialog.Builder初始化(以及所有其他需要Context的内容)延迟到onCreate()

10-08 15:32