문제

I've been trying to crack this all day reading many many posts and tutorials etc and I'm 0% closer to solving it. I think theres a high chance of a more experienced coder cracking it easily so posting it in the hope someone will correct it and other noobs will see it.

I have a simple button bagButton that when pressed should transition from MainActivity to BagActivity

On launch of the app it stops and I never get a chance to see it run let alone press the button.

When I take out this code the app runs fine (but obviously does not transition):

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

The greater MainActivity.java code is:

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

    }

}

The logcat output is as follows:

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

The XML has two parts 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" />

And its 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>

I've tried cleaning it, restarting Eclipse, getting a better idea of the error by adding logs, trying different Intent args, making sure manifest is ok, plus loads more...

Can anyone shed light on what I might try?

도움이 되었습니까?

해결책

Issue is with the Button view. You have the Button view only in the Fragment layout not in the MainActivity Layout, but you are trying to access the button from MainActivity.

So, you can access the Button only in Fragment.

Move the code from MainActivity to PlaceholderFragment like below

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

다른 팁

activity_main.xml does not contain a view with the id @id/buttonBag, that view is in fragment_main.xml. When you try to find the view in the MainActivity, you get a NPE because that view doesn't exist in the layout you just inflated! You should add the OnClickListener in onCreateView(...) of PlaceholderFragment, like so:

@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;
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top