我有一个通用基本活动,在onStart()
方法中有一些身份验证代码需要在每个Activity中执行。但是,如果我在我的一个真实活动中将其子类化,并尝试启动其中一个,我会得到一个NPE。
这是我正在使用的一些代码
public class Login extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
configureEventHandlers();
}
private void configureEventHandlers()
{
mLoginBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mLoginModel.setPassword(mPwdTxt.getText().toString());
mLoginModel.setUserName(mLoginTxt.getText().toString());
// Call the network
List<NameValuePair> paramTable = new ArrayList<NameValuePair>(2);
paramTable.add(new BasicNameValuePair("email", mLoginModel.getUserName()));
paramTable.add(new BasicNameValuePair("password", mLoginModel.getPassword()));
mSpinner = ProgressDialog.show(Login.this, "Working", "Logging in ..");
login(paramTable);
}
});
mClearBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
mLoginTxt.setText("");
mPwdTxt.setText("");
}
});
}
private void login(List<NameValuePair> paramTable) {
NetworkParams params = new NetworkParams();
params.setMethodName("ValidateLogin");
params.setUrl(UserContext.GLOBAL_IP);
params.setParams(paramTable);
ResponseHandler handler = new ResponseHandler() {
@Override
public void requestSucceded(NetworkResult result) {
parseResponseFromNetwork(result.getResponseMessage());
}
@Override
public void requestFailed(NetworkResult result) {
new AlertDialog.Builder(Login.this).setTitle("Attention").setMessage("Could not contact PPK's servers. " +
"This could be because of low signal strength. Please try later or contact support if " +
"the problem persists")
.setNeutralButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dlg, int sumthin) { // do nothing Ð it will close on its own
}
}
).show();
mSpinner.dismiss();
}
};
params.setHandler(handler);
NetworkAccessClass nac = new NetworkAccessClass();
nac.execute(params);
}
private void parseResponseFromNetwork(String responseMessage) {
try {
LoginXmlParser parser = new LoginXmlParser(mLoginModel);
AsyncXmlParserParams params = new AsyncXmlParserParams();
params.setHandler(parser);
params.setListener(new AsyncXmlListener() {
@Override
public void asyncXmlParsingCompleted(Object parsedObject) {
// Dismiss the "waiting" progress indicator _after_ the parsing
// the login xml. Avoids the delay between the pop up going away and Facility screen coming up.
mSpinner.dismiss();
mLoginModel = (LoginDataModel) parsedObject;
if(parsedObject == null || mLoginModel.getValid() == null) {
authFailed();
return;
}
if(((LoginDataModel) parsedObject).getValid()) {
// Works fine till here. The LoginDataModel object that I have looks okay
authSucceeded();
}
else
{
authFailed();
}
}
});
params.setRequestString(responseMessage);
AsyncXmlParser asyncParser = new AsyncXmlParser();
asyncParser.execute(params);
}
catch(Exception e) {
authFailed();
Log.i("PPKMobileChargeCaptureException",e.getMessage());
}
return;
}
private void authSucceeded() {
// Handle pushing facility screen
try {
Intent facilityLaunchIntent = new Intent(Login.this, FacilityScreen.class);
Login.this.startActivity(facilityLaunchIntent);
}
catch(Exception ex)
{
String stackTrace = ex.getStackTrace().toString();
}
}
}
public class FacilityScreen extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.facilityscreen);
configureListView();
configureEventHandlers();
configureContext();
}
@Override
protected void onStart()
{
super.onStart();
if(mFacilityModel == null || mFacilityModel.size() == 0 || mUserPrefModel == null || mUserPrefModel.isEmpty()) {
displayProgressIndicator();
getPreferences();
getFacilityList();
}
}
@Override
protected void onDestroy()
{
UserContext.clearUserPrefs();
super.onDestroy();
}
}
public class FacilityScreen extends PPKBaseActivity
{
// onCreate, onResume etc. **This doesn't work, NPE**
}
public class PPKBaseActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
@Override
protected void onStart()
{
if(!UserContext.isUserLoggedIn()) {
this.finish();
}
super.onStart();
}
@Override
protected void onResume()
{
super.onResume();
}
@Override
protected void onPause()
{
super.onPause();
}
@Override
protected void onStop()
{
super.onStop();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
@Override
protected void onRestart()
{
super.onRestart();
}
}
我错过了一些非常简单的事情吗?
谢谢,
的Teja。
编辑:添加了更多代码。还要提一下,FacilityScreen
的{{1}}方法中的断点根本没有被击中。
EDIT2:堆栈跟踪。 (不太熟悉Android + Eclipse,这需要什么?)
onCreate()
ex InvocationTargetException (id=830084855920)
cause RuntimeException (id=830085267584)
cause NullPointerException (id=830085217952)
detailMessage "Unable to instantiate activity ComponentInfo{com.PatientPoint.MCC/com.PatientPoint.MCC.FacilityScreen}: java.lang.NullPointerException" (id=830084938528)
stackState (id=830084989144)
stackTrace null
detailMessage null
stackState (id=830084855952)
stackTrace null
target RuntimeException (id=830085267584)
Thread [<3> main] (Suspended (exception RuntimeException))
ActivityThread.performLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2417
ActivityThread.handleLaunchActivity(ActivityThread$ActivityRecord, Intent) line: 2512
ActivityThread.access$2200(ActivityThread, ActivityThread$ActivityRecord, Intent) line: 119
ActivityThread$H.handleMessage(Message) line: 1863
ActivityThread$H(Handler).dispatchMessage(Message) line: 99
Looper.loop() line: 123
ActivityThread.main(String[]) line: 4363
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]
Method.invoke(Object, Object...) line: 521
ZygoteInit$MethodAndArgsCaller.run() line: 860
ZygoteInit.main(String[]) line: 618
NativeStart.main(String[]) line: not available [native method]
编辑3(最终):
非常感谢你的帮助!我的道歉,因为我已经发现我没有包含在源代码中的一行代码导致异常。带有行号的<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.PatientPoint.MCC"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Login"
android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".FacilityScreen"
android:label=""
android:theme="@android:style/Theme.NoTitleBar">
<intent-filter>
<action android:name="CATEGORY_ALTERNATIVE"></action>
</intent-filter>
</activity>
<uses-sdk android:minSdkVersion="4" />
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
输出帮助我缩小了范围。我的ex.printStackTrace()
课程中也有一个SharedPreferenceManager
负责这一切。再次道歉,谢谢你的时间!
答案 0 :(得分:0)
感谢您快速回复(也感谢您的耐心等待)。
您应该从
中删除.
(点)
<activity android:name=".FacilityScreen"
行,所以它看起来像
<activity android:name="FacilityScreen"
此外,如果您还想使用其他活动,则应在androidManifes.xml
文件中列出所有活动。
答案 1 :(得分:0)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.PatientPoint.MCC/com.PatientPoint.MCC.FacilityScreen}: java.lang.NullPointerException
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2417)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2512)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread.access$2200(ActivityThread.java:119)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1863)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.os.Handler.dispatchMessage(Handler.java:99)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.os.Looper.loop(Looper.java:123)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread.main(ActivityThread.java:4363)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at java.lang.reflect.Method.invokeNative(Native Method)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at java.lang.reflect.Method.invoke(Method.java:521)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at dalvik.system.NativeStart.main(Native Method)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): Caused by: java.lang.NullPointerException
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:146)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at com.PatientPoint.MCC.PPKBaseActivity.<init>(PPKBaseActivity.java:20)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at com.PatientPoint.MCC.FacilityScreen.<init>(FacilityScreen.java:54)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at java.lang.Class.newInstanceImpl(Native Method)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at java.lang.Class.newInstance(Class.java:1479)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2409)
04-21 19:25:11.646: ERROR/AndroidRuntime(339): ... 11 more
我的PPKBaseActivity
类中有一行代码如下:
SharedPreferences currentUserPrefs = getSharedPreferences(SHARED_PREFS_NAME, Context.MODE_PRIVATE);
由于某种原因导致NullPointerException
。我现在没有使用它,所以我删除了那行代码,它似乎有效。