简体   繁体   English

从ArrayList获取自定义类

[英]Getting custom class from ArrayList

I am pretty new to Android, so please be gentle with me. 我对Android很新,所以请温柔地对待我。 I have a custom class that extends Object. 我有一个扩展Object的自定义类。 It is called Word and through the course of the app, certain Words are added to an ArrayList. 它被称为Word,并且通过应用程序的过程,某些单词被添加到ArrayList中。 At the end of the activity, this ArrayList is passed via an Intent to another activity. 在活动结束时,此ArrayList通过Intent传递给另一个活动。 In testing it, I just have it set up to take two Words and I know that they are both in the ArrayList before being passed to the new activity. 在测试它时,我只是设置了两个单词,我知道它们都是在传递给新活动之前都在ArrayList中。 When I get to the second activity, I have no problem accessing the ArrayList if I am only trying to get the 1st Word (ie [get(0)]). 当我进入第二个活动时,如果我只想获得第一个单词(即[get(0)]),我访问ArrayList没有问题。 The problem is that when I also try to get (1), it throws an exception: "java.lang.RuntimeException: Unable to start activity ComponentInfo{chase_crawford_69001.ltoj/chase_crawford_69001.ltoj.Finished}: java.lang.ClassCastException: java.lang.String cannot be cast to chase_crawford_69001.ltoj.Word" 问题是,当我也尝试获取(1)时,它会抛出异常:“java.lang.RuntimeException:无法启动活动ComponentInfo {chase_crawford_69001.ltoj / chase_crawford_69001.ltoj.Finished}:java.lang.ClassCastException:java .lang.String无法强制转换为chase_crawford_69001.ltoj.Word“

Here is what I have: 这是我有的:

public class Word extends Object implements Parcelable{
private String vocabWord;
private String definition;
private Boolean flagged = Boolean.FALSE;

public Word (String vocabWord, String definition) {
    this.vocabWord = vocabWord;
    this.definition = definition;}
public Word (String vocabWord){ //Used to make ten Language words so that all TextViews are full,
                                // but this will never be the correct answer.
    this.vocabWord = vocabWord;}

public String getVocabWord(){return vocabWord;}
public String getDefinition(){return definition;}
public Boolean getFlagged(){return flagged;}

public void setVocabWord(String vocabWord) {this.vocabWord = vocabWord;}
public void setDefinition(String definition) {this.definition = definition;}
public void setFlag(Boolean used){this.flagged = used;}

public int describeContents() {
    return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
    out.writeString(vocabWord);
    out.writeString(definition);
    out.writeValue(flagged);
  //  out.writeByte((byte) (flagged ? 1:0));//1 == TRUE, 0== FALSE
}

public static final Parcelable.Creator<Word> CREATOR
        = new Parcelable.Creator<Word>() {
    public Word createFromParcel(Parcel in) {
        return new Word(in);
    }

    public Word[] newArray(int size) {
        return new Word[size];
    }
};

private Word(Parcel in) {
    vocabWord = in.readString();
    definition = in.readString();
    flagged = in.readByte()!=0;//If not 0, flagged is true.
}

} from the 1st activity: 来自第一个活动:

ArrayList<Word> missedWords = new ArrayList<>(); //this was instantiated at the beginning of the activity

else {
        view.setText("Try Again!");
        view.setBackgroundColor(getResources().getColor(R.color.red));
        if (!missedWords.contains(correctWord)) {
            missedWords.add(correctWord);}

 public void FinalMessage(View view) {

    Intent toFinished = new Intent(this, Finished.class);
    missedWordsBundle.putParcelableArrayList("missedWords", missedWords);
    toFinished.putExtra("missedWordsList", missedWordsBundle);
    startActivity(toFinished);
}

the second activity: 第二项活动:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_finished);
    Intent words = getIntent();
    Bundle missedWordsBundle;
    ArrayList<Word> missedWords = new ArrayList();
    //missedWords = getIntent().getParcelableArrayListExtra("missedWords");
    missedWordsBundle = this.getIntent().getBundleExtra("missedWordsList");
    missedWords = missedWordsBundle.getParcelableArrayList("missedWords");


    MissedWords(missedWords);
}

public void MissedWords(ArrayList missedWords) {
    wordOne = (Word) missedWords.get(0);
    wordTwo = (Word) missedWords.get(1);

    String sWordOne = wordOne.getVocabWord();
    String sWordTwo = wordTwo.getVocabWord();
    TextView finished = (TextView) findViewById(R.id.finished);
    TextView finishedOne = (TextView) findViewById(R.id.finished1);
    String wrongList = sWordOne;// + " " +
    String wrongList1 =  sWordTwo;
    finished.setText(wrongList);
    finishedOne.setText(wrongList1);}

Would you please help me figure out why I am unable to get the second item from the ArrayList? 你能帮我弄清楚为什么我无法从ArrayList获得第二项吗? I have been struggling with this for a couple weeks now, and am about to pull my hair out. 我已经在这几个星期里一直在努力,我准备把头发拉出来。 I am sure that it is something simple that I am missing. 我确信这是我想念的简单事。 Thank You!!! 谢谢!!!

Here is the complete error trace: 这是完整的错误跟踪:

