【问题标题】:Button to second activity crashes app on start第二个活动的按钮在启动时使应用程序崩溃
【发布时间】:2014-05-11 05:04:14
【问题描述】:

我整天都在尝试破解这个问题,阅读了很多帖子和教程等,我离解决它还有 0% 的距离。我认为更有经验的编码员很可能很容易破解它,所以发布它希望有人会纠正它,其他菜鸟会看到它。

我有一个简单的按钮 bagButton 按下时应该从 MainActivity 转换为 BagActivity

应用程序启动时它会停止,我从来没有机会看到它运行,更不用说按下按钮了。

当我取出这段代码时,应用程序运行良好(但显然没有转换):

    Button b = (Button)findViewById(R.id.buttonBag);
    b.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            Intent i = new Intent(MainActivity.this, BagActivity.class);
            startActivity(i);
        }
    });

更大的MainActivity.java代码是:

package nz.co.gamekeeper;

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


public class MainActivity extends ActionBarActivity {

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

        Button b = (Button)findViewById(R.id.buttonBag);
        b.setOnClickListener(new View.OnClickListener() {

            public void onClick(View v) {
                Intent i = new Intent(MainActivity.this, BagActivity.class);
                startActivity(i);
            }
        });


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

    @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输出如下:

05-11 16:45:02.494: I/Process(1437): Sending signal. PID: 1437 SIG: 9
05-11 16:46:12.599: D/AndroidRuntime(2028): Shutting down VM
05-11 16:46:12.599: W/dalvikvm(2028): threadid=1: thread exiting with uncaught exception (group=0x4182b2a0)
05-11 16:46:12.599: E/AndroidRuntime(2028): FATAL EXCEPTION: main
05-11 16:46:12.599: E/AndroidRuntime(2028): java.lang.RuntimeException: Unable to start activity ComponentInfo{nz.co.gamekeeper/nz.co.gamekeeper.MainActivity}: java.lang.NullPointerException
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread.access$700(ActivityThread.java:140)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.os.Handler.dispatchMessage(Handler.java:99)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.os.Looper.loop(Looper.java:137)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread.main(ActivityThread.java:4921)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at java.lang.reflect.Method.invokeNative(Native Method)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at java.lang.reflect.Method.invoke(Method.java:511)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at dalvik.system.NativeStart.main(Native Method)
05-11 16:46:12.599: E/AndroidRuntime(2028): Caused by: java.lang.NullPointerException
05-11 16:46:12.599: E/AndroidRuntime(2028):     at nz.co.gamekeeper.MainActivity.onCreate(MainActivity.java:35)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.Activity.performCreate(Activity.java:5206)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
05-11 16:46:12.599: E/AndroidRuntime(2028):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
05-11 16:46:12.599: E/AndroidRuntime(2028):     ... 11 more

XML 有两部分activity_main.xml:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="nz.co.gamekeeper.MainActivity"
    tools:ignore="MergeRootFrame" />

及其fragment_main.xml:

<LinearLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:baselineAligned="false"
    android:orientation="vertical"
    tools:context="nz.co.gamekeeper.MainActivity$PlaceholderFragment" >

        <TableRow
            android:id="@+id/tableRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" >

             <Button
                 android:id="@+id/buttonBag"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_bag" />

             <Button
                 android:id="@+id/buttonSeason"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_season" />

         </TableRow>

         <TableRow
             android:id="@+id/tableRow2"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1" >

             <Button
                 android:id="@+id/buttonMates"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_mates" />

             <Button
                 android:id="@+id/buttonBirds"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_birds" />

         </TableRow>

         <TableRow
             android:id="@+id/tableRow3"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1" >

             <Button
                 android:id="@+id/buttonSetup"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_setup" />

             <Button
                 android:id="@+id/buttonSync"
                 android:layout_width="wrap_content"
                 android:layout_height="wrap_content"
                 android:layout_weight="1"
                 android:text="@string/button_text_sync" />

         </TableRow>

         <TableRow
             android:id="@+id/tableRow4"
             android:layout_width="fill_parent"
             android:layout_height="wrap_content"
             android:layout_weight="1" >

            <Button
                android:id="@+id/buttonSpare1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_text_spare1" />

            <Button
                android:id="@+id/buttonSpare2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:text="@string/button_text_spare2" />

         </TableRow>

</LinearLayout>

我已经尝试清理它,重新启动 Eclipse,通过添加日志来更好地了解错误,尝试不同的 Intent args,确保清单没问题,再加上加载更多......

谁能说明我可能会尝试什么?

【问题讨论】:

    标签: android button android-activity


    【解决方案1】:

    问题在于Button 视图。 Button 视图仅在 Fragment layout 中而不在 MainActivity 布局中,但您正试图从 MainActivity 访问按钮。

    因此,您只能在Fragment 中访问按钮。

    将代码从MainActivity 移动到PlaceholderFragment,如下所示

     @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        // you can find the button here from the fragment layout
        Button b = (Button) rootView .findViewById(R.id.buttonBag);
        b.setOnClickListener(new View.OnClickListener() {
    
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), BagActivity.class);
                startActivity(i);
            }
        });
            return rootView;
        }
    

    【讨论】:

    • 非常感谢!我尝试将其添加到片段中,但我错过了 rootView .findViewById(..。MainActivity.this 出现错误(超出范围),但通过以下方式解决添加 v.getContext()
    • 很好。你也可以使用getActivity()。
    【解决方案2】:

    activity_main.xml 不包含 ID 为 @id/buttonBag 的视图,该视图位于 fragment_main.xml 中。当您尝试在MainActivity 中查找视图时,您会得到 NPE,因为您刚刚膨胀的布局中不存在该视图!您应该在onCreateView(...) 的PlaceholderFragment 中添加OnClickListener,如下所示:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
    
        Button button = (Button) rootView.findViewById(R.id.buttonBag);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), BagActivity.class);
                startActivity(i);
            }
        });
    
        return rootView;
    }
    

    【讨论】:

    • 干杯,感谢您的 cmets,他们帮了很多忙。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2021-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多