简体   繁体   English

我刚刚编写了我的第一个android应用程序,但3个小时后仍然无法正常工作

[英]I have just written my first android app, and after 3 hours it still doesn't work

I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess): 我刚刚开始在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);
    }
}

With the following error log: 带有以下错误日志:

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

I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours. 抱歉,如果我所包含的内容过多或太少,这是我的第一个问题,而且我已经搜索了3个小时。


Full Code: package com.ollieapps.helloworld; 完整代码: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: xml:
fragment: 分段:

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

Main: 主要:

<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" />

It seems you built your views inside fragment_main.xml and not activity_main.xml . 看来您是在fragment_main.xml而不是activity_main.xml中建立视图的。

When you first create a new android project, you have these files which are automatically created and opened: 首次创建新的android项目时,您会拥有以下这些文件,这些文件会自动创建并打开:

在此处输入图片说明

Then, when you begin, you add views (eg: a TextView) inside fragment_main.xml file. 然后,当您开始时,您可以在fragment_main.xml文件中添加视图(例如:TextView) Finally, you tried to do a basically event with this view inside your Activity , something like this: 最后,您尝试在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();
        }
    } 

You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout.. 您无法运行您的应用程序,或者有时您只有白屏,因为您尝试调用/显示的视图布局错误。

Solution: Move all your stuff inside onCreateView method into the Fragment class . 解决方案: 将onCreateView方法中的所有内容移到Fragment类中

As DoctororDrive said in his comment 正如DoctororDrive在他的评论中所说
Call views and do something in the related fragment and not the parent activity . 调用视图并在相关片段而不是父活动中执行某些操作


For example, in your case, these following lines: 例如,在您的情况下,以下几行:

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

might be inside your fragment because you created it in fragment_main.xml layout. 可能在您的片段中,因为您是在fragment_main.xml布局中创建的。 Then: 然后:

// 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
 if (pepBox.isChecked()) {

This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code). 这行代码由于NullPointerException而失败,因为已声明了 pepBox ,但pepBox对其进行初始化(因此在代码中此点为null )。

Here is its declaration line: 这是它的声明行:

TextView textView; CheckBox pepBox, cheeseBox;

And here is its initialization: 这是它的初始化:

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

The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null . 问题是(a)未调用此行,或(b) findViewById(R.id.checkBox1)返回null

If findViewByID is returning null then you probably want to refer to this question , which addresses exactly this issue. 如果findViewByID返回null那么您可能要引用此问题 ,它恰好解决了此问题。 Its "related questions", down the right-hand side, should also be helpful. 它右侧的“相关问题”也应有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我的Android应用程序无法在设备上运行 - My android app doesn't work on device 为什么我的服务不适用于Android? (我只想记录5秒钟的东西) - Why doesn't my Service work in Android? (I just want to log something ever 5 seconds) 第一次离开应用程序后,我的数据会保存,但第二次后,它不保存 - My data saves after I leave the app the first time, but after the second time, it doesn't save 我的 android 应用程序在手机上不起作用,但在模拟器上运行 - My android app doesn't work on phone and does work on emulator 为什么我的歌曲无法在我的Android应用中正常播放? - Why doesn't my song work in my android app? 注销 servlet 不起作用:注销后仍然可以看到姓氏和注销按钮 - Logout servlet doesn't work: first last name and logout button are still visible after logout 没有焦点时如何保持我的Android应用运行? - How do I keep my Android app running when it doesn't have focus? 我的Android应用程序不加载应用程序屏幕,只是将其跳过到主应用程序屏幕? - My android app doesn't load the app screen it just skips it to the main app screen? 为什么“保存”按钮在我的示例Android应用中不起作用 - Why Save Button doesn't work in my Sample Android App 为什么我的 API 和 JSON 应用程序在 Android Studio 中不起作用 - Why doesn't my API and JSON app work in Android Studio
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM