Android - 后退按钮导致问题

Android - Back button causes problems

我正在尝试创建一个应用程序来跟踪用户访问过的国家/地区。从下拉微调器中 select 编辑一个国家,然后在文本字段中输入一个数字。下一个屏幕应按频率顺序显示访问次数最多的三个国家/地区。

第一次输入一个国家和频率它工作正常但是当你按下后退按钮然后select一个不同的国家并输入另一个频率时,问题就出现了,它没有将频率分配给正确的国家。

举个例子,如果你首先 select Austria and Times Visited as 5 然后按下它显示:

Austria       5
Wales         0
Switzerland   0

如果你按返回然后select比利时输入10,它显示

Denmark       10
Austria       5
Wales         0

第三次回去select卢森堡输入15就显示

Spain         15
Denmark       10
Austria       5

似乎 countryList 数组与微调器位置不同步,我不确定如何修复它,我们将不胜感激。

这是我尝试制作的第一个 android 应用程序,所以可能还有其他我不知道的错误。

谢谢

这是第一个activity:

package com.example.country;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;

import java.util.Collections;

public class Select extends AppCompatActivity {

ImageView flagChoiceView;
Spinner spinnerCountry;
ArrayAdapter<CharSequence> adapter;
public static Button next2;
int elementPosition;

//Declaring all objects of type country
country Austria = new country("Austria");
country Belgium = new country("Belgium");
country Denmark = new country("Denmark");
country England = new country("England");
country France = new country("France");
country Germany = new country("Germany");
country Ireland = new country("Ireland");
country Italy = new country("Italy");
country Luxembourg = new country("Luxembourg");
country Portugal = new country("Portugal");
country Spain = new country("Spain");
country Sweden = new country("Sweden");
country Switzerland = new country("Switzerland");
country Wales = new country("Wales");

//Creating an array of type country in preparation for sorting
country[] countryList = {Austria, Belgium, Denmark,England,France,
        Germany,Ireland,Italy,Luxembourg,Portugal,Spain,Sweden,Switzerland,Wales};

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    afterSecondClick();



    //Setting protocols for entering values into the text field
    final TextWatcher numberInput = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) { }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try{
                countryList[elementPosition].setFrequency(Integer.parseInt(s.toString()));
            }
            catch(NumberFormatException e)
            {
                countryList[elementPosition].setFrequency(0);
            }
        }

        @Override
        public void afterTextChanged(Editable s) { }
    };

    //Creating a listener for the input field
    EditText inputFrequency = (EditText)findViewById(R.id.inputFrequency);
    inputFrequency.addTextChangedListener(numberInput);

    //sortFunction(countryList);
    spinnerCountry = (Spinner)findViewById(R.id.dropdown);
    adapter = ArrayAdapter.createFromResource(this,R.array.country_list,android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCountry.setAdapter(adapter);
    spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {

            flagChoiceView = (ImageView) findViewById(R.id.flagChoice);

            elementPosition = position;
           switch(position)
           {
               case 0:

                   flagChoiceView.setImageResource(R.drawable.austriaflag);
               break;

               case 1:
                   flagChoiceView.setImageResource(R.drawable.belgiumflag);
                   break;

               case 2:
                   flagChoiceView.setImageResource(R.drawable.denmarkflag);
                   break;

               case 3:
                   flagChoiceView.setImageResource(R.drawable.englandflag);
                   break;

               case 4:
                   flagChoiceView.setImageResource(R.drawable.franceflag);
                   break;

               case 5:
                   flagChoiceView.setImageResource(R.drawable.germanflag);
                   break;

               case 6:
                   flagChoiceView.setImageResource(R.drawable.irelandflag);
                   elementPosition = position;
                   break;

               case 7:
                   flagChoiceView.setImageResource(R.drawable.italyflag);
                   break;

               case 8:
                   flagChoiceView.setImageResource(R.drawable.luxembourgeflag);
                   break;

               case 9:
                   flagChoiceView.setImageResource(R.drawable.portugalflag);
                   break;

               case 10:
                   flagChoiceView.setImageResource(R.drawable.spainflag);
                   break;

               case 11:
                   flagChoiceView.setImageResource(R.drawable.swedenflag);
                   break;

               case 12:
                   flagChoiceView.setImageResource(R.drawable.switzerlandflag);
                   break;

               case 13:
                   flagChoiceView.setImageResource(R.drawable.walesflag);
                   break;

               default:
                   flagChoiceView.setImageResource(R.drawable.austriaflag);
                   break;

           }

        }

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

        }
    });

}

