Java 当我将MainActivity拆分为几个类时,Android应用程序崩溃

Java 当我将MainActivity拆分为几个类时,Android应用程序崩溃,java,android,android-studio,android-activity,Java,Android,Android Studio,Android Activity,我只是android开发的初学者。最近我正在开发一个应用程序,可以在其他单位之间转换单位。代码变得非常庞大&最终维护、查找、修复bug变得非常麻烦。因此,我尝试将MainActivity.java拆分为其他类,但现在应用程序不断崩溃。Android Studio可以构建和运行该项目,但它不再在我的设备上运行 MainActivity.java文件包含 package com.gazzali.spinitmeow; import android.support.v7.app.AppCompatA

我只是android开发的初学者。最近我正在开发一个应用程序,可以在其他单位之间转换单位。代码变得非常庞大&最终维护、查找、修复bug变得非常麻烦。因此,我尝试将MainActivity.java拆分为其他类,但现在应用程序不断崩溃。Android Studio可以构建和运行该项目,但它不再在我的设备上运行

MainActivity.java
文件包含

package com.gazzali.spinitmeow;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    Spinner spinnerMainChoice, spinnerInputChoice, spinnerOutputChoice;

    EditText getInputValueID;
    double inputValue;

    TextView outputValue;

    Button buttonConvert;

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

        /* ------------ Main code Starts Here ----------------*/

        /* Main conversion Type choice with Spinner (Drop Down menu)*/
        spinnerMainChoice = findViewById(R.id.spinnerIDMainChoice);
        // [IMPORTANT] Set Spinner Click Listener
        spinnerMainChoice.setOnItemSelectedListener(this);
        // Create an ArrayAdapter using the string array and a default spinner layout
        ArrayAdapter<CharSequence> adapterMainChoice = ArrayAdapter.createFromResource(this,
                R.array.MainChoices_array, android.R.layout.simple_spinner_item);
        // Specify the layout to use when the list of choices appears
        adapterMainChoice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        // Apply the adapter to the spinner
        spinnerMainChoice.setAdapter(adapterMainChoice);

        /* Input Conversion type choice with Spinner */
        spinnerInputChoice = findViewById(R.id.spinnerIDInputChoice);
        spinnerInputChoice.setOnItemSelectedListener(this);

        /* Output Conversion type choice with Spinner */

        spinnerOutputChoice = findViewById(R.id.spinnerIDOutputChoice);
        spinnerOutputChoice.setOnItemSelectedListener(this);

        /* for input and output fields */
        getInputValueID = findViewById(R.id.editTextIDInputValue);
        String inputValueString = getInputValueID.getText().toString();
        if(!TextUtils.isEmpty(inputValueString))
        {
            try
            {
                inputValue = Double.parseDouble(inputValueString);
            }
            catch (Exception e1)
            {
                e1.printStackTrace();
            }
        }
        outputValue = findViewById(R.id.textViewIDOutputValue);

    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        // An item was selected. retrieve the selected item
        String selectedMainChoice = parent.getItemAtPosition(pos).toString();
        Log.i("Selected", selectedMainChoice);
        //Toast.makeText(MainActivity.this, "Selected: " + selectedMainChoice, Toast.LENGTH_SHORT).show();

/* This is where I made the separation ; previously the contents inside the spinnerSelects's setInputOutSpinner()
        was inside the MainActivity as a method */

        spinnerSelects spinnerSelects = new spinnerSelects();
        spinnerSelects.setInputOutputSpinners(selectedMainChoice);

    }


    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        // Another interface callback
    }

}
Logcat显示了这些痕迹,这对我来说很陌生

2019-07-20 19:55:12.757 18958-18958/com.gazzali.spinitmeow E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.gazzali.spinitmeow, PID: 18958
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources android.content.Context.getResources()' on a null object reference
    at android.content.ContextWrapper.getResources(ContextWrapper.java:91)
    at android.view.ContextThemeWrapper.getResourcesInternal(ContextThemeWrapper.java:127)
    at android.view.ContextThemeWrapper.getResources(ContextThemeWrapper.java:121)
    at android.support.v7.app.AppCompatActivity.getResources(AppCompatActivity.java:543)
    at com.gazzali.spinitmeow.spinnerSelects.setInputOutputSpinners(spinnerSelects.java:13)
    at com.gazzali.spinitmeow.MainActivity.onItemSelected(MainActivity.java:83)
    at android.widget.AdapterView.fireOnSelected(AdapterView.java:944)
    at android.widget.AdapterView.dispatchOnItemSelected(AdapterView.java:933)
    at android.widget.AdapterView.access$300(AdapterView.java:53)
    at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:898)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:201)
    at android.app.ActivityThread.main(ActivityThread.java:6810)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
