Android - 后退按钮会导致问题

时间:2016-03-23 15:01:32

标签: java android arrays android-spinner

我正在尝试创建一个跟踪用户访问过的国家/地区的应用。从下拉微调器中选择一个国家/地区,然后将一个数字输入到文本字段中。下一个屏幕应显示按频率顺序访问的前三个国家。

第一次输入国家/地区和频率时工作正常但是当您按下后退按钮然后选择其他国家/地区并输入其他频率时会出现问题,它不会将频率指定给正确的国家/地区。

举个例子,如果你首先选择奥地利和时间访问为5,然后按下它显示:

Austria       5
Wales         0
Switzerland   0

如果按后退然后选择比利时并输入10,则显示

Denmark       10
Austria       5
Wales         0

如果你第三次回去并选择卢森堡并输入15,则显示

Spain         15
Denmark       10
Austria       5

似乎countryList数组从微调器位置变得不同步,我不知道如何修复它,任何帮助都会非常感激。

这是我试图制作的第一个Android应用程序,因此可能存在其他我不知道的错误。

由于

这是第一项活动:

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;
}
}

这是第二项活动:

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>

3 个答案:

答案 0 :(得分:1)

在上面的示例中:

问题是,当您选择比利时时, elementPosition为1,但您已对国家/地区列表进行了排序,因此列表中的比利时位于0位而非1位。因此,它更新了位于第1位的丹麦的频率(国家列表中的第二位)。

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

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

此外,您的代码还有另一个问题,如果您首先输入文字值然后选择国家/地区更新将转到错误的国家< / strong>即可。因此,您必须在按钮 onClick方法的EditText上执行任何操作(更新频率)。

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

在afterSecondClick方法中 - &gt;在onClick方法中 - &gt;在你的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

答案 1 :(得分:0)

看看这是否有帮助

mvn groupId:lib groupId:build

}

答案 2 :(得分:0)

您将在MainActivity.java文件中添加此内容

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