Android编程:控制器类中的按钮侦听器异常

Posted

技术标签:

【中文标题】Android编程:控制器类中的按钮侦听器异常【英文标题】:Android programming : exception with button listener in controller class 【发布时间】:2017-08-26 02:50:27 【问题描述】:

我有一个活动和一个按钮,通过单击我想打开另一个活动。我想在我的控制器类中执行按钮单击事件,所以我使用

在我的 MainActivity.java 中

MainController mainController = new MainController(btn_secondpage);
btn_secondpage.setOnClickListener(mainController);

在 MainController 类中我使用了这些方法-

在 MainController 类中..

public MainController(Button btn_secondpage) 

    this.btn_secondpage=btn_secondpage;

    

@Override
public void onClick(View v) 
    Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
    startActivity(intent);


但是,每当我单击按钮时,都会打开一个对话框并显示我的应用程序已停止工作... 我正在使用eclipse mars2 我已经提供了我所有的类,xml,manifest.xml

    activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/layout_id"
    style="@style/AppTheme"
    android:layout_
    android:layout_
    android:focusable="false"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.MainActivity" >

    <Button
        android:id="@+id/btn_secondpage"
        android:layout_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Second page" />

</RelativeLayout>
    activity_second.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.testandroidproject.view.SecondActivity" >

    <TextView
        android:layout_
        android:layout_
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Welcome to second page" />

</RelativeLayout>
    MainActivity.java
package com.testandroidproject.view;

import com.example.testandroidproject.R;
import com.testandroidproject.controller.MainController;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity 

    public Button btn_secondpage;
    public static final String TAG = "abcd";
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Log.i(TAG, "inside oncreate");             // printing (1st)
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        MainController mainController = new MainController(btn_secondpage);
        btn_secondpage.setOnClickListener(mainController);

        //      onButtonClick();  // this is working properly
    

    ////////////// this method is working properly.......
    public void onButtonClick()
        btn_secondpage = (Button)findViewById(R.id.btn_secondpage);
        btn_secondpage.setOnClickListener(
                new OnClickListener() 

                    @Override
                    public void onClick(View v) 
                        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");   
                        startActivity(intent);

                    
                );
    

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

    SecondActivity.java
package com.testandroidproject.view;

import com.example.testandroidproject.R;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class SecondActivity extends Activity 

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    //  Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.second, 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);
    

    MainController.java
package com.testandroidproject.controller;

import android.app.Activity;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainController extends Activity implements OnClickListener 
    Button btn_secondpage;
    public static final String TAG = "abcd";

    public MainController(Button btn_secondpage) 
        this.btn_secondpage=btn_secondpage;
        Log.i(TAG, "inside mainController constructor"); // printing (2nd)
    

    @Override
    public void onClick(View v) 
        Log.i(TAG, "inside public void onClick before intent");                     // printing(3rd)
        Intent intent = new Intent("com.testandroidproject.view.SecondActivity");
        Log.i(TAG, "inside public void onClick after intent");                      // printing(4th)
        startActivity(intent);
        Log.i(TAG, "inside public void onClick after startActivity");               //  NOT printing

    


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

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.testandroidproject.view.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.testandroidproject.view.SecondActivity"
            android:label="@string/title_activity_second" >
            <intent-filter>
                <action android:name="com.testandroidproject.view.SecondActivity" />    

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

</manifest>
    日志猫
04-01 00:10:38.344: I/abcd(1764): inside oncreate
04-01 00:10:38.345: I/abcd(1764): inside mainController constructor
04-01 00:10:38.370: D/OpenGLRenderer(1764): Render dirty regions requested:     true
04-01 00:10:38.374: D/(1764): HostConnection::get() New Host Connection   established 0xa5f43380, tid 1764
04-01 00:10:38.375: D/Atlas(1764): Validating map...
04-01 00:10:38.399: D/(1764): HostConnection::get() New Host Connection established 0xad480dc0, tid 1780
04-01 00:10:38.401: I/OpenGLRenderer(1764): Initialized EGL, version 1.4
04-01 00:10:38.446: D/OpenGLRenderer(1764): Enabling debug mode 0
04-01 00:10:38.546: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:10:38.546: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:51.749: I/abcd(1764): inside oncreate
04-01 00:11:51.754: I/abcd(1764): inside mainController constructor
04-01 00:11:51.896: W/EGL_emulation(1764): eglSurfaceAttrib not implemented
04-01 00:11:51.896: W/OpenGLRenderer(1764): Failed to set EGL_SWAP_BEHAVIOR   on surface 0xa5f46240, error=EGL_SUCCESS
04-01 00:11:55.658: I/abcd(1764): inside public void onClick before intent
04-01 00:11:55.658: I/abcd(1764): inside public void onClick after intent
04-01 00:11:55.658: D/AndroidRuntime(1764): Shutting down VM
04-01 00:11:55.658: D/AndroidRuntime(1764): --------- beginning of crash
04-01 00:11:55.658: E/AndroidRuntime(1764): FATAL EXCEPTION: main
04-01 00:11:55.658: E/AndroidRuntime(1764): Process:   com.example.testandroidproject, PID: 1764
04-01 00:11:55.658: E/AndroidRuntime(1764): java.lang.NullPointerException:   Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
04-01 00:11:55.658: E/AndroidRuntime(1764):     at   android.app.Activity.startActivityForResult(Activity.java:3736)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android. app.Activity.startActivityForResult(Activity.java:3697)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:4007)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.Activity.startActivity(Activity.java:3975)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.testandroidproject.controller.MainController.onClick(MainController.java:24)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View.performClick(View.java:4756)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.view.View$PerformClick.run(View.java:19749)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.handleCallback(Handler.java:739)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Handler.dispatchMessage(Handler.java:95)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.os.Looper.loop(Looper.java:135)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at android.app.ActivityThread.main(ActivityThread.java:5221)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Native Method)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at java.lang.reflect.Method.invoke(Method.java:372)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.and  roid.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
04-01 00:11:55.658: E/AndroidRuntime(1764):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
04-01 00:11:55.857: I/art(1764): Background sticky concurrent mark sweep GC freed 2383(175KB) AllocSpace objects, 1(81KB) LOS objects, 29% free,    794KB/1135KB, paused 1.621ms total 150.498ms
04-01 00:12:09.406: I/Process(1764): Sending signal. PID: 1764 SIG: 9

enter image description here

【问题讨论】:

欢迎堆栈溢出!请向我们展示您的错误日志。 嗨,是的,我刚刚提供了我的 LogCat。请检查一下。 【参考方案1】:

onClick() 中的MainController 类中创建Intent 对象时是错误的,请使用此Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class); 进行更改

确保您的 MainController 不是 Activity 的子类,这会导致错误。因为现在你的activity不是Context的子类,所以不能调用startActivity()。要启动一个活动,请使用传递的 Button 的上下文

public class MainController implements OnClickListener
    //............
@Override
public void onClick(View v) 
    Intent intent = new Intent(btn_secondpage.getContext(), SecondActivity.class);
    btn_secondpage.getContext().startActivity(intent);

【讨论】:

非常感谢,这次运行正常。感谢您的时间和耐心。

以上是关于Android编程:控制器类中的按钮侦听器异常的主要内容,如果未能解决你的问题,请参考以下文章

获取存储在类中的异常对象时,Junit 测试失败,而不是抛出

Android中三种创建监听器的方法

由于在编辑器类中设置 onClick 侦听器时出现空指针异常,Android 应用程序崩溃

如何使用lambda表达式/缩短onclicklisteners android studio

在 Swift 中以编程方式设置动作监听器

单击android小部件按钮上的侦听器