android - 节省内部存储 android

标签 android storage internal

我在保存内部存储器的代码中遇到了某种逻辑问题。 我在 pet 类中创建了两个方法用于加载和保存我试图保存和加载 pet 实例的地方。我在 logcat 中没有收到任何错误消息,但是当我退出然后再次打开应用程序时,没有任何内容被保存。

 package Model;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;


import edu.chl.dat255.sofiase.readyforapet.CreatePet;
import android.content.Context;



public class Pet implements Serializable{

    /**
     * 
     */
     private static final long serialVersionUID = 1L;
    PetMood petMood = new PetMood();
    private int hungerCounter;
    private int walkCounter;
    private int playCounter;



    /**
     * Method that increases mood bar while eating
     *
     * @return String with the pet's reaction 
     */
    public String eat() {
        //walkCounter = petMood.getWalkMood();
        hungerCounter = petMood.getFoodMood();
        //playCounter = petMood.getPlayMood();
        if (hungerCounter < 5) {
            hungerCounter = hungerCounter + 1;
            petMood.setFoodMood(hungerCounter);
            return "Yummie!";
        }   

        else{
            return "I am full";
        }

    }

    /**
     * Method that increases mood bar while walking
     * and decides that the dog can't walk when it is too hungry or too tired
     *
     * @return String with the pet's reaction 
     */
    public String walk() {
        walkCounter = petMood.getWalkMood();
        hungerCounter = petMood.getFoodMood();
        playCounter = petMood.getPlayMood();
        if (hungerCounter < 3 && walkCounter < 5)
            return "I'm too hungry!";
        else if (playCounter + walkCounter > 6)
            return "I'm tired! I want to rest!";
        else if (walkCounter < 5) {
            walkCounter = walkCounter + 1;
            petMood.setWalkMood(walkCounter);
            return "Yeey! Great exercise!";
        }   
        else{
            return "I'm tired! I want to rest!";
        }

    }

    /**
     * Method that increases mood bar while playing
     * and decides that the dog can't play when it is too hungry or too tired
     *
     * @return String with the pet's reaction 
     */
    public String play() { 
        walkCounter = petMood.getWalkMood();
        hungerCounter = petMood.getFoodMood();
        playCounter = petMood.getPlayMood();
        if (playCounter + walkCounter > 6) {
            return "I'm tired! I want to rest!";
        }
        else if (hungerCounter <3 && playCounter < 5)
            return "I'm too hungry!";
        else if (playCounter < 5 ) {
            playCounter = playCounter + 1;
            petMood.setPlayMood(playCounter);
            return "Yeey! Lots of fun!";
        }   
        else{
            return "I'm tired! I want to rest!";
        }

    }

    public void save(String FILENAME, Context context) throws FileNotFoundException, IOException{
        FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
        ObjectOutputStream savedPet = new ObjectOutputStream(fos);
        savedPet.writeObject(context.getApplicationContext());
        savedPet.close();
    }

    public static Pet load(String FILENAME, Context context) throws FileNotFoundException, IOException, ClassNotFoundException{
        FileInputStream fis = context.openFileInput(FILENAME);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Pet pet = (Pet) ois.readObject();
        ois.close();
        CreatePet.setPet(pet);
        return pet;
    } 

    }

    package edu.chl.dat255.sofiase.readyforapet;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

import Model.Dog;
import Model.Pet;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;

public class CreatePet extends Activity implements OnClickListener, Serializable { //lagt till interface serializivble. kanske inte n�dv�ndigt

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    String petName; 
    private static Dog dog;
    String FILENAME = "pet_file.dat";//lagts till f�r nullpointerexeption

    /**
     * onCreate Method
     * 
     *
     * @param savedInstanceState - Bundle
     */
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.createpet);


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

    public void onClick (View v){
        startActivity(new Intent(CreatePet.this, PetActivity.class));
        EditText setName = (EditText) findViewById(R.id.edit_pet_name);
        petName = setName.getText().toString();
        dog = new Dog(petName);

        try {
            dog.save("pet_file.dat", this);
        } catch (FileNotFoundException e) {
            System.out.print("File not found kastad i CreatePet");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.print("IOException kastad i CreatePet");
            e.printStackTrace();
        }
    }

    /**
     * getPet Method
     * 
     * makes the created pet available to other classes
     *
     * @return dog - an instance of the class Dog
     */
    public static Pet getPet(){
        return dog;
    }

    /**
     * getPet Method
     * 
     * makes the created pet available to other classes
     *
     * @return dog - an instance of the class Dog
     */
    public static void setPet(Pet pet){
        dog = (Dog) pet; 
    }

}

    package edu.chl.dat255.sofiase.readyforapet;


import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Serializable;

import Model.Pet;

import Model.Dog;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;



public class SelectGame extends Activity implements Serializable {// la till f�r att objektet m�ste vara serializible
    private static final long serialVersionUID = 1L;
    TextView failMessage;
    String FILENAME = "pet_file.dat";// lgts till f�r nullpointerexep




    /**
     * onCreate method
     * 
     * @param savedInstanceState - Bundle
     */
    @Override
    protected void onCreate (Bundle savedInstanceState) {
        super.onCreate (savedInstanceState);
        setContentView(R.layout.selectgame);


        //The continue button reacts to a click and starts PetActivity
        Button continuePreviousGame = (Button) findViewById(R.id.continuegame);
        continuePreviousGame.setOnClickListener(new OnClickListener() {

            /**
             * Method onClick for the continue previous game button
             * 
             * @param v - View
             */
            public void onClick (View v){

                    try {
                    Pet.load("pet_file.dat",SelectGame.this);
                    } catch (FileNotFoundException e) {
                    System.out.print("File not found ");
                    e.printStackTrace();
                } catch (IOException e) {
                    System.out.print("IO Exception ");
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    System.out.print("Class not found exception ");
                    e.printStackTrace();
                } 

                if (CreatePet.getPet() != null){
                    startActivity(new Intent(SelectGame.this, PetActivity.class));      
                }
                else{
                    failMessage = (TextView) findViewById(R.id.failmessage);
                    failMessage.setText("Create a pet first!");

                }
            }
        }

                );


        //To send the button CreateNewPet to the activity CreatePet
        Button createNewPet = (Button) findViewById(R.id.createnewpet);
        createNewPet.setOnClickListener(new OnClickListener() { 
            /**
             * Method onClick for the create new pet button
             * 
             * @param v - View
             */
            public void onClick (View v){
                startActivity(new Intent(SelectGame.this, CreatePet.class));
            }
        }
                );
    }
}

最佳答案

您正在保存错误的对象。您的代码保存一个 Context 并尝试将其作为 Pet 重新加载。 而不是

savedPet.writeObject(context.getApplicationContext());

你应该做的

savedPet.writeObject(this);

关于android - 节省内部存储 android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16605810/

相关文章:

android - 如何在 Android 上对 RxJava Completable.error 进行单元测试

java - Android隐藏状态栏、兼容性

iphone - 我的 iphone 应用程序因这个原因被拒绝 "We found that your app does not follow the iOS Data Storage Guidelines,..."

xml - 使用括号设置 Azure Blob 索引标记 - 在浏览器中有效,但在 REST API 中无效

android - 通过蓝牙将 OBDSim 连接到 Windows 上的 Torque

android - 只为 android apk 保留 armeabi-v7a 是否安全

C#高效存储大int数据

android - 你在哪里存储默认图像在 android 的内部存储?

java - Springs @RequestParam 注解的内部工作

java - 将对象写入内部存储