Выбранное значение Spinner не изменяется при выборе и продолжает оставаться нулевым - PullRequest
0 голосов
/ 02 апреля 2020

Прежде чем я начну, я просто хочу сказать вам, что я просматривал этот сайт и другие довольно давно, прежде чем я решил опубликовать это. Я провел свое исследование, проанализировал мой код и точно определил проблему. Я надеюсь, что вы могли бы просто помочь мне найти решение для него и сказать, почему это происходит.

Предполагается, что строковое значение 'carModel' инициализируется значением, которое выбирает пользователь, однако оно не в состоянии и когда проверяется на равенство во втором java классе, он говорит -

java .lang.NullPointerException: попытка вызвать виртуальный метод 'boolean java .lang.String.equalsIgnoreCase ( java .lang.String) 'для ссылки на пустой объект

То же самое происходит со значением' Zone 'строки. Я думаю, что-то не так в том, как я инициализировал значения

Основной класс

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
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 androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    ArrayList<String> SelectedOptions = new ArrayList<String>();
    public String CarMake, InsuranceComp;
    public String Zone;
    String CarModel;
    public double ATDper;
    public int YOM, YOPE, ZDepPer, NCB, ZDepAdd, OwnerDriv, PaidDriv, Passenger, CODisc;

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

        final EditText ZeroDep = findViewById(R.id.editText1);
        final EditText ZeroDepAdd = findViewById(R.id.editText2);
        final EditText CODiscount = findViewById(R.id.editText3);

        ZeroDep.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                ZDepPer = Integer.parseInt(ZeroDep.getText().toString().replace("%", ""));
                return false;
            }
        });

        ZeroDepAdd.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                ZeroDepAdd.getText().clear();
                ZDepAdd = Integer.parseInt(ZeroDepAdd.getText().toString().replace("%",""));
                return false;
            }
        });

        CODiscount.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int i, KeyEvent keyEvent) {
                CODisc = Integer.parseInt(CODiscount.getText().toString().replace("%", ""));
                return false;
            }
        });

        Button calcButton = findViewById(R.id.button);
        calcButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, output_Activity.class);
                startActivity(intent);
            }
        });


        Spinner carCompSpinner = findViewById(R.id.spinner1);
        final ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this, R.array.car_companies,
                android.R.layout.simple_spinner_item);
        adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        carCompSpinner.setAdapter(adapter1);
        carCompSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                CarMake = adapterView.getItemAtPosition(i).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });


        final Spinner carModSpinner = findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter2= ArrayAdapter.createFromResource(this, R.array.car_model,
                android.R.layout.simple_spinner_item);
        carModSpinner.setAdapter(adapter2);
        carModSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                **CarModel = carModSpinner.getItemAtPosition(i).toString();// carModel is not being initialised and is remaining as null
                Log.d("Calculator", CarModel);
            }**
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });

        final Spinner YOMSpinner = findViewById(R.id.spinner3);
        ArrayAdapter<CharSequence> adapter3= ArrayAdapter.createFromResource(this, R.array.year_of_manuf,
                android.R.layout.simple_spinner_item);
        YOMSpinner.setAdapter(adapter3);
        YOMSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                YOM = Integer.parseInt(YOMSpinner.getItemAtPosition(i).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner YOPESpinner = findViewById(R.id.spinner4);
        ArrayAdapter<CharSequence> adapter4= ArrayAdapter.createFromResource(this, R.array.year_of_pex,
                android.R.layout.simple_spinner_item);
        YOPESpinner.setAdapter(adapter4);
        YOPESpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                YOPE = Integer.parseInt(YOPESpinner.getItemAtPosition(i).toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner ZSpinner = findViewById(R.id.spinner5);
        ArrayAdapter<CharSequence> adapter5= ArrayAdapter.createFromResource(this, R.array.zone,
                android.R.layout.simple_spinner_item);
        ZSpinner.setAdapter(adapter5);
        ZSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            **@Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Zone = ZSpinner.getItemAtPosition(i).toString();
                Log.d("Calculator", Zone); //Here Zone is printed out perfectly in the logcat, however, the value does not change
            }**

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner NCBSpinner = findViewById(R.id.spinner9);
        ArrayAdapter<CharSequence> adapter9= ArrayAdapter.createFromResource(this, R.array.NCB,
                android.R.layout.simple_spinner_item);
        NCBSpinner.setAdapter(adapter9);
        NCBSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                NCB = Integer.parseInt(NCBSpinner.getItemAtPosition(i).toString().replace("%",""));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        final Spinner ATSpinner = findViewById(R.id.spinner10);
        ArrayAdapter<CharSequence> adapter10= ArrayAdapter.createFromResource(this, R.array.AntiTheft,
                android.R.layout.simple_spinner_item);
        ATSpinner.setAdapter(adapter10);
        ATSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                ATDper = Double.parseDouble(ATSpinner.getItemAtPosition(i).toString().replace("%",""));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner ODSpinner = findViewById(R.id.spinner15);
        ArrayAdapter<CharSequence> adapter15= ArrayAdapter.createFromResource(this, R.array.ownerDriv,
                android.R.layout.simple_spinner_item);
        ODSpinner.setAdapter(adapter15);
        ODSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                OwnerDriv = Integer.parseInt(ODSpinner.getItemAtPosition(i).toString().replace("%",""));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {}
        });
        final Spinner PDSpinner = findViewById(R.id.spinner16);
        ArrayAdapter<CharSequence> adapter16= ArrayAdapter.createFromResource(this, R.array.paidDriv,
                android.R.layout.simple_spinner_item);
        PDSpinner.setAdapter(adapter16);
        PDSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                PaidDriv = Integer.parseInt(PDSpinner.getItemAtPosition(i).toString().replace("%",""));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner PsngrSpinner = findViewById(R.id.spinner17);
        ArrayAdapter<CharSequence> adapter17= ArrayAdapter.createFromResource(this, R.array.passenger,
                android.R.layout.simple_spinner_item);
        PsngrSpinner.setAdapter(adapter17);
        PsngrSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Passenger = Integer.parseInt(PsngrSpinner.getItemAtPosition(i).toString().replace("%",""));
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
        final Spinner InsCompSpinner = findViewById(R.id.spinner19);
        ArrayAdapter<CharSequence> adapter19= ArrayAdapter.createFromResource(this, R.array.insuranceComp,
                android.R.layout.simple_spinner_item);
        InsCompSpinner.setAdapter(adapter19);
        InsCompSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                InsuranceComp = InsCompSpinner.getItemAtPosition(i).toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }
}

