Display other data based on spinner selection

百般思念 提交于 2019-12-11 13:51:14

问题


I have an xml file where I am displaying the text from the first tag, treasure name, in a spinner for the user to select. Once selected, I need to be able to access the other data associated to the treasure name selected that is stored in the xml document (in data file stored on device). I've parsed through the xml file and store each item in a separate array list. When a user clicks on a button (Get Clue), I need to be able to display the first clue associated to that treasure. This project is due today by midnight, and this is the last piece I just can't seem to get. Any help would be greatly appreciated. I added code to try and do this:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
//import java.lang.reflect.Array;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.os.Bundle;
import android.app.Activity;
//import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PlayGeoTreasureActivity extends Activity implements OnItemSelectedListener {

    ArrayList<String> treasureList=new ArrayList<String>();
    ArrayList<String>clue1List=new ArrayList<String>();
    ArrayList<String> clue2List=new ArrayList<String>();
    ArrayList<String> clue3List=new ArrayList<String>();
    ArrayList<String> answerList=new ArrayList<String>();
    ArrayList<String> locationList=new ArrayList<String>();
    ArrayList<String> pointValueList=new ArrayList<String>();


    XmlPullParserFactory parser;
    XmlPullParser xpp;
    TextView selected;

    Spinner spinnerTreasures;
    //Spinner spinnerTreasures = new Spinner(this);

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

        spinnerTreasures = (Spinner)findViewById(R.id.treasuresSpinner);


        //get the xml file
        File filename = new File(getFilesDir(), "treasure.xml");

        //check to see if file exists.  If it does, read it.

    try {
        if(filename.exists())
        {       
            readXML(filename);
        }
        else
        {
            Toast.makeText(null, "File not Found", Toast.LENGTH_LONG).show();
        }  
        }catch (FileNotFoundException e) {
            //String errorMessage=(e.getMessage()==null)?"Message is Empty":e.getMessage();
            //Log.e("GeoTreasureGameLog",errorMessage);
            Log.e("GeoTreasureGameLog", (e.toString()));
            e.printStackTrace();
        } catch (XmlPullParserException e) {
            //String errMessage=(e.getMessage()==null)?"Message is Empty":e.getMessage();
            //Log.e("GeoTreasureGameLog",errMessage);
            Log.e("GeoTreasureGameLog", (e.toString()));
            e.printStackTrace();
        }

    }


    private void readXML(File filename) throws XmlPullParserException, FileNotFoundException {
        // pull parser to read xml file
                    parser = XmlPullParserFactory.newInstance();
                    xpp = parser.newPullParser();

                    // point the xml parser to file
                    xpp.setInput(new FileReader(filename)); 

                    // get start and end tags
                    int eventType = xpp.getEventType();

                    // set current tag
                    String currentTag="";

                    // current value of the tag's element

                    String currentElement="";

                    //int counter = 0;
                    try{
                    // parse the entire xml file until done
                    while (eventType != XmlPullParser.END_DOCUMENT)
                    { 
                        // look for start tags
                        if(eventType == XmlPullParser.START_TAG)
                        {
                            // get the name of the start tag
                            currentTag = xpp.getName();

                            if (currentTag.equals("TreasureName"))
                            {
                                currentElement = xpp.nextText();
                                treasureList.add(currentElement);
                            }
                                else if (currentTag.equals("ClueOne"))
                                {
                                    currentElement = xpp.nextText();
                                    clue1List.add(currentElement);
                                }
                                else if (currentTag.equals("ClueTwo"))
                                {
                                    currentElement = xpp.nextText();
                                    clue2List.add(currentElement);
                                }
                                else if (currentTag.equals("ClueThree"))
                                {
                                    currentElement = xpp.nextText();
                                    clue3List.add(currentElement);
                                }
                                else if (currentTag.equals("Answer"))
                                {
                                    currentElement = xpp.nextText();
                                    answerList.add(currentElement);
                                }
                                else if (currentTag.equals("TreasureLocation"))
                                {
                                    currentElement = xpp.nextText();
                                    locationList.add(currentElement);
                                }
                                else if (currentTag.equals("PointValue"))
                                {
                                    currentElement = xpp.nextText();
                                    pointValueList.add(currentElement);
                                }
                        }
                        eventType = xpp.next();
                        }
                    } catch (Exception e)

                    {
                        //Log.e("GeoTreasureGameLog", e.getMessage());
                        Log.e("GeoTreasureGameLog", (e.toString())); 

                    }

                    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item,treasureList);

                    selected=(TextView) findViewById(R.id.itemSelected);
                    spinnerTreasures.setOnItemSelectedListener(PlayGeoTreasureActivity.this);
                    spinnerTreasures.setAdapter(spinnerArrayAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.play_geo_treasure, menu);
        return true;
    }




@Override
    public void onItemSelected(AdapterView<?> parent,
            View v, int position, long id) {
        selected.setText(treasureList.get(position));
        int i=treasureList.indexOf(selected);
        clueOne=clue1List.get(i).toString();
        clueTwo=clue2List.get(i).toString();
        clueThree=clue3List.get(i).toString();
        Button getClue = (Button)findViewById(R.id.getClueBtn);
        getClue.setOnClickListener((OnClickListener) this);

        }
        public void OnClick(View v) throws IOException{
            int buttonClicks = 3;
            TextView clue1=(TextView)findViewById(R.id.clue1TxtView);
            TextView clue2 = (TextView)findViewById(R.id.clue2TextView);
            TextView clue3=(TextView)findViewById(R.id.clue3TextView);
            if (buttonClicks == 3){
                clue1.setText(clueOne);
                buttonClicks=2;
            }
            else if (buttonClicks==2){
                clue2.setText(clueTwo);
                buttonClicks=1;
            }
            else if (buttonClicks==1){
                clue3.setText(clueThree);
                buttonClicks=0;
            }
            else if (buttonClicks==0)
                Toast.makeText(getBaseContext(), "No more clues are available", Toast.LENGTH_LONG).show();

    }


    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        selected.setText("Please choose a treasure");

    }


}

Thanks to any input I can get!!!

Ok, I tried doing it this way, and am getting the error:

09-15 16:33:47.439: E/AndroidRuntime(1440): FATAL EXCEPTION: main
09-15 16:33:47.439: E/AndroidRuntime(1440): java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1
09-15 16:33:47.439: E/AndroidRuntime(1440):     at java.util.ArrayList.get(ArrayList.java:310)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at com.rasmussen.geotreasuresgame.PlayGeoTreasureActivity.onItemSelected(PlayGeoTreasureActivity.java:182)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.widget.AdapterView.fireOnSelected(AdapterView.java:892)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.widget.AdapterView.access$200(AdapterView.java:49)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:860)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.os.Handler.handleCallback(Handler.java:730)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.os.Handler.dispatchMessage(Handler.java:92)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.os.Looper.loop(Looper.java:137)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at android.app.ActivityThread.main(ActivityThread.java:5103)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at java.lang.reflect.Method.invokeNative(Native Method)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at java.lang.reflect.Method.invoke(Method.java:525)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-15 16:33:47.439: E/AndroidRuntime(1440):     at dalvik.system.NativeStart.main(Native Method)

回答1:


I ran into same Error (java.lang.ArrayIndexOutOfBoundsException: length=12; index=-1) with spinners too. In my case, I was trying to setAdapter on spinner outside the ui thread. After wrapping the related code inside runOnUiThread, the issue is solved.



来源:https://stackoverflow.com/questions/18917267/display-other-data-based-on-spinner-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!