10-12 04:24:48.789 353-353/chase_crawford_69001.ltoj E/AndroidRuntime: FATAL EXCEPTION: main
                                                                           java.lang.RuntimeException: Unable to start activity        ComponentInfo{chase_crawford_69001.ltoj/chase_crawford_69001.ltoj.Finished}: java.lang.ClassCastException: java.lang.String cannot be cast to chase_crawford_69001.ltoj.Word
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2080)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2105)
                                                                           at android.app.ActivityThread.access$600(ActivityThread.java:133)
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1211)
                                                                           at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                           at android.os.Looper.loop(Looper.java:137)
                                                                           at android.app.ActivityThread.main(ActivityThread.java:4795)
                                                                           at java.lang.reflect.Method.invokeNative(Native Method)
                                                                           at java.lang.reflect.Method.invoke(Method.java:511)
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
                                                                           at dalvik.system.NativeStart.main(Native Method)
                                                                        Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to chase_crawford_69001.ltoj.Word
                                                                           at chase_crawford_69001.ltoj.Finished.missedWords(Finished.java:30)
                                                                           at chase_crawford_69001.ltoj.Finished.onCreate(Finished.java:25)
                                                                           at android.app.Activity.performCreate(Activity.java:5008)
                                                                           at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
                                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2044)
                                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2105) 
                                                                           at android.app.ActivityThread.access$600(ActivityThread.java:133) 
                                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1211) 
                                                                           at android.os.Handler.dispatchMessage(Handler.java:99) 
                                                                           at android.os.Looper.loop(Looper.java:137) 
                                                                           at android.app.ActivityThread.main(ActivityThread.java:4795) 
                                                                           at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                           at java.lang.reflect.Method.invoke(Method.java:511) 
                                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789) 
                                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556) 
                                                                           at dalvik.system.NativeStart.main(Native Method) 

Line 30 is:  wordTwo = missedWords.get(1);
Line 25 is: missedWords(missedWords);

First of all, you don't need to extends an Object if you create your own object model. 首先,如果您创建自己的对象模型,则不需要扩展Object。 So it will be like this 所以它会是这样的

public class Word {
    private String vocabWord;
    private String definition;
    private Boolean flagged = Boolean.FALSE;

    public Word(String vocabWord, String definition) {
        this.vocabWord = vocabWord;
        this.definition = definition;
    }

    public Word(String vocabWord) { //Used to make ten Language words so that all TextViews are full,
        // but this will never be the correct answer.
        this.vocabWord = vocabWord;
    }

    public String getVocabWord() {
        return vocabWord;
    }

    public String getDefinition() {
        return definition;
    }

    public Boolean getFlagged() {
        return flagged;
    }

    public void setVocabWord(String vocabWord) {
        this.vocabWord = vocabWord;
    }

    public void setDefinition(String definition) {
        this.definition = definition;
    }

    public void setFlag(Boolean used) {
        this.flagged = used;
    }

And then you can convert your ArrayList to String with Gson class like this 然后你可以像这样将你的ArrayList转换为带有Gson类的String

String stringList = new Gson().toJson(yourList);

Then put Extras to Intent 然后将Extras添加到Intent

intent.putExtra(EXTRA_KEY, stringList);

In second activity you can get your stringList and convert then it again to ArrayList 在第二个活动中,您可以获取stringList并将其转换为ArrayList

ArrayList<Word> list = new Gson().fromJson(br, new TypeToken<ArrayList<Word>>(){}.getType());

Note that it is bad practice and bad for performance, but is simply and short code 请注意,这是不好的做法,对性能不利,但只是简单的代码

First of all, as Hank Moody just said you don't need to extends from Object. 首先,正如Hank Moody刚才所说,你不需要从Object扩展。 Maybe your error could be in the method MissedWords (you should rename it as missedWords in order to follow Java code style) because your aren't defining the type of the arraylist and you need to casting. 也许你的错误可能出现在MissedWords方法中(你应该将它重命名为missWords以便遵循Java代码风格)因为你没有定义arraylist的类型而你需要进行转换。 If you refactor the method like this you won't need the casting anymore: 如果您重构这样的方法,则不再需要进行投射:

public void missedWords(ArrayList<Word> missedWords) {
    Word wordOne = missedWords.get(0);
    Word wordTwo = missedWords.get(1);

Also you need to know if there is a second word in missedWords (you couldn't have or even you could have none of them). 你还需要知道missWords中是否有第二个单词(你不能拥有,甚至你不能拥有它们)。 It's difficult to say if we don't know what you want to do exactly. 如果我们不知道你想要做什么,很难说。

The Parcel in and Parcel out methods do not match in type. Parcel in和Parcel out方法的类型不匹配。 Parcel in has: 包裹有:

flagged = in.readByte()!=0;

while Parcel out has: 而Parcel out有:

out.writeValue(flagged);

They need to both call the same type of method (Value or Byte) In the end the code that worked was: 他们需要同时调用相同类型的方法(值或字节)最后,有效的代码是:

out.writeByte((byte) (flagged ? 1:0));//1 == TRUE, 0== FALSE
flagged = in.readByte()!=0;//If not 0, flagged is true.

Thanks for your help everyone. 谢谢大家的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM