TypedArray和Enums

时间:2015-07-01 12:10:25

标签: java android typed-arrays

我试图创建我的第一个Android应用程序,现在我遇到了设计问题。我正在制作一个笑话应用程序(所有的笑话都要离线存储),我不知道如何处理笑话然后检索它们。我发现了TypedArrays,这看起来是个好主意,但我的Joke类包含枚举,而且我不确定是否可以从TypedArray设置枚举。

jokes.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="texts">
    <item>Sure, white people can't say the "n word" but, atleast we can say phrases like,"Thanks for the warning, Officer" and, "Hey, Dad."</item>
    <item>I cheated on my girlfriend once. I was playing monopoly and I took some money from the bank when she wasn't looking.
        Then I went upstairs and fucked her sister.</item>
    <item>'Yo Momma' jokes are old and worn out. Just like… Yo Momma.</item>
</array>
<array name="category">
    <item>OFFENSIVE</item>
    <item>ANTIJOKES</item>
    <item>YO_MOMMA</item>
</array>
<array name="length">
    <item>SHORT</item>
    <item>MEDIUM</item>
    <item>SHORT</item>
</array>

</resources>

Joke.java

    //TODO add more joke categories
private enum CATEGORY{OFFENSIVE,YO_MAMMA,ANTIJOKES}
public enum LENGTH{SHORT,MEDIUM,LONG}
private String mText;
//I'm not sure about this one, is just a placeholder for the audio file of the joke
private File mAudioFile;
private CATEGORY mCategory;
private LENGTH mLength;



public Joke(String text,CATEGORY category,LENGTH length){
    mText = text;
    mCategory = category;
    mLength = length;
}

MainActivity.java

public Joke getJoke(int index){
    Resources resources = getResources();
    TypedArray text = resources.obtainTypedArray(R.array.texts);
    TypedArray category = resources.obtainTypedArray(R.array.category);
    TypedArray length = resources.obtainTypedArray(R.array.length);

    Joke joke = new Joke(text,category,length);
}

我愿意以另一种方式提出建议。

1 个答案:

答案 0 :(得分:0)

我建议使用JSON。您可以将您的笑话作为JSON存储在文件中,并使用Gson将Jokes解组为POJO。此外,您应该将File mAudioFile更改为String mAudioFile并按名称检测音频文件,以避免JSON编组/解组问题。

<强>更新 您的POJO可能如下所示:

public class Joke {
    private String mText;
    private String mAudio;
    private CATEGORY category;
    private LENGTH length;

    public Joke(String mText, String mAudio, CATEGORY category, LENGTH length) {
        this.mText = mText;
        this.mAudio = mAudio;
        this.category = category;
        this.length = length;
    }

    public String getmText() {
        return mText;
    }

    public void setmText(String mText) {
        this.mText = mText;
    }

    public String getmAudio() {
        return mAudio;
    }

    public void setmAudio(String mAudio) {
        this.mAudio = mAudio;
    }

    public CATEGORY getCategory() {
        return category;
    }

    public void setCategory(CATEGORY category) {
        this.category = category;
    }

    public LENGTH getLength() {
        return length;
    }

    public void setLength(LENGTH length) {
        this.length = length;
    }
}

您的JSON示例是:

{
  "mText": "text",
  "mAudio": "audio file path",
  "category": "YO_MAMMA",
  "length": "LONG"
}