为什么我使用SharedPreference变量获得ArrayIndexOutOfBoundsException?

时间:2015-11-30 19:40:44

标签: android arrays android-sharedpreferences

我有一个简单的应用程序可以打印笑话并保存你最喜欢的"那些。我遇到了一个arrayoutofbounds问题,我不确定我做错了什么。这是我的代码:

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * Created by Android on 11/15/15.
 */
public class Pun extends Activity {

    private InterstitialAd interstitial;

    public static final String PREFS_NAME = "MyPrefsFile";

    public static final String TAG = Pun.class.getSimpleName();
    public static final String mPath = "body.txt";
    public static final String mBusinessPath = "business.txt";
    public static final String mCrimePath = "crime.txt";
    public static final String mEducationPath = "education.txt";
    public static final String mEntertaintmentPath = "entertainment.txt";
    public static final String mFoodPath = "food.txt";
    public static final String mHealthPath = "health.txt";
    public static final String mNaturePath = "nature.txt";
    public static final String mPeoplePath = "people.txt";
    public static final String mPlacesPath = "places.txt";
    public static final String mTechnologyPath = "technology.txt";
    public static final String mTransportationPath = "transportation.txt";
    public static final String mWorkPath = "work.txt";
    private QuoteBank mQuoteBank;
    private List<String> mLines;
    private int counter = 0;

