简体   繁体   English

从菜单项调用方法时,Android应用程序崩溃

[英]Android app crashing on method call from menu item

I have a function called createGrid that crates a grid of buttons in a Gridlayout (code below), sets their listener and adds a custom layout called no_padding_button to each one. 我有一个调用的函数createGrid该包装箱中按钮的网格Gridlayout (下面的代码),将其监听器,并增加了所谓的no_padding_button每一个自定义布局。

after creating the grid, depending on what button(s) the user has clicked on I have another function called saveDesign that iterates through the gridlayout and returns the number of clicked buttons depending on their tag. 创建网格后,根据用户单击的按钮的不同,我还有另一个名为saveDesign函数,该函数可遍历gridlayout并根据其标签返回单击的按钮数。 I call saveDesign from a menu Item. 我从菜单项调用saveDesign

The problem is that as soon as I called the saveDesign method, the app crashes. 问题是,一旦我调用saveDesign方法,该应用程序就会崩溃。 The grid works fine, you click buttons, they change color and their tag changes but some reason trying to read through the gridlayout crashes the app. 网格工作正常,您单击按钮,它们会更改颜色,并且其标签也会更改,但是由于某些原因,试图通读gridlayout会使应用崩溃。

can you guys help me understand what the error in my code is? 你们可以帮助我了解代码中的错误是什么吗?

Thanks 谢谢

//method to create a new grid, the number of rows and columns come from the dialogue inside the activity and then passed to this function
void createGrid(final Context context, GridLayout gridLayout) {

    gridLayout.setColumnCount(totalColumns);    //set the number of rows of the gridlayout
    gridLayout.setRowCount(totalRows);          //set the number of columns of the grid layout

    //add the buttons and implement their listeners
    for (int i = 0; i < totalRows; i++) {
        for (int j = 0; j < totalColumns; j++) {
            Button button = new Button(context);
            //no padding
            button.setBackground(context.getResources().getDrawable(R.drawable.no_padding_button));
            //set the name of the button according to its position
            button.setText(Integer.toString(i) + "," + Integer.toString(j)+",");
            //hide the name, the user does not need to see this information at this moment
            button.setTextColor(View.INVISIBLE);

            //setting up the layout parameters for each button
            GridLayout.LayoutParams param = new GridLayout.LayoutParams();
            param.setMargins(0, 0, 0, 0);
            button.setLayoutParams(param);

            //button listener
            button.setOnClickListener(new View.OnClickListener() {
                boolean already_clicked = false;
                @Override
                public void onClick(View v) {

                    //on click, hide the button
                    Button button = (Button) v;
                    if(!already_clicked){
                    //change the color of the selected buttons as an indication
                    button.setBackgroundColor(context.getResources().getColor(R.color.selected_button));
                        button.setTag(1);
                        already_clicked =true;
                    }
                    else{
                        button.setBackgroundColor(context.getResources().getColor(R.color.unselected_button));
                        button.setTag(0);
                        already_clicked =false;
                    }
                }
            });

            gridLayout.addView(button);
        }
    }

    Toast.makeText(context, "Grid Created", Toast.LENGTH_SHORT).show();
}

saveDesing method: saveDesing方法:

public void saveDesign(){
    int temp=0;
    for (int i=0;i<gridLayout.getChildCount(); i++){
        Button childButton = (Button)gridLayout.getChildAt(i);
        if(childButton.getTag().toString() == "1"){
            temp++;
        }
    }
    Toast.makeText(this, Integer.toString(temp), Toast.LENGTH_SHORT).show();
}

the xml code of the activity holding the gridlayout: 持有gridlayout的活动的xml代码:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center">
    <HorizontalScrollView android:id="@+id/HorizontalScrollView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <GridLayout xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/gridLayout"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center">

        </GridLayout>
    </HorizontalScrollView>
</ScrollView>

UPDATE 1 the error log , i also tried string.equals("1") but i got the same error: UPDATE 1错误日志,我也尝试过string.equals(“ 1”),但是我得到了同样的错误:

E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: com.example.test.gridtest, PID: 3247
                  java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.Object.equals(java.lang.Object)' on a null object reference
                      at com.example.abtin.gridtest.MainActivity.saveDesign(MainActivity.java:85)
                      at com.example.abtin.gridtest.MainActivity.onOptionsItemSelected(MainActivity.java:109)
                      at android.app.Activity.onMenuItemSelected(Activity.java:3204)
                      at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:406)
                      at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:195)
                      at android.support.v7.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:103)
                      at android.support.v7.app.AppCompatDelegateImplV9.onMenuItemSelected(AppCompatDelegateImplV9.java:667)
                      at android.support.v7.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:810)
                      at android.support.v7.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:957)
                      at android.support.v7.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:947)
                      at android.support.v7.widget.ActionMenuView.invokeItem(ActionMenuView.java:616)
                      at android.support.v7.view.menu.ActionMenuItemView.onClick(ActionMenuItemView.java:153)
                      at android.view.View.performClick(View.java:5610)
                      at android.view.View$PerformClick.run(View.java:22260)
                      at android.os.Handler.handleCallback(Handler.java:751)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:154)
                      at android.app.ActivityThread.main(ActivityThread.java:6077)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

If you don't click on button, it haven't tag. 如果您不单击按钮,则它没有标记。 Therefore childButton.getTag() return null and toString crash your app. 因此,childButton.getTag()返回null,并且toString使您的应用程序崩溃。 So check in saveDesign() 因此,请检查saveDesign()

if(childButton.getTag() != null) {
    if(childButton.getTag().toString() == "1"){
        temp++;
    }
}

or set button tag when create button. 或在创建按钮时设置按钮标签。

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

相关问题 Android - 单击时菜单项崩溃(相机意图) - Android - Menu Item Crashing on Click (Camera Intent) Android 应用程序,从菜单项启动 tabActivity - Android app , Launching a tabActivity from menu Item Android应用程式的onActivityResult方法当机 - Android app crashing in onActivityResult method Android 应用程序在调用方法时崩溃。 该方法运行一些 if 语句并更改某些图像视图上的可绘制对象 - Android app crashing on call of a method. The method runs some if statements and changes the drawables on some imageviews Android:从NavigationMenu项中选择调用上下文菜单 - Android: Call to context menu from NavigationMenu item selected Android应用程序在线程中调用方法后崩溃? - Android App Crashing after calling method in a thread? Android:向 MainActvity 添加方法后应用程序崩溃 - Android: app crashing after adding a method to MainActvity 如果从微调框选择了项目,则来自类的Android Java调用方法 - Android Java call method from class if item is selected from spinner 防止应用崩溃的全局方法? - Global method to prevent app from crashing? 使用后台方法从我的片段中读取 json 后,我的 android studio 应用程序不断崩溃 - My android studio app keeps crashing after using a background method to read a json from my fragment
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM