我刚刚编写了我的第一个Android应用程序,3小时后它仍然无效

时间:2014-04-07 16:10:04

标签: java android xml eclipse adt

我刚刚开始在Android应用程序中编写我的第一段代码,但是当我使用以下部分运行它时未注释它会崩溃(我告诉你的任何其他内容都是无用的猜测):

  public void onButton1Click(View v){
    if(v.getId() == R.id.button1){

        StringBuilder str = new StringBuilder("");
        if (pepBox.isChecked()) {
            str.append("Pepperoni"+" ");
        }
        if (cheeseBox.isChecked()) {
            str.append("Extra Cheese");
        }
        if (str.length() == 0) {
            str.append("Plain");
        }
        textView.setText(str);
    }
}

使用以下错误日志:

04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210):    at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210):    at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210):    ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210):    at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210):    ... 11 more

如果我包含太多或太少,我很抱歉,这是我的第一个问题,我已经搜索了3个小时。


完整代码:     包com.ollieapps.helloworld;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;

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

    pepBox = (CheckBox) findViewById(R.id.checkBox1);
    cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
    textView = (TextView) findViewById(R.id.textView1);


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

public void onButton1Click(View v){
    if(v.getId() == R.id.button1){

        StringBuilder str = new StringBuilder("");
        if (pepBox.isChecked()) {
            str.append("Pepperoni"+" ");
        }
        if (cheeseBox.isChecked()) {
            str.append("Extra Cheese");
        }
        if (str.length() == 0) {
            str.append("Plain");
        }
        textView.setText(str);
    }
}

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

}

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.ollieapps.helloworld.MainActivity$PlaceholderFragment" >

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:orientation="vertical" >

    <CheckBox
        android:id="@+id/checkBox1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Pepperoni" />

    <CheckBox
        android:id="@+id/checkBox2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="ExtraCheese" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="onButton1Click"
        android:text="Show" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Plain" />

</LinearLayout>

</RelativeLayout>

主:

<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="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />

2 个答案:

答案 0 :(得分:0)

您似乎在 fragment_main.xml 而非 activity_main.xml 中构建了视图。

当你第一次创建一个新的android项目时,你会自动创建和打开这些文件:

enter image description here

然后,当您开始时,在fragment_main.xml文件中添加视图(例如:TextView)。最后,您试图在Activity中使用此视图执行基本事件,如下所示:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main); // Using layout activity_main.xml

        // You try to set a simple text on the view (TextView) previously added
        TextView text = (TextView) findViewById(R.id.textView1);
        text.setText("Simple Text");  // And you get an error here!

        /*
         * You do an fragment transaction to add PlaceholderFragment Fragment
         * on screen - this below snippnet is automatically created.
        */
        if(savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new PlaceholderFragment()).commit();
        }
    } 

您无法运行自己的应用,或者有时只有白屏,因为您尝试调用/显示的视图布局错误。

  

解决方案:将onCreateView方法中的所有内容移动到Fragment类中。

正如 DoctororDrive 在评论中所说
调用视图并在相关片段中执行某些操作,而不是父活动


例如,在您的情况下,以下这些行:

pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);  

可能在您的片段中,因为您是在fragment_main.xml布局中创建的。然后:

// start fragment
public static class PlaceholderFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

        // Use the layout which is displayed it's fragment_main.xml
        View rootView = inflater.inflate(R.layout.fragment_main, container, false);

        // Find your views here!
        // Don't forget to findViewById attached to the inflated view "rootView.findView..."
        pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
        cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
        textView = (TextView) rootView.findViewById(R.id.textView1);

        /*
         * Do something here: click listener, set a text, check a box..
        */

        return rootView;
    }  

    /*
     * Perform other methods still inside the fragment
    */ 
    public void onButton1Click(View v){
        if(v.getId() == R.id.button1){

            StringBuilder str = new StringBuilder("");
            if (pepBox.isChecked()) {
                str.append("Pepperoni"+" ");
            }
            if (cheeseBox.isChecked()) {
                str.append("Extra Cheese");
            }
            if (str.length() == 0) {
                str.append("Plain");
            }
            textView.setText(str);
        }
    }
}
// end fragment

答案 1 :(得分:0)

 if (pepBox.isChecked()) {

由于NullPointerExceptiondeclared,这行代码失败,因为pepBoxthis question,但它没有按原样进行初始化(因此null就是TextView textView; CheckBox pepBox, cheeseBox; 码)。

这是其声明行:

pepBox = (CheckBox) findViewById(R.id.checkBox1);

这是它的初始化:

findViewById(R.id.checkBox1)

问题在于:(a)未调用此行,或(b)null正在返回findViewByID

如果null正在返回{{1}},那么您可能需要参考 {{3}} ,它正好解决了这个问题。右下方的“相关问题”也应该有所帮助。