我刚刚写了我的第一个Android应用程序,3个小时后仍然不起作用 [英] I have just written my first android app, and after 3 hours it still doesn't work

查看:167
本文介绍了我刚刚写了我的第一个Android应用程序,3个小时后仍然不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在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):进程:com.ollieapps.helloworld,PID:15210
04-07 17:45:30.897:E / AndroidRuntime(15210) :java.lang.IllegalStateException:无法执行活动的方法
04-07 17:45:30.897:E / AndroidRuntime(15210):在android.view.View $ 1.onClick(View.java:3823)
04-07 17:45:30.897:E / AndroidRuntime(15210):在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):在android.os.Handler.handleCallback (Handler.java:733)
04-07 17:45:30.897:E / AndroidRuntime(15210):在android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17 :45:30.897:E / AndroidRuntime(15210):在andro id.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897:E / AndroidRuntime(15210):在android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897:E / AndroidRuntime(15210):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):引起: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) view.View $ 1.onClick(View.java:3818)
04-07 17:45:30.897:E / AndroidRuntime(15210):... 9更多
04-07 17:45:30.897 :E / AndroidRuntime(15210):引起的:java.lang.NullPointerException:尝试调用虚拟的od'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更多

如果我已经包含了太多或太少的话,我很抱歉,这是我的第一个问题,我也已经搜索了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(菜单菜单){

//扩充菜单;如果存在,则会将项目添加到操作栏。
getMenuInflater()。inflate(R.menu.main,menu);
返回true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item){
//处理动作栏项点击此处。操作栏将
//自动处理Home / Up按钮上的点击,所以长
//在AndroidManifest.xml中指定父活动。
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
返回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);
}
}

/ **
*包含简单视图的占位符片段。
* /
public static class PlaceholderFragment extends Fragment {

public PlaceholderFragment(){
}

@Override
public查看onCreateView(LayoutInflater inflater,ViewGroup容器,
Bundle savedInstanceState){
查看rootView = inflater.inflate(R.layout.fragment_main,container,false);
返回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_horizo​​ntal_margin
android:paddingRight =@ dimen / activity_horizo​​ntal_margin
android:paddingTop =@ dimen / activity_vertical_margin
工具: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 =显示/>

< 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
工具:context =com.ollieapps.helloworld.MainActivity
工具:ignore =MergeRootFrame/>


解决方案

似乎你在 fragment_main .xml 而不是 activity_main.xml



当您首次创建一个新的Android项目时,您将有自动创建和打开的这些文件:





然后,当您开始时,您可以在 fragment_main.xml 文件中添加视图(例如:TextView)。最后,你试图在你的活动之内做一个基本的事件,就像这样:

  public class MainActivity extends Activity {

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

setContentView(R.layout.activity_main); //使用layout activity_main.xml

//您尝试在以前添加的视图(TextView)上设置一个简单的文本
TextView text =(TextView)findViewById(R.id.textView1) ;
text.setText(Simple Text); //这里有一个错误!

/ *
*您可以在屏幕上添加一个片段事务来添加PlaceholderFragment Fragment
* - 下面的snippnet将自动创建。
* /
if(savedInstanceState == null){
getSupportFragmentManager()。beginTransaction()
.add(R.id.container,new PlaceholderFragment())。commit );
}
}

您无法运行应用程序,有时您只能使用白色屏幕,因为您尝试调用/显示的视图进入错误的布局。


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


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

@覆盖
public View onCreateView(LayoutInflater inflater,ViewGroup容器,
Bundle savedInstanceState){

//使用显示的布局是fragment_main.xml
查看rootView = inflater.inflate(R.layout.fragment_main,container,false);

//在这里找到你的意见!
//不要忘记findViewById附加到膨胀视图rootView.findView ...
pepBox =(CheckBox)rootView.findViewById(R.id.checkBox1);
cheeseBox =(CheckBox)rootView.findViewById(R.id.checkBox2);
textView =(TextView)rootView.findViewById(R.id.textView1);

/ *
*在这里做一些事情:点击监听器,设置一个文本,检查一个框..
* /

return rootView;
}

/ *
*执行其他方法仍然在片段内
* /
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


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

  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.


Full Code: package 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:
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.

When you first create a new android project, you have these files which are automatically created and opened:

Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:

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.

As DoctororDrive said in his comment
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. 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

这篇关于我刚刚写了我的第一个Android应用程序,3个小时后仍然不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