2

I am getting a null pointer exception when trying to run my app. It seems ok in the manifest xml file. here is the activity java code:

package com.shale.activities;

import java.util.Arrays;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.facebook.FacebookException;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.LoginButton.OnErrorListener;
import com.shale.services.DBConnection;
import com.shale.services.Login;
import com.shale.shaleapp.R;

public class MainActivity extends Activity {

    private String TAG = "MainActivity";
    private Context context;
    private Button loginBtn;
    private Intent mainPage = new Intent(this, MainPage.class);
    private EditText userEmail;
    private EditText userPass;
    private LoginButton fbLoginBtn;

     @Override
     protected void onCreate(Bundle savedInstanceState) 
     {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.activity_main);
         DBConnection.initialize(this);
         loginBtn = (Button) findViewById(R.id.loginBtn);
         userEmail = (EditText) findViewById(R.id.emailInput);
         userPass = (EditText) findViewById(R.id.passwordInput);
         fbLoginBtn = (LoginButton) findViewById(R.id.authButton);
         context = this;


         loginBtn.setOnClickListener(new OnClickListener() 
         {
            @Override
            public void onClick(View view)
            {
                Login login = new Login(userEmail.getText().toString(), userPass.getText().toString());
                boolean userAllowed = login.loginUser();
                if(userAllowed) 
                {
                    startActivity(mainPage);

                }
                else
                {
                    Toast.makeText(context, "Invalide email and password", Toast.LENGTH_LONG).show();
                }
            }
         });

          fbLoginBtn.setOnErrorListener(new OnErrorListener()
          {
               @Override
               public void onError(FacebookException error)
               {
                   Log.i(TAG, "Error " + error.getMessage());
               }
          });

          // set permission list, Don't foeget to add email
          fbLoginBtn.setReadPermissions(Arrays.asList("basic_info","email"));
          // session state call back event
          fbLoginBtn.setSessionStatusCallback(new Session.StatusCallback()
          {

              @Override
              public void call(Session session, SessionState state, Exception exception) 
              {
                  if (session.isOpened())
                  {
                      Log.i(TAG,"Access Token"+ session.getAccessToken());
                      Request.executeMeRequestAsync(session, new Request.GraphUserCallback() 
                      {
                          @Override
                          public void onCompleted(GraphUser user,Response response)
                          {
                              if (user != null) 
                              { 
                                  Log.i(TAG,"User ID "+ user.getId());
                                  Log.i(TAG,"Email "+ user.asMap().get("email"));
                                  Login login = new Login(user.asMap().get("email").toString(), "facebookPass");
                                  logIn();
                              }
                          }
                      });
                  }

              }
          });
    }

     @Override
     public void onActivityResult(int requestCode, int resultCode, Intent data)
     {
         super.onActivityResult(requestCode, resultCode, data);
         Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
     }

     private void logIn() 
     {
         Intent mainPage = new Intent(this, MainPage.class);
         startActivity(mainPage);
     }

}

here is the manifest xml code:

<?xml version="1.0" encoding="utf-8"?>
<manifest package="com.shale.shaleapp"
    android:versionCode="1"
    android:versionName="1.0" xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.shale.activities.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.shale.activities.MainPage"
            android:label="@string/title_activity_main_page" >
        </activity>
        <meta-data android:value="@string/fb_app_id" android:name="com.facebook.sdk.ApplicationId"/>
        <activity android:label="@string/app_name" android:name="com.facebook.LoginActivity"></activity>
    </application>

</manifest>

and here is the logCat output:

05-06 06:25:01.618: E/AndroidRuntime(1690): FATAL EXCEPTION: main
05-06 06:25:01.618: E/AndroidRuntime(1690): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.shale.shaleapp/com.shale.activities.MainActivity}: java.lang.NullPointerException
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1983)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.os.Looper.loop(Looper.java:137)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread.main(ActivityThread.java:4745)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at java.lang.reflect.Method.invokeNative(Native Method)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at java.lang.reflect.Method.invoke(Method.java:511)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at dalvik.system.NativeStart.main(Native Method)
05-06 06:25:01.618: E/AndroidRuntime(1690): Caused by: java.lang.NullPointerException
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.content.ContextWrapper.getPackageName(ContextWrapper.java:127)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.content.ComponentName.<init>(ComponentName.java:75)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.content.Intent.<init>(Intent.java:3301)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at com.shale.activities.MainActivity.<init>(MainActivity.java:33)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at java.lang.Class.newInstanceImpl(Native Method)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at java.lang.Class.newInstance(Class.java:1319)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.Instrumentation.newActivity(Instrumentation.java:1053)
05-06 06:25:01.618: E/AndroidRuntime(1690):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1974)
05-06 06:25:01.618: E/AndroidRuntime(1690):     ... 11 more

It indicates that there is problem with the MainActivity, but I just can't find it. Thanks!!!

4

4 回答 4

4

在下面的代码行中,

    private Intent mainPage = new Intent(this, MainPage.class);

您甚至在启动活动之前尝试传递 MainActivity 的上下文(即 this)。因此,如果您希望它是全局的,则可以在 onCreate 之前声明意图并在 onCreate 中定义它,以便它获得适当的上下文来启动另一个活动。

于 2013-05-06T06:47:02.123 回答
4

这是因为

private Intent mainPage = new Intent(this, MainPage.class);

将其移至onCreate()

于 2013-05-06T06:34:42.120 回答
2

尚未调用构造函数,因此使用this将给出空指针异常。尽量不要初始化mainPage。相反,移动你的

Intent mainPage = new Intent(MainActivity.this, MainPage.class);

就在行前startActivity(mainPage);

于 2013-05-06T06:35:14.610 回答
1
private Intent mainPage;// before onCreate() inside activity class

在 onCreate()

mainPage = new Intent(MainActivity.this, MainPage.class);

你得到 NullPointerException 因为你在 onCreate(); 之前初始化了你的意图;

于 2013-05-06T06:38:35.633 回答