//Linking the second activity to the third with a button click
public void afterSecondClick()
{
    next2 = (Button)findViewById(R.id.button);
    next2.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v){
                    sortFunction(countryList);



                    Intent proceedAgain = new Intent("com.example.country.Results");
                    proceedAgain.putExtra("firstCountry", countryList[13].getName());
                    proceedAgain.putExtra("secondCountry", countryList[12].getName());
                    proceedAgain.putExtra("thirdCountry", countryList[11].getName());
                    proceedAgain.putExtra("firstFrequency", countryList[13].getFrequency());
                    proceedAgain.putExtra("secondFrequency", countryList[12].getFrequency());
                    proceedAgain.putExtra("thirdFrequency", countryList[11].getFrequency());
                    startActivity(proceedAgain);
                    EditText inputFrequency=(EditText) findViewById(R.id.inputFrequency);
                    inputFrequency.setText("");



                }
            }
    );
}

//Declaring a new inner class known as country
private class country
{
    private String name;
    private int frequency;

    public country(String Name){
        this.name = Name;
        this.frequency = 0;
    }

    public country(){
        this.name = "";
        this.frequency = 0;
    }

    public void setFrequency(int freq){
        this.frequency = freq;
    }

    public int getFrequency(){
        return frequency;
    }

    public String getName(){
        return name;
    }
}

//Sorting algorithm from lowest frequency to highest
void sortFunction(country[] List){
    int count = 0;
    while(count < List.length){
        for(int n = 0; n < List.length - 1; n++){
            if(List[n].getFrequency() > List[n+1].getFrequency())
                swapFunction(List, n);
        }
        count++;
    }
}

//Counterpart Method to sortFunction
void swapFunction(country[] List, int m){
    country a, b, c;
    a = List[m];
    b = List[m+1];
    c = a;
    List[m+1] = c;
    List[m] = b;
}
}

这是第二个 activity:

package com.example.country;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.TextView;

public class Results extends AppCompatActivity

{
//Inflation of GUI and toolbar for the activity
@Override
protected void onCreate(Bundle savedInstanceState)

{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_results);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    Bundle extras = getIntent().getExtras();

    TextView countryOne = (TextView)findViewById(R.id.firstCountry);
    countryOne.setText(extras.getString("firstCountry"));

    TextView countryTwo = (TextView)findViewById(R.id.secondCountry);
    countryTwo.setText(extras.getString("secondCountry"));

    TextView countryThree = (TextView)findViewById(R.id.thirdCountry);
    countryThree.setText(extras.getString("thirdCountry"));

    TextView freqOne = (TextView)findViewById(R.id.firstFrequency);
    freqOne.setText(String.valueOf(extras.getInt("firstFrequency")));

    TextView freqTwo = (TextView)findViewById(R.id.secondFrequency);
    freqTwo.setText(String.valueOf(extras.getInt("secondFrequency")));

    TextView freqThree = (TextView)findViewById(R.id.thirdFrequency);
    freqThree.setText(String.valueOf(extras.getInt("thirdFrequency")));
}

}

数组的xml在这里:

<resources>
<string name="app_name">COUNTry</string>
<string name="action_settings">Settings</string>
<string name="appName">Welcome!</string>
<string name="nextButtonValue">NEXT</string>
<string name="title_activity_select">Select</string>
<string-array name="country_list">
    <item>Austria</item>
    <item>Belgium</item>
    <item>Denmark</item>
    <item>England</item>
    <item>France</item>
    <item>Germany</item>
    <item>Ireland</item>
    <item>Italy</item>
    <item>Luxembourg</item>
    <item>Portugal</item>
    <item>Spain</item>
    <item>Sweden</item>
    <item>Switzerland</item>

看看这是否有帮助

package com.example.country;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Select extends AppCompatActivity {
ImageView flagChoiceView;
Spinner spinnerCountry;
ArrayAdapter<CharSequence> adapter;
public static Button next2;

//Declaring all objects of type Country
List<Country> countries = Arrays.asList(
        new Country("Austria", R.drawable.austriaflag),
        new Country("Belgium", R.drawable.belgiumflag),
        new Country("Denmark", R.drawable.denmarkflag),
        new Country("England", R.drawable.englandflag),
        new Country("France", R.drawable.franceflag),
        new Country("Germany", R.drawable.germanflag),
        new Country("Ireland", R.drawable.irelandflag),
        new Country("Italy", R.drawable.italyflag),
        new Country("Luxembourg", R.drawable.luxembourgeflag),
        new Country("Portugal", R.drawable.portugalflag),
        new Country("Spain", R.drawable.spainflag),
        new Country("Sweden", R.drawable.swedenflag),
        new Country("Switzerland", R.drawable.switzerlandflag),
        new Country("Wales", R.drawable.walesflag)
);

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_select);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    afterSecondClick();

    //Setting protocols for entering values into the text field
    final TextWatcher numberInput = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            try {
                countries.get(spinnerCountry.getSelectedItemPosition()).setFrequency(Integer.parseInt(s.toString()));
            } catch (NumberFormatException e) {
                Toast.makeText(getParent(), s + " is not a number", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    };

    //Creating a listener for the input field
    EditText inputFrequency = (EditText) findViewById(R.id.inputFrequency);
    inputFrequency.addTextChangedListener(numberInput);

    //sortFunction(countryList);
    spinnerCountry = (Spinner) findViewById(R.id.dropdown);
    adapter = ArrayAdapter.createFromResource(this, R.array.country_list, android.R.layout.simple_spinner_item);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinnerCountry.setAdapter(adapter);
    spinnerCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, final int position, long id) {
            flagChoiceView = (ImageView) findViewById(R.id.flagChoice);
            flagChoiceView.setImageResource(countries.get(position).getFlag());
        }

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

}

//Linking the second activity to the third with a button click
public void afterSecondClick() {
    next2 = (Button) findViewById(R.id.button);
    next2.setOnClickListener(
            new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Collections.sort(countries, Country.sortByFrequency());
                    Intent proceedAgain = new Intent("com.example.Country.Results");
                    proceedAgain.putExtra("firstCountry", countries.get(countries.size() - 1).getName());
                    proceedAgain.putExtra("secondCountry", countries.get(countries.size() - 2).getName());
                    proceedAgain.putExtra("thirdCountry", countries.get(countries.size() - 3).getName());
                    proceedAgain.putExtra("firstFrequency", countries.get(countries.size() - 1).getFrequency());
                    proceedAgain.putExtra("secondFrequency", countries.get(countries.size() - 2).getFrequency());
                    proceedAgain.putExtra("thirdFrequency", countries.get(countries.size() - 3).getFrequency());
                    startActivity(proceedAgain);
                    EditText inputFrequency = (EditText) findViewById(R.id.inputFrequency);
                    inputFrequency.setText("");
                }
            }
    );
}

//Declaring a new inner class known as Country
private static class Country {
    private final String name;
    private int frequency;
    private final int flag;

    public Country(String Name, int flag) {
        this.name = Name;
        this.frequency = 0;
        this.flag = flag;
    }

    public void setFrequency(int freq) {
        this.frequency = freq;
    }

    public int getFrequency() {
        return frequency;
    }

    public String getName() {
        return name;
    }

    public int getFlag() {
        return flag;
    }

    public static Comparator<Country> sortByFrequency() {
        return new Comparator<Country>() {
            @Override
            public int compare(Country lhs, Country rhs) {
                return Integer.compare(lhs.getFrequency(), rhs.getFrequency());
            }
        };
    }
}

}

在你上面的例子中:

问题是当你select比利时时elementPosition为1,但是你已经对国家列表进行了排序,所以比利时在列表中在位置 0 而不是在 1。因此它会更新位置 1(国家/地区列表中的第二个)丹麦的频率。

要解决此问题,如果国家/地区的频率与给定的国家/地区名称(例如比利时)匹配,而不是国家/地区在微调器上的位置(因为微调器未排序且不匹配),则应修改该国家/地区的频率。

因此,一种方法是搜索列表中的每个国家/地区,如果它的名称与微调器匹配 selected 项目的名称(国家/地区名称,使用 .equals() 检查),然后更新其频率。


此外,您的代码还有另一个问题,如果您先输入文本值然后然后select国家更新将发送到错误的国家/地区。因此,您必须在按钮onClick 方法.

中的EditText 上执行任何操作( 更新频率

所以,解决方案代码应该是这样的:

在 afterSecondClick 方法内部 -> 在 onClick 方法内部 -> 在你的 R.id.button 按钮中:

排序前!!!(这一行前:sortFunction(countryList);

EditText ed = (EditText) findViewById(R.id.inputFrequency);


Spinner spinner = (Spinner)findViewById(R.id.dropdown);
String text = spinner.getSelectedItem().toString();


int count = 0;
while(count < countryList.length)
{
    if((countryList[count]).getName().equals(text))
    {
        try
        {
            countryList[count].setFrequency(Integer.parseInt(ed.toString()));
        }
        catch(NumberFormatException e)
        {
            countryList[count].setFrequency(0);
        }
    }
    count++;
}

时间复杂度为O(n)。您的排序算法的时间复杂度为 O(n^2),因此它不会对速度产生太大影响。此外,对于一些国家(大约 100 个)来说,它可以被认为是快速的。也尝试使用 Quicksort 作为您的排序算法以提高速度(但对于少数国家来说仍然可以,因为您现在拥有它)

并且从 EditText 中删除 TextWatcher

只是你将被添加到 MainActivity.java 文件中 添加这个

@Override
public void invokeDefaultOnBackPressed() {
    moveTaskToBack(true);
}