2019-07-20 19:55:12.787 18958-18958/com.gazzali.spinitmeow I/Process: Sending signal. PID: 18958 SIG: 9
位于com.gazzali.spinitmeow.spinnerSelects.setInputOutputSpinners(spinnerSelects.java:13) 在com.gazzali.spinitmeow.MainActivity.onItemSelected上(MainActivity.java:83)

这两条线有蓝色下划线,而其他线有红色下划线

有人能告诉我哪里需要修复bug,这样我的电脑就不会崩溃了吗?
提前感谢。

首先,您不应该在任何其他课程中扩展任何
活动。当您使用
Intent
启动时,Android系统将创建
Activity
类的实例。我们不应该使用其构造函数创建
活动
实例

spinnerSelects
类中,您尝试使用的
spinnerInputChoice
不是由Android系统创建的
MainActivity
实例的一部分。因为您在
中创建的
spinnerSelects
的实例已被选中
方法具有不同版本的extended
MainActivity

更新

检查以下各项是否可以解决您的问题:

  • spinnerSelects
    中删除
    MainActivity
    inheritense
  • onItemSelected
    中,通过构造函数在
    spinnerSelects
    中提供
    context
    。您可以使用它来
    getResources
  • setInputOutputSpinners
    方法的返回类型更改为
    ArrayAdapter
    ,然后返回创建的
    ArrayAdapter
    实例
  • onimselected
    方法中,将
    setInputOutputSpinner
    返回的适配器设置为spinner

  • 为了解决当前的NullPointerException问题

    将活动上下文传递给spinnerSelects所需的方法

    spinnerSelects.setInputOutputSpinners(MainActivity.this,selectedMainChoice);
    
    在此方法中,使用该活动获取资源

    protected void setInputOutputSpinners(Activity activity, String selectedMainChoice) {
            switch (selectedMainChoice)
            {
                case "Length": {
                    spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
                            android.R.layout.simple_spinner_dropdown_item,
                            activity.getResources().getStringArray(R.array.LengthChoices_array)));
    
                    spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
                            android.R.layout.simple_spinner_dropdown_item,
                            activity.getResources().getStringArray(R.array.LengthChoices_array)));
                }
                break;
    
    
            }
        }
    
    受保护的void setInputOutputSpinner(活动活动,字符串选择主选项){
    开关(selectedMainChoice)
    {
    案例“长度”:{
    spinnerInputChoice.setAdapter(新阵列适配器,
    android.R.layout.simple\u微调器\u下拉菜单\u项,
    activity.getResources().getStringArray(R.array.LengthChoices_数组));
    spinnerOutputChoice.setAdapter(新阵列适配器,
    android.R.layout.simple\u微调器\u下拉菜单\u项,
    activity.getResources().getStringArray(R.array.LengthChoices_数组));
    }
    打破
    }
    }
    
    希望它能解决你的问题,但在我看来,你的代码是 不好的。你可以改进它

    如果我的解决方案不起作用,请不要扩展MainActivity并保留 SpinnerSelect仅作为Java类,并传递
    spinnerInputChoice
    变量 到所需的类方法


    快乐编码

    使用Logcat检查与崩溃相关的堆栈跟踪:如果您不理解堆栈跟踪告诉您的内容,请编辑您的问题,并发布来自运行问题中代码版本的堆栈跟踪。我明白您的意思。那么,如何修改这些类呢?我试图使用构造函数,但他们正在创建更多problem@ArifHamim我不明白你的问题。但检查更新的答案是否解决了您的问题。
    spinnerSelects.setInputOutputSpinners(MainActivity.this,selectedMainChoice);
    
    protected void setInputOutputSpinners(Activity activity, String selectedMainChoice) {
            switch (selectedMainChoice)
            {
                case "Length": {
                    spinnerInputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
                            android.R.layout.simple_spinner_dropdown_item,
                            activity.getResources().getStringArray(R.array.LengthChoices_array)));
    
                    spinnerOutputChoice.setAdapter(new ArrayAdapter<CharSequence>(this,
                            android.R.layout.simple_spinner_dropdown_item,
                            activity.getResources().getStringArray(R.array.LengthChoices_array)));
                }
                break;
    
    
            }
        }