Часть, в которой возникает проблема, - это этот и другие подобные методы.

final Spinner carModSpinner = findViewById(R.id.spinner2);
        ArrayAdapter<CharSequence> adapter2= ArrayAdapter.createFromResource(this, R.array.car_model,
                android.R.layout.simple_spinner_item);
        carModSpinner.setAdapter(adapter2);
        carModSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                CarModel = carModSpinner.getItemAtPosition(i).toString();// carModel is not being initialised and is remaining as null
                Log.d("Calculator", ""+ adapterView.getItemAtPosition(i));
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) { }
        });

Второй класс

 if (CarModel.equalsIgnoreCase("City")){ //error occurs here as it says CarModel is null
            CC = 1200;
            switch(carAge){
                case 1: ExShowRoomPrice = 950000;
                    break;
                case 2: ExShowRoomPrice = 760000;
                    break;
                case 3: ExShowRoomPrice = 665000;
                    break;
                case 4: ExShowRoomPrice = 570000;
                    break;
                case 5: ExShowRoomPrice = 475000;
                    break;
                case 6: ExShowRoomPrice = 451250;
                    break;
                case 7: ExShowRoomPrice = 427500;
                    break;
                case 8: ExShowRoomPrice = 403750;
                    break;
                case 9: ExShowRoomPrice = 380000;
                    break;
                case 10: ExShowRoomPrice = 356250;
                    break;
            }
        }
        else if (CarModel.equalsIgnoreCase("Amaze")){ // and so on

Та же проблема возникает и при проверке зоны на равенство

if (CC<1000 && carAge < 5){
            if (Zone.equals("A")) IRDATariff = 3.127; //throws the same error as it says for carModel and says that it is a null reference
            if (Zone.equals("B")) IRDATariff = 3.039;
        }

Изменение значений видно в Logcat довольно четко

Logcat

D/Calculator: City
D/Calculator: A
D/Calculator: B
D/Calculator: BR-V
D/Calculator: Civic
D/Calculator: CRV
D/Calculator: Brio
D/Calculator: A

Как Zone и carModel могут быть нулевыми во втором классе, когда в logcat они выводятся в качестве своих значений?

...