带按钮的Android启动活动?

时间:2014-02-18 16:06:06

标签: java android android-activity

我一直得到空指针异常

我在使用按钮启动新活动时遇到问题。

我已经检查了以前与我的问题相关的问题,其中一个问题几乎相同,但解决方案对我来说没有用。所以这是我的问题。

每当我启动应用程序时,它都会崩溃。 我有一个名为MainActivity的主类和名为login

的新Activity

主要课程

public class MainActivity extends Activity {

    Intent myIntent = new Intent(MainActivity.this, login.class);
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button loginButton  = (Button) findViewById(R.id.button_login);


        loginButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                startActivity(myIntent);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

logcat的

02-18 10:27:42.520    1098-1098/com.example.app E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.example.app, PID: 1098
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.app/com.example.app.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.app.MainActivity.onCreate(MainActivity.java:30)
            at android.app.Activity.performCreate(Activity.java:5231)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
            at android.app.ActivityThread.access$800(ActivityThread.java:135)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:136)
            at android.app.ActivityThread.main(ActivityThread.java:5017)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:515)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
            at dalvik.system.NativeStart.main(Native Method)

提前致谢!!!

EDIT --->清单

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.app" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.app.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.example.app.login"
            android:label="@string/title_activity_login" >
            <intent-filter>
                <action android:name="android.intent.action.LOGIN" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>
    </application>

</manifest>

MainActivity布局

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.app.MainActivity">

    //login Button
    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="Login"
        android:id="@+id/button_login"
        android:layout_marginBottom="160dp"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginLeft="23dp" />

    //high score button
    <Button
        android:layout_width="120dp"
        android:layout_height="wrap_content"
        android:text="high score"
        android:id="@+id/highScore"
        android:layout_alignTop="@+id/button_login"
        android:layout_toRightOf="@+id/button_login"
        android:layout_marginLeft="45dp" />

    //play Button
    <Button
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:text="Play"
        android:id="@+id/Play"
        android:layout_above="@+id/button_login"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="55dp" />
</RelativeLayout>

使用导入编辑更正

package com.example.app;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button loginButton  = (Button) findViewById(R.id.button_login);

//        if (savedInstanceState == null) {
//            getSupportFragmentManager().beginTransaction()
//                    .add(R.id.container, new PlaceholderFragment())
//                    .commit();
//        }

        loginButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent myIntent = new Intent(MainActivity.this, login.class);
                startActivity(myIntent);
            }
        });

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);
            return rootView;
        }
    }

}

4 个答案:

答案 0 :(得分:3)

在onCreate方法中移动它:

Intent myIntent = new Intent(MainActivity.this, login.class);

通过在方法外部使用该行,您将在完全创建之前引用MainActivity的实例。

由于看起来你只使用了一次这个意图,你甚至可以按照InnocentKiller的建议在loginButton的OnClickListener的onClick方法中移动该行。

答案 1 :(得分:1)

从屏幕顶部删除此行

Intent myIntent = new Intent(MainActivity.this, login.class);

并置于按钮点击事件下。所以基本上你的代码对MainActivity来说都是这样的。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button loginButton  = (Button) findViewById(R.id.button_login);


    loginButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {

    Intent myIntent = new Intent(MainActivity.this, login.class);
            startActivity(myIntent);
        }
    });
............
...........

}

答案 2 :(得分:0)

你需要一个意图!

尝试:

loginButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent myIntent = new Intent(MainActivity.this, Login.class);
            startActivity(myIntent);
        }
    });

您的登录类也应命名为“Login”以提供名称约定

你需要将新的Login.class添加到你的Manifest中,如

<activity
        android:name="com.example.yourapp.Login"
        android:label="@string/app_name" 

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity

答案 3 :(得分:0)

您是否已将清单上的Login活动声明为活动

  <activity
        android:name="com.examlpe.app.loginActivity"/>