    private static int SIZE = 20;
    private String favorites1[] = new String[SIZE];
    private String favorites2[] = new String[SIZE];
    private String favorites3[] = new String[SIZE];
    private String favorites4[] = new String[SIZE];
    private String favorites5[] = new String[SIZE];
    private String favorites6[] = new String[SIZE];
    private String favorites7[] = new String[SIZE];
    private String favorites8[] = new String[SIZE];
    private String favorites9[] = new String[SIZE];
    private String favorites10[] = new String[SIZE];
    private String favorites11[] = new String[SIZE];
    private String favorites12[] = new String[SIZE];
    private String favorites13[] = new String[SIZE];

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pun);

        // Create the interstitial.
        interstitial = new InterstitialAd(this);
        interstitial.setAdUnitId("ca-app-pub-9704824959875003/5950200773");

        mQuoteBank = new QuoteBank(this);

        final TextView textView = (TextView) findViewById(R.id.textView);

        Random r = new Random();
        final int i1 = r.nextInt(20 - 1) + 1;

        mQuoteBank = new QuoteBank(this);
        mLines = mQuoteBank.readLine(mPath);

        textView.setText(mLines.get(i1));

        favorites1 = new String[SIZE];
        favorites2 = new String[SIZE];
        favorites3 = new String[SIZE];
        favorites4 = new String[SIZE];
        favorites5 = new String[SIZE];
        favorites6 = new String[SIZE];
        favorites7 = new String[SIZE];
        favorites8 = new String[SIZE];
        favorites9 = new String[SIZE];
        favorites10 = new String[SIZE];
        favorites11 = new String[SIZE];
        favorites12 = new String[SIZE];
        favorites13 = new String[SIZE];

        // Set all favorites1 to false for initial setup
        for (int i = 0; i < SIZE; i++) {
            favorites1[i] = "false";
            favorites2[i] = "false";
            favorites3[i] = "false";
            favorites4[i] = "false";
            favorites5[i] = "false";
            favorites6[i] = "false";
            favorites7[i] = "false";
            favorites8[i] = "false";
            favorites9[i] = "false";
            favorites10[i] = "false";
            favorites11[i] = "false";
            favorites12[i] = "false";
            favorites13[i] = "false";

        }

        Context mContext = getApplicationContext();

        // Save and Load array
        //saveArray(favorites1,"favorites1",this);
        favorites1 = loadArray("favorites1",this);
        favorites2 = loadArray("favorites2",this);
        favorites3 = loadArray("favorites3",this);
        favorites4 = loadArray("favorites4",this);
        favorites5 = loadArray("favorites5",this);
        favorites6 = loadArray("favorites6",this);
        favorites7 = loadArray("favorites7",this);
        favorites8 = loadArray("favorites8",this);
        favorites9 = loadArray("favorites9",this);
        favorites10 = loadArray("favorites10",this);
        favorites11 = loadArray("favorites11",this);
        favorites12 = loadArray("favorites12",this);
        favorites13 = loadArray("favorites13",this);

        final ImageButton favoritesBtn = (ImageButton) findViewById(R.id.imageButton);
        favoritesBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (MainActivity.category){
                    case "body":
                        if(favorites1[i1-1].equals("true")){
                            favorites1[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites1[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "crime":
                        if(favorites2[i1-1].equals("true")){
                            favorites2[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites2[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "entertainment":
                        if(favorites3[i1-1].equals("true")){
                            favorites3[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites3[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "health":
                        if(favorites4[i1-1].equals("true")){
                            favorites4[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites4[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "people":
                        if(favorites5[i1-1].equals("true")){
                            favorites5[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites5[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "technology":
                        if(favorites6[i1-1].equals("true")){
                            favorites6[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites6[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "work":
                        if(favorites7[i1-1].equals("true")){
                            favorites7[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites7[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "business":
                        if(favorites8[i1-1].equals("true")){
                            favorites8[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites8[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "education":
                        if(favorites9[i1-1].equals("true")){
                            favorites9[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites9[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "food":
                        if(favorites10[i1-1].equals("true")){
                            favorites10[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites10[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "nature":
                        if(favorites11[i1-1].equals("true")){
                            favorites11[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites11[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "places":
                        if(favorites12[i1-1].equals("true")){
                            favorites12[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites12[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "transportation":
                        if(favorites13[i1-1].equals("true")){
                            favorites13[i1-1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites13[i1-1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    default:
                        break;
                }


                saveArray(favorites1,"favorites1",Pun.this);
                saveArray(favorites2,"favorites1",Pun.this);
                saveArray(favorites3,"favorites1",Pun.this);
                saveArray(favorites4,"favorites1",Pun.this);
                saveArray(favorites5,"favorites1",Pun.this);
                saveArray(favorites6,"favorites1",Pun.this);
                saveArray(favorites7,"favorites1",Pun.this);
                saveArray(favorites8,"favorites1",Pun.this);
                saveArray(favorites9,"favorites1",Pun.this);
                saveArray(favorites10,"favorites1",Pun.this);
                saveArray(favorites11,"favorites1",Pun.this);
                saveArray(favorites12,"favorites1",Pun.this);
                saveArray(favorites13,"favorites1",Pun.this);

            }
        });

        switch (MainActivity.category) {
            case "body":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mPath);

                System.out.print(i1);

                if(favorites1[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "crime":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mCrimePath);
                if(favorites2[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "entertainment":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mEntertaintmentPath);
                if(favorites3[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "health":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mHealthPath);
                if(favorites4[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "people":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mPeoplePath);
                if(favorites5[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "technology":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mTechnologyPath);
                if(favorites6[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "work":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mWorkPath);
                if(favorites7[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "business":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mBusinessPath);
                if(favorites8[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "education":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mEducationPath);
                if(favorites9[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "food":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mFoodPath);
                if(favorites10[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "nature":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mNaturePath);
                if(favorites11[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "places":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mPlacesPath);
                if(favorites12[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            case "transportation":
                mQuoteBank = new QuoteBank(this);
                mLines = mQuoteBank.readLine(mTransportationPath);
                if(favorites13[i1-1].equals("true"))
                    favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                break;
            default:
                break;
        }


        final Button btn1 = (Button) findViewById(R.id.next);
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Random r = new Random();
                int i1 = r.nextInt(20 - 1) + 1;

                textView.setText(mLines.get(i1));

                counter++;
                if (counter == 3) {
                    counter = 0;
                    // ad
                    displayInterstitial();
                }

                switch (MainActivity.category) {
                    case "body":
                    if (favorites1[i1 - 1].equals("true")) {
                        favorites1[i1 - 1] = "false";
                        favoritesBtn.setBackgroundResource(R.drawable.starblank);
                    } else {
                        favorites1[i1 - 1] = "true";
                        favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                    }
                    break;
                    case "crime":
                        if (favorites2[i1 - 1].equals("true")) {
                            favorites2[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites2[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "entertainment":
                        if (favorites3[i1 - 1].equals("true")) {
                            favorites3[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites3[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "health":
                        if (favorites4[i1 - 1].equals("true")) {
                            favorites4[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites4[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "people":
                        if (favorites5[i1 - 1].equals("true")) {
                            favorites5[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites5[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "technology":
                        if (favorites6[i1 - 1].equals("true")) {
                            favorites6[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites6[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "work":
                        if (favorites7[i1 - 1].equals("true")) {
                            favorites7[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites7[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "business":
                        if (favorites8[i1 - 1].equals("true")) {
                            favorites8[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites8[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "education":
                        if (favorites9[i1 - 1].equals("true")) {
                            favorites9[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites9[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "food":
                        if (favorites10[i1 - 1].equals("true")) {
                            favorites10[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites10[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "nature":
                        if (favorites11[i1 - 1].equals("true")) {
                            favorites11[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites11[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "places":
                        if (favorites12[i1 - 1].equals("true")) {
                            favorites12[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites12[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    case "transportation":
                        if (favorites13[i1 - 1].equals("true")) {
                            favorites13[i1 - 1] = "false";
                            favoritesBtn.setBackgroundResource(R.drawable.starblank);
                        } else {
                            favorites13[i1 - 1] = "true";
                            favoritesBtn.setBackgroundResource(R.drawable.staryellow);
                        }
                        break;
                    default:
                        break;
                }

                saveArray(favorites1,"favorites1",Pun.this);
                saveArray(favorites2,"favorites1",Pun.this);
                saveArray(favorites3,"favorites1",Pun.this);
                saveArray(favorites4,"favorites1",Pun.this);
                saveArray(favorites5,"favorites1",Pun.this);
                saveArray(favorites6,"favorites1",Pun.this);
                saveArray(favorites7,"favorites1",Pun.this);
                saveArray(favorites8,"favorites1",Pun.this);
                saveArray(favorites9,"favorites1",Pun.this);
                saveArray(favorites10,"favorites1",Pun.this);
                saveArray(favorites11,"favorites1",Pun.this);
                saveArray(favorites12,"favorites1",Pun.this);
                saveArray(favorites13,"favorites1",Pun.this);
            }
        });


    }

    public void displayInterstitial() {

        // Create ad request.
        AdRequest adRequest = new AdRequest.Builder().build();

        // Begin loading your interstitial.
        interstitial.loadAd(adRequest);

        if (interstitial.isLoaded()) {
            interstitial.show();
        }
    }

    public boolean saveArray(String[] array, String arrayName, Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(arrayName +"_size", array.length);
        for(int i=0;i<array.length;i++)
            editor.putString(arrayName + "_" + i, array[i]);
        return editor.commit();
    }

    public String[] loadArray(String arrayName, Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        int size = prefs.getInt(arrayName + "_size", 0);
        String array[] = new String[size];
        for(int i=0;i<size;i++)
            array[i] = prefs.getString(arrayName + "_" + i, null);
        return array;
    }
}

这部分似乎正在发生:

if(favorites1[i1-1].equals("true"))

以下是加载和保存方法:

public boolean saveArray(String[] array, String arrayName, Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putInt(arrayName +"_size", array.length);
        for(int i=0;i<array.length;i++)
            editor.putString(arrayName + "_" + i, array[i]);
        return editor.commit();
    }

    public String[] loadArray(String arrayName, Context mContext) {
        SharedPreferences prefs = mContext.getSharedPreferences("preferencename", 0);
        int size = prefs.getInt(arrayName + "_size", 0);
        String array[] = new String[size];
        for(int i=0;i<size;i++)
            array[i] = prefs.getString(arrayName + "_" + i, null);
        return array;
    }

注意^以上方法工作正常。我的应用程序使用一个收藏夹阵列正确运行,但是当我添加更多它开始崩溃时。我必须遗漏一些简单的东西,但我无法找到它。感谢。

2 个答案:

答案 0 :(得分:2)

您的数组初始化始终被loadArray()的返回覆盖。但如果没有保存名称传递给loadArray()的数组,则返回一个空数组。然后,当您尝试访问该数组的元素时,它将给出一个越界异常。首先尝试运行您的加载操作,然后执行&#34; false&#34;只有在没有加载数据时才初始化。

答案 1 :(得分:0)

停止使用String []并开始使用ArrayList,这样你就可以添加元素,直到你满意为止,并且你不必管理你正在使用的String []。

以下是一个可以帮助您入门的代码段:

List<String> favorites = new ArrayList<String>();

然后添加一个元素:

favorites.add(myFavorite);

获取元素:

favorites.get(elementId);

或者您可以使用Map键值对:

Map<String,String> favorites = new HashMap<String, String>();

其中第一个String是您要保存的键,第二个String是Value,在您的情况下,该值将是您要对收藏夹进行排序的类别。要添加值:

favorites.put("http://thiscool.link", "sports");

迭代地图:

String desiredKey = "sports";
for(String key : favorites.keyMap()){
     if(desiredKey.equals(favorites.get(key)){
         return key;
     }
}

由于地图的所有键都是唯一的。