Android SharedPreference变量未存储

时间:2013-12-11 14:30:20

标签: android string variables sharedpreferences store


我正在尝试使用sharedPreference存储变量值,问题是每当我返回它时总是为NULL,即使我确定在退出之前为其分配了值 (我的应用程序获取用户编号并发送验证码并检查是否为真,如果是,则检查变量存储为真)

public class Verify extends Activity {

    TextView Number;
    EditText numf;
    TextView codet;
    EditText codef;
    TextView vcs;
    Button verify;
    Button numOK;
    ProgressBar pb;
    TextView vs;
    String cs;
    TextView vr;
    TextView checkSave;
    TextView textViewShowTime;
    String check;

    int code;
    int min = 00000;
    int max = 99999;
    private CountDownTimer countDownTimer; // built in android class
    // CountDownTimer
    private long totalTimeCountInMilliseconds; // total count down time in
            // milliseconds
    private long timeBlinkInMilliseconds; // start time of start blinking
    private boolean blink; // controls the blinking .. on and off
    long seconds;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.verifiy_activity);
         Number = (TextView) findViewById(R.id.Number);
         numf = (EditText) findViewById(R.id.numf);
         codet = (TextView) findViewById(R.id.codet);
         codef= (EditText) findViewById(R.id.codef);
         vcs = (TextView) findViewById(R.id.vcs);
         verify = (Button) findViewById(R.id.verify);
         numOK = (Button) findViewById(R.id.numOK);
         pb = (ProgressBar) findViewById(R.id.pb);
         vs = (TextView) findViewById(R.id.vs);
         vr = (TextView) findViewById(R.id.vr);
         checkSave = (TextView) findViewById(R.id.checkSave);
         textViewShowTime = (TextView) findViewById(R.id.tvTimeCount);

         final SmsManager sm = SmsManager.getDefault();
         checkGSM();
            Toast.makeText(getApplicationContext(), "1"+check, Toast.LENGTH_LONG).show();

         //OK button Start
         numOK.setOnClickListener(new OnClickListener(){

            @Override
            public void onClick(View v) {
                if(seconds==0)
                {
                 setTimer();
                 startTimer();



                 Random r = new Random();
                 code = r.nextInt(max - min + 1) + min;
                 cs=String.valueOf(code);
                 //sm.sendTextMessage(Number.getText().toString(), null,cs, null, null);

                 pb.setVisibility(View.VISIBLE);



                 Toast.makeText(getApplicationContext(), cs, Toast.LENGTH_LONG).show();
                }



            }



         });

         //Verify Button Start
            verify.setOnClickListener(new OnClickListener() {
                 public void onClick(View arg0) {
                     vcs.setVisibility(View.INVISIBLE);
                     pb = (ProgressBar) findViewById(R.id.pb);
                     codef= (EditText) findViewById(R.id.codef);
                     vcs = (TextView) findViewById(R.id.vcs);
                     vr = (TextView) findViewById(R.id.vr);
                     if(!(codef.getText().toString().equals(cs))&&codef.getText().length()!=0)
                       {
                           vcs.setVisibility(View.VISIBLE);
                           vcs.setText("Wrong Verification Code,Try Again");
                           //pb.setVisibility(View.INVISIBLE);
                           codef.setText("");
                           callCheck();


                   Toast.makeText(getApplicationContext(), cs, Toast.LENGTH_LONG).show();
                       }

                else if(codef.getText().toString().equals(cs))
                {

                    callCheck1();
                    vr.setTextColor(Color.GREEN);
                    vr.setText("Verified");
                     pb.setVisibility(View.GONE);
                     textViewShowTime.setVisibility(View.INVISIBLE);                    
                    checkSave.setVisibility(View.VISIBLE);
                    Toast.makeText(getApplicationContext(), "2"+check, Toast.LENGTH_LONG).show();
                     Toast.makeText(getApplicationContext(),
                           "hes"+ check, Toast.LENGTH_SHORT).show();    
                 setCheck("true");
                Toast.makeText(getApplicationContext(), "3"+check, Toast.LENGTH_LONG).show();
                } 

                 }  
                });     

            Toast.makeText(getApplicationContext(),
                       "4"+ check, Toast.LENGTH_SHORT).show();




            codef.addTextChangedListener(new TextWatcher() {

                public void onTextChanged(CharSequence s, int start, int before, int count) {

                }
                public void afterTextChanged(Editable s) {
                    // TODO Auto-generated method stub


                }
                public void beforeTextChanged(CharSequence s, int start, int count,
                        int after) {
                    // TODO Auto-generated method stub

                }
            });


            //check verification code
            codef.setOnFocusChangeListener(new OnFocusChangeListener() {          

                public void onFocusChange(View v, boolean hasFocus) {
                    if(hasFocus==true)
                    {   


                    }
                    else
                    {                   
                        //codef.getText().length()!=0
                        //vcs.setVisibility(View.GONE);
                        /*if(!(codef.getText().toString().equals(cs))&&codef.getText().length()!=0)
                           {
                               vcs.setVisibility(View.VISIBLE);
                           vcs.setText("Wrong Verification Code,Try Again");
                           pb.setVisibility(View.GONE);
                           Toast.makeText(getApplicationContext(), cs, Toast.LENGTH_LONG).show();
                           }

                        else if(codef.getText().toString().equals(cs))
                        {
                            vr.setTextColor(Color.GREEN);
                            vr.setText("Verified");
                             pb.setVisibility(View.GONE);
                        }*/
                    }




                }
            }); 



            //Verify Button End

    }
    public void setCheck(String x)
    {
        check=x;
        Toast.makeText(getApplicationContext(), "5"+check, Toast.LENGTH_LONG).show();
    }
    public void checkGSM()
    {
        if(vr.equals("Verified"))
        {
        check="true";
        }
        else
        {
            check="false";
        }


    }
    public void reset()
    {
        countDownTimer.cancel();
    }


    private void setTimer() {
        int time = 5;
        if(countDownTimer==null)
        {

            totalTimeCountInMilliseconds = 60 * time * 1000;
        }
        else
        {
            reset();
            totalTimeCountInMilliseconds = 60 * time * 1000;

        }




    }

    private void startTimer() {


        countDownTimer = new CountDownTimer(totalTimeCountInMilliseconds, 500) {
            // 500 means, onTick function will be called at every 500
            // milliseconds

            //@Override
            public void onTick(long leftTimeInMilliseconds) {
                seconds = leftTimeInMilliseconds / 1000;

                textViewShowTime.setText(String.format("%02d", seconds / 60)
                        + ":" + String.format("%02d", seconds % 60));
                // format the textview to show the easily readable format
            } 

            @Override
            public void onFinish() {
                // this function will be called when the timecount is finished
                textViewShowTime.setText("Time up!");
                textViewShowTime.setVisibility(View.VISIBLE);

            }

        }.start();

    }



    //Check Function Start
            public void callCheck1()
            {
                // Creating alert Dialog with one Button

                AlertDialog alertDialog1 = new AlertDialog.Builder(
                        Verify.this).create();

                // Setting Dialog Title
                alertDialog1.setTitle("Phone Number Saved");

                // Setting Dialog Message
                alertDialog1.setMessage("Your Phone Number Was Saved Successfully");


                // Setting OK Button
                alertDialog1.setButton("OK", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        // Write your code here to execute after dialog
                        // closed
                        Toast.makeText(getApplicationContext(),
                                "You clicked on OK", Toast.LENGTH_SHORT).show();
                    }
                });

                // Showing Alert Message
                alertDialog1.show();
            }






    //Check Function Start
        public void callCheck()
        {
            // Creating alert Dialog with one Button

            AlertDialog alertDialog1 = new AlertDialog.Builder(
                    Verify.this).create();

            // Setting Dialog Title
            alertDialog1.setTitle("SMS verification");

            // Setting Dialog Message
            alertDialog1.setMessage("Wrong Verification Code");


            // Setting OK Button
            alertDialog1.setButton("OK", new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    // Write your code here to execute after dialog
                    // closed
                    Toast.makeText(getApplicationContext(),
                            "You clicked on OK", Toast.LENGTH_SHORT).show();
                }
            });

            // Showing Alert Message
            alertDialog1.show();
        }
        public void savePreferences2(String key, boolean value) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());   
            Editor editor = sharedPreferences.edit();       
            editor.putBoolean(key, value);
          editor.commit();
     }
        public void savePreferences(String key, String value) {
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());   
            Editor editor = sharedPreferences.edit();       
            editor.putString(key, value);
          editor.commit();
     }

    public void loadSavedPreferences() {

            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            SharedPreferences sharedPreferences2 = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());



          String name = sharedPreferences.getString("storedAct","xx");
          check=name.toString();
          Toast.makeText(getApplicationContext(), "6"+check, Toast.LENGTH_LONG).show();
          if(check.equals("true"))
                  {
              vr.setText("Activated");

            //Toast.makeText(getApplicationContext(),
            //      "hello"+check, Toast.LENGTH_SHORT).show();  
                  }
          else
          {
              vr.setText("Still");
          }

        /*  if(name!=UserNumber)
          {
          nfield.setText(UserNumber);

          }
          else
          {
              nfield.setText(name);
          }
           */
        }
        @Override
        public void onStart(){
            super.onStart();
          loadSavedPreferences();

        }
        public void onPause()
        {
            super.onPause();
            savePreferences("storedِAct",check);

        }
        public void onResume()
        {
            super.onResume();
            loadSavedPreferences();
        }
        @Override
        public void onStop(){

            super.onStop();
            savePreferences("storedِAct",check);

        }

        //End Save Settings On Close

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

}

3 个答案:

答案 0 :(得分:1)

好的,要存储设置,请使用:

public void savePreferences(String key, String value) {
    // We need an Editor object to make preference changes.
    //"mySettings" is the name of settings file, and MODE_PRIVATE means that (from the docs):
    //the created file can only be accessed by the calling application (or all applications //sharing the same user ID).
    SharedPreferences settings = getSharedPreferences("mySettings", Activity.MODE_PRIVATE);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString(key, value);

    // Commit the edits!
    editor.commit();
}

并阅读:

public void loadSavedPreferences() {
    // Restore preferences
    SharedPreferences settings = getSharedPreferences("mySettings", Activity.MODE_PRIVATE);
    check = settings.getString("storedAct", "false");

    //rest of the code
}

请同时检查用于保存首选项的onPause()和onStop()键名称。它是“storedAct”,但由于某种原因,它在这里显示奇怪,在我的编辑器和loadSavedPreferences()中,你的密钥是“storedAct”,但它显示正确,所以它可能是你的密钥没有的问题匹配:)此外,仅在onPause()中保存您的首选项,从onStop()中删除它并将其加载到onResume()中(从onStart()中删除。)

答案 1 :(得分:0)

首先,您确定使用相同的密钥来存储和检索该值吗? (这看起来很愚蠢,但只是为了确保...)

然后你也可以尝试使用this.getSharedPreferences(String name,int mode) 有了这个你的活动和名称,你的喜好的任何唯一名称(如你的应用程序全名)

答案 2 :(得分:0)

您必须在活动的onStop()中删除对savePreference()的调用。此时变量可能为null。 在该点尝试日志输出以检查字符串的值。