简体   繁体   English

Android通过按钮启动活动?

[英]Android start activity with button?

i keep getting a null pointer exception 我不断收到一个空指针异常

I have a problem about starting a new activity via using button. 我有一个关于通过使用按钮启动新活动的问题。

I already checked the previous questions related to mine problem, one of them is almost same but solutions didn't work out for me. 我已经检查了先前与地雷问题相关的问题,其中一个问题几乎相同,但解决方案对我而言并不奏效。 So here is my problem. 所以这是我的问题。

whenever i start the app it crashes. 每当我启动应用程序时,它就会崩溃。 i have a main class called MainActivity and new Activity called login 我有一个名为MainActivity的主类和一个名为login的新Activity

Main class 主班

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 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)

thanks in advance!!! 提前致谢!!!

EDIT---> MANIFEST 编辑--->清单

<?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 Layout 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>

Edited corrections with imports 编辑导入的更正

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;
        }
    }

}

Move this inside the onCreate method : 将其移动到onCreate方法中:

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

By using that line outside the method, you are referring to the instance of MainActivity before it is fully created. 通过在方法之外使用该行,您可以在完全创建MainActivity实例之前对其进行引用。

Since it looks like you are only using that intent once, you could even move that line inside the onClick method of the loginButton's OnClickListener, as suggested by InnocentKiller. 由于看起来您只使用了一次该意图,因此您甚至可以按照InnocentKiller的建议,将该行移动到loginButton的OnClickListener的onClick方法内。

Remove this line from top of your screen 从屏幕顶部删除此行

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

and put under the button click event. 并将其放置在按钮单击事件下。 So basically your code will something like this for MainActivity. 因此,基本上,您的代码对于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);
        }
    });
............
...........

}

You need an Intent! 您需要一个意图!

try: 尝试:

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

Your login class should also be named "Login" to serve the name convention 您的登录类也应命名为“ Login”以使用名称约定

And you need to add the new Login.class to your Manifest like 并且您需要将新的Login.class添加到清单中,例如

<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

Do you have the Login activity declared on your manifest as an activity 您是否在清单上将Login活动声明为一项活动?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM