Android应用在运行时在下拉列表选项上运行if语句时崩溃。

huangapple go评论78阅读模式
英文:

Android app crashing when running if statement on a spinner option

问题

我是一个初学者,正在使用Android Studio创建一个从API读取数据的应用程序。我试图让API根据两个微调器中选择的选项来过滤结果;一个选项用于电动汽车充电桩的类型,另一个选项用于显示结果的最大半径。当应用程序执行到“if (defaultCharger.equals("0"))”语句时突然崩溃。由于没有显示错误,我已经注释掉了不同部分的代码,看看哪个部分能够正常工作,似乎这部分是有问题的。此处的代码使得链接在未选择充电桩类型的情况下不会包括充电桩类型的过滤器。对于这个问题的任何帮助将不胜感激。

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Spinner;

public class results extends AppCompatActivity implements AdapterView.OnItemSelectedListener {

    String link, getLong, getLat;

    TextView newAddress, see, testResult;

    // 创建微调器选项
    Spinner dropdownone, dropdowntwo;
    String[] distance = {"更改半径(英里)", "1", "5", "10"};
    String[] chargeType = {"按充电桩类型过滤", "低于2kW", "高于2kW", "40kW及更高"};
    String defaultMiles, defaultCharger;

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

        // 文本链接返回主页并输入新地址
        newAddress = findViewById(R.id.newAddress);
        newAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                newAddress.setTextColor(getResources().getColorStateList(R.color.colorAccent));
                Intent intent = new Intent(results.this, home.class);
                startActivity(intent);
            }
        });

        // 获取经度和纬度
        home home = new home();
        if (home.status.equals("gps")) {
            getLong = home.gpsLong;
            getLat = home.gpsLat;
        } else if (home.status.equals("address")) {
            GeoLocation geoLocation = new GeoLocation();
            getLong = geoLocation.adLongitude;
            getLat = geoLocation.adLatitude;
        } else {
            getLong = "-5.926437";
            getLat = "54.607868";
        }

        // 微调器一 - 选择结果的半径
        dropdownone = findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(results.this,
                android.R.layout.simple_spinner_item, distance);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dropdownone.setAdapter(adapter);
        dropdownone.setOnItemSelectedListener(this);

        // 微调器二 - 选择充电桩类型
        dropdowntwo = findViewById(R.id.spinner2);
        ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(results.this,
                android.R.layout.simple_spinner_item, chargeType);

        adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        dropdowntwo.setAdapter(adapter2);
        dropdowntwo.setOnItemSelectedListener(this);

        // 检查是否正确返回值
        see = findViewById(R.id.textView6);
        see.setText(defaultMiles + " " + defaultCharger);

        // 创建链接
        if (defaultCharger.equals("0")) {
            link = "https://api.openchargemap.io/v3/poi/?output=json&amp;Latitude=" + getLat + "&amp;Longitude=" + getLong + "&amp;distance=" + defaultMiles + "&amp;distanceunit=miles&amp;maxresults=10&amp;compact=true&amp;verbose=false";
        } else {
            link = "https://api.openchargemap.io/v3/poi/?output=json&amp;Latitude=" + getLat + "&amp;Longitude=" + getLong + "&amp;distance=" + defaultMiles + "&amp;distanceunit=miles&amp;LevelID=" + defaultCharger + "&amp;maxresults=1&amp;compact=true&amp;verbose=false";
        }

        testResult = findViewById(R.id.testResult);
        testResult.setText(link);
    }

    @Override
    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (parent.getId()) {
            case R.id.spinner1:
                switch (position) {
                    case 0:
                        // 默认情况
                        defaultMiles = "0";
                        break;
                    case 1:
                        // 1 英里半径
                        defaultMiles = "1";
                        break;
                    case 2:
                        // 5 英里半径
                        defaultMiles = "5";
                        break;
                    case 3:
                        // 10 英里半径
                        defaultMiles = "10";
                        break;
                }
            case R.id.spinner2:
                switch (position) {
                    case 0:
                        // 默认无充电桩类型过滤
                        defaultCharger = "0";
                        break;
                    case 1:
                        // 类型 1 充电桩
                        defaultCharger = "1";
                        break;
                    case 2:
                        // 类型 2 充电桩
                        defaultCharger = "2";
                        break;
                    case 3:
                        // 类型 3 充电桩
                        defaultCharger = "3";
                        break;
                }
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {
        defaultMiles = "10";
        defaultCharger = "0";
    }
}
英文:

I am a beginner with Android Studio creating an app that will read from an API. I am trying to get the API to filter results using options chosen in two spinners; one option for a type of electric car charger and another for the max radius of results to be shown. The app suddenly crashes when it gets to the "if (defaultCharger.equals("0"))" statement. As there are no errors shown I have commented out different sections of code to see what works and this part seems to be the issue. This is here so the link will not include a filter for the charger type if one has not been chosen. Any help with this problem would be appreciated.

import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Spinner;
public class results extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
String link, getLong, getLat;
TextView newAddress, see, testResult;
//Create spinner options
Spinner dropdownone, dropdowntwo;
String[] distance = {&quot;Change the radius in miles&quot;, &quot;1&quot;, &quot;5&quot;, &quot;10&quot;};
String[] chargeType = {&quot;Filter by type of charger&quot;, &quot;Under 2kW&quot;, &quot;Over 2kW&quot;, &quot;40kW and higher&quot;};
String defaultMiles, defaultCharger;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
//text link to go back to home and enter a new address
newAddress = findViewById(R.id.newAddress);
newAddress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
newAddress.setTextColor(getResources().getColorStateList(R.color.colorAccent));
Intent intent = new Intent(results.this, home.class);
startActivity(intent);
}
});
//get longitude and latitude
home home = new home();
if (home.status.equals(&quot;gps&quot;)){
getLong = home.gpsLong;
getLat = home.gpsLat;
}
else if (home.status.equals(&quot;address&quot;)){
GeoLocation geoLocation = new GeoLocation();
getLong = geoLocation.adLongitude;
getLat = geoLocation.adLatitude;
}
else {
getLong = &quot;-5.926437&quot;;
getLat = &quot;54.607868&quot;;
}
//drop down one - choose radius of results
dropdownone = findViewById(R.id.spinner1);
ArrayAdapter&lt;String&gt; adapter = new ArrayAdapter&lt;String&gt;(results.this,
android.R.layout.simple_spinner_item,distance);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdownone.setAdapter(adapter);
dropdownone.setOnItemSelectedListener(this);
//drop down two - choose charger type
dropdowntwo = findViewById(R.id.spinner2);
ArrayAdapter&lt;String&gt; adapter2 = new ArrayAdapter&lt;String&gt;(results.this,
android.R.layout.simple_spinner_item,chargeType);
adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
dropdowntwo.setAdapter(adapter2);
dropdowntwo.setOnItemSelectedListener(this);
//see if correct values are being returned
see = findViewById(R.id.textView6);
see.setText(defaultMiles + &quot; &quot; + defaultCharger);
//create link
if (defaultCharger.equals(&quot;0&quot;)){
link = &quot;https://api.openchargemap.io/v3/poi/?output=json&amp;Latitude=&quot; + getLat + &quot;&amp;Longitude=&quot; + getLong + &quot;&amp;distance=&quot; + defaultMiles + &quot;&amp;distanceunit=miles&amp;maxresults=10&amp;compact=true&amp;verbose=false&quot;;
}
else {
link = &quot;https://api.openchargemap.io/v3/poi/?output=json&amp;Latitude=&quot; + getLat + &quot;&amp;Longitude=&quot; + getLong + &quot;&amp;distance=&quot; + defaultMiles + &quot;&amp;distanceunit=miles&amp;LevelID=&quot; + defaultCharger + &quot;&amp;maxresults=1&amp;compact=true&amp;verbose=false&quot;;
}
testResult = findViewById(R.id.testResult);
testResult.setText(link);
}
@Override
public void onItemSelected(AdapterView&lt;?&gt; parent, View v, int position, long id) {
switch (parent.getId()){
case R.id.spinner1:
switch (position) {
case 0:
// Create default if nothing is changed
defaultMiles = &quot;0&quot;;
break;
case 1:
// 1 mile radius
defaultMiles = &quot;1&quot;;
break;
case 2:
// 5 mile radius
defaultMiles = &quot;5&quot;;
break;
case 3:
// 10 mile radius
defaultMiles = &quot;10&quot;;
break;
}
case R.id.spinner2:
switch (position) {
case 0:
// Default for no charger filter
defaultCharger = &quot;0&quot;;
break;
case 1:
// Type 1 charger
defaultCharger = &quot;1&quot;;
break;
case 2:
// Type 2 charger
defaultCharger = &quot;2&quot;;
break;
case 3:
// Type 3 charger
defaultCharger = &quot;3&quot;;
break;
}
}
}
@Override
public void onNothingSelected(AdapterView&lt;?&gt; parent) {
defaultMiles = &quot;10&quot;;
defaultCharger = &quot;0&quot;;
}
}

答案1

得分: 1

你的 onCreate 方法中的 defaultCharger 字符串将会是 null,导致在尝试比较时出现空指针异常:if (defaultCharger.equals(&quot;0&quot;))

你可以通过在变量声明时为 defaultCharger 设置一个值,比如 &quot;&quot;,来防止这种情况发生:

String defaultCharger = &quot;&quot;;

或者通过交换 equals 语句的顺序来避免:

if (&quot;0&quot;.equals(defaultCharger))
英文:

Your defaultCharger String will be null in the onCreate method, causing a NullPointerException when trying to compare it : if (defaultCharger.equals(&quot;0&quot;)) .

You can prevent it by setting a value like "" for defaultCharger during variable declaration:

String defaultCharger = &quot;&quot;;

or by switching around the equals statement:

if (&quot;0&quot;.equals(defaultCharger))

huangapple
  • 本文由 发表于 2020年5月5日 18:05:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/61610554.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定