按钮导致应用程序在启动时崩溃

时间:2014-06-20 08:10:08

标签: java android button android-fragmentactivity

当我启动我的应用程序时,它立即崩溃读取logcat我可以看到它是由我的mainActivity中的sendButton引起的,从阅读周围我可以说它与按钮没有被启动但是我可以看到它是,我在我的fragment_main.xml中声明它没有好,没有MainActivity.java中的按钮代码我的代码加载应用程序宏。任何帮助都会非常感激。

logcat的

06-20 08:50:18.323: E/AndroidRuntime(30036): FATAL EXCEPTION: main
06-20 08:50:18.323: E/AndroidRuntime(30036): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.draco.dragonmessage/com.draco.dragonmessage.MainActivity}: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2483)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2535)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread.access$600(ActivityThread.java:178)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1390)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.os.Handler.dispatchMessage(Handler.java:107)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.os.Looper.loop(Looper.java:194)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread.main(ActivityThread.java:5560)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at java.lang.reflect.Method.invokeNative(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at java.lang.reflect.Method.invoke(Method.java:525)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:611)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at dalvik.system.NativeStart.main(Native Method)
06-20 08:50:18.323: E/AndroidRuntime(30036): Caused by: java.lang.NullPointerException
06-20 08:50:18.323: E/AndroidRuntime(30036):    at com.draco.dragonmessage.MainActivity.onCreate(MainActivity.java:48)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.Activity.performCreate(Activity.java:5135)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1151)
06-20 08:50:18.323: E/AndroidRuntime(30036):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2437)
06-20 08:50:18.323: E/AndroidRuntime(30036):    ... 11 more

MainActivity.java

package com.draco.dragonmessage;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Dialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import android.widget.Button;
import android.widget.TextView;
import android.widget.EditText;

public class MainActivity extends Activity
    implements NavigationDrawerFragment.NavigationDrawerCallbacks {

/**
 * Fragment managing the behaviors, interactions and presentation of the navigation drawer.
 */
private NavigationDrawerFragment mNavigationDrawerFragment;

/**
 * Used to store the last screen title. For use in {@link #restoreActionBar()}.
 */
private CharSequence mTitle;
String sendMessageString = "";

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

    mNavigationDrawerFragment = (NavigationDrawerFragment)
            getFragmentManager().findFragmentById(R.id.navigation_drawer);
    mTitle = getTitle();

    // Set up the drawer.
    mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
            (DrawerLayout) findViewById(R.id.drawer_layout));

   final Button sendMessage = (Button) findViewById(R.id.messageButton); 
   System.out.println(sendMessage.toString());
        sendMessage.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View view) {
            final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
            final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);
            sendMessageString = messageToSend.toString();
            receivedMessage.setText(sendMessageString);
        }
    });

}

@Override
public void onNavigationDrawerItemSelected(int position) {
    // update the main content by replacing fragments
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction()
            .replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
            .commit();
}

public void onSectionAttached(int number) {
    switch (number) {
        case 1:
            mTitle = getString(R.string.title_section1);
            break;
        case 2:
            mTitle = getString(R.string.title_section2);
            break;
        case 3:
            mTitle = getString(R.string.title_section3);
            break;
    }
}

public void restoreActionBar() {
    ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);
    actionBar.setTitle(mTitle);
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    if (!mNavigationDrawerFragment.isDrawerOpen()) {
        // Only show items in the action bar relevant to this screen
        // if the drawer is not showing. Otherwise, let the drawer
        // decide what to show in the action bar.
        getMenuInflater().inflate(R.menu.main, menu);
        restoreActionBar();
        return true;
    }
    return super.onCreateOptionsMenu(menu);
}

@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 {
    /**
     * The fragment argument representing the section number for this
     * fragment.
     */
    private static final String ARG_SECTION_NUMBER = "section_number";

    /**
     * Returns a new instance of this fragment for the given section
     * number.
     */
    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        TextView textView = (TextView) rootView.findViewById(R.id.section_label);
        textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
        return rootView;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(
                getArguments().getInt(ARG_SECTION_NUMBER));
    }
}

}

fragment_main.xml

<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: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.draco.dragonmessage.MainActivity$PlaceholderFragment" >

<TextView
    android:id="@+id/section_label"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

<EditText
    android:id="@+id/editTextSend"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/section_label"
    android:layout_alignParentBottom="true"
    android:ems="10"
    android:hint="Enter message to send..." />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/section_label"
    android:layout_alignTop="@+id/textReceived"
    android:text="Keith"
    android:textSize="20sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/textReceived"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/section_label"
    android:layout_alignRight="@+id/editTextSend"
    android:text="Medium Text"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/messageButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/editTextSend"
    android:layout_alignParentRight="true"
    android:layout_marginRight="31dp"
    android:text="Button" />

</RelativeLayout>

activity_main.xml中

<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.draco.dragonmessage.MainActivity" >

<!--
     As the main content view, the view below consumes the entire
     space available using match_parent in both dimensions.
-->

<FrameLayout
    android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<!--
     android:layout_gravity="start" tells DrawerLayout to treat
     this as a sliding drawer on the left side for left-to-right
     languages and on the right side for right-to-left languages.
     If you're not building against API 17 or higher, use
     android:layout_gravity="left" instead.
-->
<!--
     The drawer is given a fixed width in dp and extends the full height of
     the container.
-->

<fragment
    android:id="@+id/navigation_drawer"
    android:name="com.draco.dragonmessage.NavigationDrawerFragment"
    android:layout_width="@dimen/navigation_drawer_width"
    android:layout_height="match_parent"
    android:layout_gravity="start" />



</android.support.v4.widget.DrawerLayout>

再次感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

只需将以下行移至Oncreate()并将R.layout更改为您的片段布局。您使用了错误的布局

final TextView receivedMessage = (TextView) findViewById(R.id.textReceived);
 final EditText messageToSend = (EditText) findViewById(R.id.editTextSend);

低于这个

final Button sendMessage = (Button) findViewById(R.id.messageButton); 

答案 1 :(得分:0)

带有ID messageButton 的按钮位于fragment_main.xml中。使用findByViewById(),您可以访问activity_main.xml(setContentView(R.layout.activity_main);

您可以向类添加属性Button,并在PlaceholderFragment的onCreateView方法中链接该元素。然后,您可以从活动中的任何位置访问此按钮。