简体   繁体   中英

How can I store intent or screen progress on android local database?

I'm a beginner at android development. I'm currently creating a game like 4-Pics-1-Word for my school project. It has 25 questions so I created 25 activities. I know this isn't the right method of doing this. Others have suggested that I should just change the pictures in ImageView . I tried to learn how to do that but I really don't understand it so I did this method. Now I'm stuck. This is how my game works. It is just like 4 pics 1 word but my prof told me that the activities must be randomized. I already randomized it. The only problem is I can't store the progress of the game on the android local database. I used intent.putExtra to send the information from the current activity to another activity. So basically after answering the previous activity then the previous activity must be removed from the list. I'm done with that already. I just can't find a way to store it on local database so when the user closes the game and opened it again the progress is saved. I tried this code below but the application won't open. It says "Unfortunately stopped" . Not sure where the problem is. Please help me. Thank you.

Here's the code for my MainActivity .

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

Button btnStart;
Context context;
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
ArrayList<Class> activityList


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button btnStart = (Button) findViewById(R.id.btnStart);
    String arrayStr = mPrefs.getString("MyObject","defValue");
    Gson gson = new Gson();
    activityList= gson.fromJson(arrayStr,new TypeToken<List<Class>>(){}.getType());
    //if the cache is null then new arraylist.
    if(activityList==null){
         // We are creating a list, which will store the activities that haven't been opened yet
        activityList = new ArrayList<>();
        activityList.add(first.class);
        activityList.add(second.class);
        activityList.add(third.class);
        activityList.add(fourth.class);
        activityList.add(fifth.class);
    }
    btnStart.setOnClickListener(this);
}

@Override
        public void onClick(View v) {

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

            Class activity = null;

            switch(number) {
                case 1:
                    activity = first.class;
                    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;
            }

            Intent intent = new Intent(getBaseContext(), activity);
            intent.putExtra("ACTIVITY_LIST", activityList);
    String json = gson.toJson(activityList); // myObject - instance of MyObject
    prefsEditor.putString("MyObject", json);
    prefsEditor.commit();
    startActivity(intent);
        }}

and here's the code for 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?" +
                        "\n" +
                        "\n" +
                        "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;
    }
}}

and this is my second activity:

public class second extends AppCompatActivity implements View.OnClickListener{
EditText etAnswer;
Button btnGo;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
    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("Antonio Luna") || answer.equals("antonio luna") || answer.equals("Heneral Luna") || answer.equals("heneral luna") ){
                AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
                dlgAlert.setMessage("He is the younger brother of the famous Filipino painter Juan Luna who is known for his masterpiece Spoliarium." +
                        "\n" +
                        "\n" +
                        "Source: http://nobert-bermosa.blogspot.com/2011/05/70-interesting-facts-about-general.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;
    }
}}

您可以使用ViewPager通过一个Activity显示多个问题,如果您不能使用ViewPager并进行多个Activitys则可以存储问题,使用SharedPrefrencesApplicationContext回答状态,或者是使用SQLite数据库制作游戏。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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