Java 启动正常主活动时出错
我现在正在努力,因为我可以开始一个正常的Java 启动正常主活动时出错,java,android,nullpointerexception,Java,Android,Nullpointerexception,我现在正在努力,因为我可以开始一个正常的startActivity()。它总是给我这个错误: 尝试调用虚拟方法 'android.app.ActivityThread$ApplicationThread null对象上的android.app.ActivityThread.getApplicationThread() 参考文献 我从我的申请开始 欢迎活动: application.getUserFromDatabase(getApplicationContext(), username, pas
startActivity()
。它总是给我这个错误:
尝试调用虚拟方法
'android.app.ActivityThread$ApplicationThread
null对象上的android.app.ActivityThread.getApplicationThread()
参考文献
我从我的申请开始
欢迎活动:
application.getUserFromDatabase(getApplicationContext(), username, password);
应用程序:
public void getUserFromDatabase(Context context, String username, String password) {
//new GetFromDatabase().execute("getUser.php", "?username=" + username + "&password=" + password, this, context);
WelcomeActivity activity = new WelcomeActivity();
activity.startMainActivity();
}
AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.mydomain.app">
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
</activity>
<activity android:name=".WelcomeActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
必须对startActivity()使用意图 例如:
Intent intent = new Intent(this, WelcomeActivity.class);
startActivtiy(intent);
它肯定会导致空指针异常,因为您的
WelcomeActivity
尚未创建。您不能通过以下方式创建活动的新实例来启动活动:
WelcomeActivity activity = new WelcomeActivity();
您的活动需要从以下内容开始:
Intent welcome = new Intent(context, WelcomeActivity.class);
context.startActivtiy(welcome);
或者通过添加正确的意图过滤器,使活动由Android系统启动
您可以通过以下方式从应用程序开始活动:
// FLAG_ACTIVITY_NEW_TASK is required
// FLAG_ACTIVITY_CLEAR_TOP brings back to the top of the stack
Intent mainActivity = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainActivity);
尽管我认为您不应该通过应用程序启动活动。您需要仔细考虑您的设计,这样应用程序就没有活动连接。您能在欢迎活动中发布代码吗?请在WelcomeActivity=new WelcomeActivity()下提供更多关于代码的详细信息;activity.startMainActivity();里面的代码是什么startMainActivity@RishabhJain是的,请参阅我的编辑。除了下面@Farrokh Shahriari的答案外,您不能使用应用程序上下文启动活动。创建意图时,需要提供活动/服务上下文。
// FLAG_ACTIVITY_NEW_TASK is required
// FLAG_ACTIVITY_CLEAR_TOP brings back to the top of the stack
Intent mainActivity = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(mainActivity);