sharedpreferences没有加载或保存

时间:2014-10-04 22:08:15

标签: java android sharedpreferences storage

当用户在其存储中为图像网格的一部分选择他们想要的特定自定义图像时,我尝试使用共享偏好。我希望他们选择的图像即使在关闭应用程序并重新打开后也会显示出来。我遇到的问题是共享偏好似乎不起作用。没有任何东西显示为他们关闭应用程序后甚至只按下后退按钮时所选择的网格项目的背景图像。

我是否必须自己创建一个sharedpreferences文件?我无法弄清楚如何使用androidstudio来获取它或创建一个。

这是我的课程代码(对不起,如果它很长而且很混乱......我是编码和测试的新手):

  public class editCreations extends Activity {

    public int mPosition = 0;
    protected static Sounds sound = new Sounds();
    private static int RESULT_LOAD_IMAGE = 1;

    private MediaRecorder mRecorder;
    private MediaPlayer mPlayer;
    private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
    private Drawable mImageFileName;
    private Button recordBtn;
    private Button stopBtn;
    private Button playBtn;
    private Button stopPlayBtn;
    private ImageButton imgBtn;
    private Drawable bg;
    private  String mPicturePath;



    private ImageAdapter img = new ImageAdapter(this);





    View.OnClickListener playListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
        }
    };



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create);

        mRecorder = new MediaRecorder();
        mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
        mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
        mRecorder.setOutputFile(mOutputFile);

        recordBtn = (Button)findViewById(R.id.create_record_button);
        recordBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                start(view);
            }
        });

        stopBtn = (Button)findViewById(R.id.create_stop_record_button);
        stopBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stop(view);
            }
        });

        playBtn = (Button)findViewById(R.id.create_play_button);
        playBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                play(view);
            }
        });

        stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
        stopPlayBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                stopPlay(view);
            }
        });

        imgBtn = (ImageButton)findViewById(R.id.imageButton);

        Intent extra = getIntent();
        Bundle extras = extra.getExtras();

        // gave mPosition a default int to debug and find problem -> found it
        mPosition = extras.getInt("position");
        getSelectedFile(mPosition);

        imgBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(
                        Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });




    }

    public void start (View view) {
        try {

            mRecorder.prepare();
            mRecorder.start();

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        recordBtn.setEnabled(false);
        stopBtn.setEnabled(true);

        Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();

    }

    public void stop(View view){
        try {
            mRecorder.stop();
            mRecorder.release();
            mRecorder = null;

            stopBtn.setEnabled(false);
            recordBtn.setEnabled(true);

            Toast.makeText(getApplicationContext(), "Stop recording...",
                    Toast.LENGTH_SHORT).show();

        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        }
    }

    public void play(View view) {
        try{
            mPlayer = new MediaPlayer();
            mPlayer.setDataSource(mOutputFile);
            mPlayer.prepare();
            mPlayer.start();

            playBtn.setEnabled(false);
            stopPlayBtn.setEnabled(true);

            Toast.makeText(getApplicationContext(), "Start play the recording...",
                    Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void stopPlay(View view) {
        try {
            if (mPlayer != null) {
                mPlayer.stop();
                mPlayer.release();
                mPlayer = null;
                playBtn.setEnabled(true);
                stopPlayBtn.setEnabled(false);

                Toast.makeText(getApplicationContext(), "Stop playing the recording...",
                        Toast.LENGTH_SHORT).show();


            }
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public void getSoundPosition(int position) {
        mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";

        // use to get proper image and sound files and edit output file to proper name
    }

    public void getSelectedFile(int position) {
            switch (mPosition) {
                case 0:
                    imgBtn.setBackgroundResource(R.drawable.sample_0);
                    imgBtn.refreshDrawableState();
                    break;
                case 1:
                    imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
                    imgBtn.refreshDrawableState();
                    break;
                case 2:
                    imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
                    imgBtn.refreshDrawableState();
                    break;
                case 3:
                    imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
                    imgBtn.refreshDrawableState();
                    break;
                case 4:
                    imgBtn.setBackgroundResource(R.drawable.sample_4);
                    imgBtn.refreshDrawableState();
                    break;
            }

    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.edit_creations, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

   @Override
   protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       super.onActivityResult(requestCode,resultCode,data);

       if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
           Uri selectedImage = data.getData();
           String[] filePathColumn = { MediaStore.Images.Media.DATA};

           Cursor cursor = getContentResolver().query(selectedImage,
                   filePathColumn, null,null,null);
           cursor.moveToFirst();

           int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
           mPicturePath = cursor.getString(columnIndex);
           cursor.close();

           imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));

           imgBtn.refreshDrawableState();
           // String picturePath contains the path of
           // selected image
       }
   }

    protected void onPause() {
        super.onPause();

        //need an editor object to make preference changes
        // all objects are from android.context.Context
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPref.edit();
        editor.putString("img_" + mPosition, mPicturePath);

        editor.commit();
    }

    protected void onResume() {
        super.onResume();
        SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
        mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
    }
}

1 个答案:

答案 0 :(得分:0)

您正在使用SharedPreferences,但您没有将代码放在正确的活动生命周期方法中。您正在onCreate()上阅读首选项并保存在onStop()上,所以也许您可以将其保存在onPause()上保存首选项(以确保它先前已保存)并重新加载{{1}而不是onResume()(后者仅在活动的生命周期中出现一次)。

此外,您可能想要检查onCreate()是否是更好的选择,因为它不仅仅在一项活动之间共享。