简体   繁体   English

我如何存储ArrayList <Class> 在SharedPreferences中存储游戏进度?

[英]How can I store ArrayList<Class> in SharedPreferences to store game progress?

I'm new to android development and I am creating an android application that works like "4 Pics 1 Word" for my project. 我是Android开发的新手,我正在为我的项目创建一个类似“4 Pics 1 Word”的android应用程序。 I'm having difficulties in storing ArrayList in SharedPreferences or in the internal storage of the android phone. 我在SharedPreferences或Android手机的内部存储中存储ArrayList时遇到了困难。 The reason why is because I am randomizing the next activity using random generator and ArrayList. 原因是因为我使用随机生成器和ArrayList随机化下一个活动。 Any suggestions or ideas that my help my case? 我帮助我的任何建议或想法? Thank you in advance! 先感谢您! I've been stuck here for hours now. 我已经被困在这里几个小时了。

This is my MainActivity 这是我的MainActivity

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

Button btnStart;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Button btnStart = (Button) findViewById(R.id.btnStart);
    btnStart.setOnClickListener(this);
}

@Override
        public void onClick(View v) {
            // We are creating a list, which will store the activities that haven't been opened yet
            ArrayList<Class> activityList = new ArrayList<>();
            activityList.add(first.class);
            activityList.add(second.class);
            activityList.add(third.class);
            activityList.add(fourth.class);
            activityList.add(fifth.class);

            Random generator = new Random();
            int number = generator.nextInt(5) + 1;

            Class activity = null;

            // Here, we are checking to see what the output of the random was
            switch(number) {
                case 1:
                    activity = first.class;
                    // We are adding the number of the activity to the list
                    activityList.remove(first.class);
                    break;
                case 2:
                    activity = second.class;
                    activityList.remove(second.class);
                    break;
                case 3:
                    activity = third.class;
                    activityList.remove(third.class);
                    break;
                case 4:
                    activity = fourth.class;
                    activityList.remove(fourth.class);
                    break;
                default:
                    activity = fifth.class;
                    activityList.remove(fifth.class);
                    break;
            }
            // We use intents to start activities
            Intent intent = new Intent(getBaseContext(), activity);
            // `intent.putExtra(...)` is used to pass on extra information to the next activity
            intent.putExtra("ACTIVITY_LIST", activityList);
            startActivity(intent);
        }
    }

And here's my first activity: 这是我的第一个活动:

public class first extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_first);
    etAnswer = (EditText) findViewById(R.id.etAnswer);
    btnGo = (Button) findViewById(R.id.btnGo);
    btnGo.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch(v.getId()){
        case R.id.btnGo:
            String answer = etAnswer.getText().toString();
            if(answer.equals("Jose Rizal") ||  answer.equals("jose rizal") || answer.equals("Rizal") || answer.equals("rizal") ){
                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
                dlgAlert.setMessage("The famous Rizal monument in Luneta was not the work of a Filipino but a Swiss sculptor named Richard Kissling?" +
                        "Source: http://www.joserizal.ph/ta01.html");
                dlgAlert.setTitle("Did you know that ...");
                dlgAlert.setPositiveButton("Next",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                ArrayList<Class> activityList = new ArrayList<>();
                                Bundle extras = getIntent().getExtras();
                                activityList = (ArrayList<Class>) extras.get("ACTIVITY_LIST");

                                if(activityList.size() == 0) {
                                    Context context = getApplicationContext();
                                    CharSequence last = "Congratulations! You just finished the game! Please wait for the next update!";
                                    int durationFinal = Toast.LENGTH_LONG;

                                    Toast toast = Toast.makeText(context, last, durationFinal);
                                    toast.show();
                                } else {
                                    // Now, the random number is generated between 1 and however many
                                    // activities we have remaining
                                    Random generator = new Random();
                                    int number = generator.nextInt(activityList.size()) + 1;

                                    Class activity = null;

                                    // Here, we are checking to see what the output of the random was
                                    switch(number) {
                                        case 1:
                                            // We will open the first remaining activity of the list
                                            activity = activityList.get(0);
                                            // We will now remove that activity from the list
                                            activityList.remove(0);
                                            break;
                                        case 2:
                                            // We will open the second remaining activity of the list
                                            activity = activityList.get(1);
                                            activityList.remove(1);
                                            break;
                                        case 3:
                                            // We will open the third remaining activity of the list
                                            activity = activityList.get(2);
                                            activityList.remove(2);
                                            break;
                                        case 4:
                                            // We will open the fourth remaining activity of the list
                                            activity = activityList.get(3);
                                            activityList.remove(3);
                                            break;
                                        default:
                                            // We will open the fifth remaining activity of the list
                                            activity = activityList.get(4);
                                            activityList.remove(4);
                                            break;
                                    }

                                    // Note: in the above, we might not have 3 remaining activities, for example,
                                    // but it doesn't matter because that case wouldn't be called anyway,
                                    // as we have already decided that the number would be between 1 and the number of
                                    // activities left.


                                    // Starting the activity, and passing on the remaining number of activities
                                    // to the next one that is opened
                                    Intent intent = new Intent(getBaseContext(), activity);
                                    intent.putExtra("ACTIVITY_LIST", activityList);
                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                    startActivity(intent);
                                }
                            }
                        });
                dlgAlert.setCancelable(true);
                dlgAlert.create().show();

            }else{
                Context context = getApplicationContext();
                CharSequence text = "Wrong! Try Again.";
                int duration = Toast.LENGTH_SHORT;

                Toast toast = Toast.makeText(context, text, duration);
                toast.show();
            }
            break;
    }
}

} }

Okay, this is a horrible hack and I don't endorse it in any way, but since you are so close to finishing your app, I propose a workaround: 好吧,这是一个可怕的黑客,我不会以任何方式认可它,但由于你已经如此接近完成你的应用程序,我提出了一个解决方法:

Instead of storing an ArrayList<Class> in your SharedPreferences (which is impossible), store a HashSet<String> containing the fully qualified names of your classes via putStringSet() . 而不是存储一个的ArrayList<Class>SharedPreferences (这是不可能的),存储HashSet<String>经由含有你的类的完全合格名称 putStringSet() 。

In order to get the String representations of the fully qualified names of your classes you need to call getName() , eg first.class.getName() . 为了获得类的完全限定名称的String表示,您需要调用getName() ,例如first.class.getName()

Then, you can get your Set<String> from SharedPreferences using getStringSet() and create a Class instance for each String in that set via Class.forName() . 然后,您可以使用getStringSet()SharedPreferences获取Set<String> ,并通过Class.forName()为该集合中的每个String创建一个Class实例。

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

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