Android共享偏好设置

时间:2014-07-21 10:59:39

标签: java android

我有活动' A'和活动'。在活动' A' ,如果我有6个EditText并且用户只输入3然后我退出我的应用程序点击onBackPressed按钮而不提交正在输入的EditText数据,然后每当我重新启动我的应用程序时我想要同样的活动' A&# 39;在启动时。但是,当我运行并只输入3个编辑文本和3个剩余时,我第一次退出我的应用程序并再次重新启动应用程序启动器活动' A'是开始,但是当我第二次做同样的事情时,它会拨打第二个活动' B'。我怎么能这样做。有人可以帮助我。感谢您的光临。

Hare是我的活动代码

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration_details);

        SharedPreferences prefs =  PreferenceManager.getDefaultSharedPreferences(this);
        final SharedPreferences.Editor edit = prefs.edit();
        boolean alldataSaved=prefs.getBoolean("SecondRun",false);

        et_CompanyName = (EditText) findViewById(R.id.editText_CompanyName);
        et_EmployeeName = (EditText) findViewById(R.id.editText_EmployeeName);
        et_CompanyWebsite = (EditText) findViewById(R.id.editText_CompanyWebSite);
        et_ContactNumber = (EditText) findViewById(R.id.editText_ConatctNo);
        et_Email_Id = (EditText) findViewById(R.id.editText_EmailId);



        et_CompanyName.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    edit.putString("Company_Name"+appWidgetId,et_CompanyName.getText().toString());
                    edit.commit();
                    Log.e("Boolean Value" , " = " + appWidgetId);
                }
            }
        });


        et_EmployeeName.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    edit.putString("Employee_Name"+appWidgetId,et_EmployeeName.getText().toString());
                    edit.commit();
                    Log.e("Boolean Value" , " = " + appWidgetId);
                }
            }
        });



        et_CompanyWebsite.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    edit.putString("Company_Website"+appWidgetId,et_CompanyWebsite.getText().toString());
                    edit.commit();
                    Log.e("Boolean Value" , " = " + appWidgetId);
                }
            }
        });


        et_ContactNumber.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    edit.putString("Contact_Number"+appWidgetId,et_ContactNumber.getText().toString());
                    edit.commit();
                    Log.e("Boolean Value" , " = " + appWidgetId);
                }
            }
        });



        et_Email_Id.setOnFocusChangeListener(new OnFocusChangeListener() {          

            public void onFocusChange(View v, boolean hasFocus) {
                if(!hasFocus)
                {
                    edit.putString("Email_Id"+appWidgetId,et_Email_Id.getText().toString());
                    edit.commit();
                    Log.e("Boolean Value" , " = " + appWidgetId);
                }
            }
        });






          SharedPreferences settings=getSharedPreferences("prefs",0); 
          boolean firstRun=settings.getBoolean("firstRun",false);

          if(firstRun==false)//if running for first time 

          {
              SharedPreferences.Editor editor=settings.edit();
              editor.putBoolean("firstRun",true); 
              editor.commit();
              //execute your code for first time
          } 

          else 
          { 
              if(alldataSaved == false)
              {
                  SharedPreferences.Editor editor=prefs.edit();
                  editor.putBoolean("SecondRun",true); 
                  editor.commit();
                  Log.e("Second"," Steps !!!!");
              }
              else
              {
                  Intent iSubmit = new Intent(A.this,B.class);
                  startActivity(iSubmit);
                  finish();
                  //Default Activity startActivity(a); 
              }

          }

        databaseHelper = new DatabaseHelper(this);
        databaseHelper.onOpen(db);


        radioGroup_FinancialYaer = (RadioGroup)findViewById(R.id.radioGroupFinanncialYear);


        btnSubmit = (Button) findViewById(R.id.buttonSubmit);
        btnSubmit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                final String stringEmail_Id = et_Email_Id.getText().toString()
                        .trim();

                final String stringCompanyWebsite = et_CompanyWebsite.getText()
                        .toString().trim();

                if ((et_CompanyName.getText().toString().isEmpty()))
                {
                    et_CompanyName.setError("Field Can Not Be Empty !");
                }

                else if (!et_CompanyName.getText().toString().trim()
                        .matches("[a-zA-Z ]+"))
                {
                    et_CompanyName.setError("Accept Alphabets Only.");
                }

                else if ((et_EmployeeName.getText().toString().isEmpty()))
                {
                    et_EmployeeName.setError("Field Can Not Be Empty !");
                }

                else if (!et_EmployeeName.getText().toString().trim()
                        .matches("[a-zA-Z ]+"))
                {
                    et_EmployeeName.setError("Accept Alphabets Only.");
                }

                else if ((et_CompanyWebsite.getText().toString().isEmpty()))
                {
                    et_CompanyWebsite.setError("Field Can Not Be Empty !");
                }

                else if (!isValidUrl(stringCompanyWebsite))
                {
                    et_CompanyWebsite.setError("Invalid URL");
                }

                else if ((et_ContactNumber.getText().toString().isEmpty()))
                {
                    et_ContactNumber.setError("Field Can Not Be Empty !");
                }

                else if (!isValidEmail(stringEmail_Id))
                {
                    et_Email_Id.setError("Invalid Email");
                }

                else

                {
                    String stringCompanyName = et_CompanyName.getText()
                            .toString().trim();
                    String stringContactNumber = et_ContactNumber.getText()
                            .toString().trim();
                    String stringEmployeeName = et_EmployeeName.getText()
                            .toString().trim();


                    int selectedId = radioGroup_FinancialYaer.getCheckedRadioButtonId();
                    Log.e("selectedId "," = " + selectedId);
                    radioButton_FinancialYaer = (RadioButton) findViewById(selectedId);
                    strFinancialYear = radioButton_FinancialYaer.getText().toString().trim();
                    Log.e("strRadioButton "," = " + strFinancialYear);


                    databaseHelper.insertRegstrationDetails(stringCompanyName,
                            stringEmployeeName, stringCompanyWebsite,
                            stringContactNumber, stringEmail_Id, strFinancialYear);
                    System.out.println("Data Inserted Successfully !!! ");

                    Intent iSubmit = new Intent(A.this,B.class);
                    startActivity(iSubmit);
                    finish();
                }

            }
        });
    }

    // validating email id
    private boolean isValidEmail(String email) {

        String EMAIL_PATTERN = "[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}" + "\\@"
                + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\."
                + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";

        Pattern pattern = Pattern.compile(EMAIL_PATTERN);
        Matcher matcher = pattern.matcher(email);
        return matcher.matches();
    }


    private boolean isValidUrl(String url) {
        Pattern p = Patterns.WEB_URL;
        Matcher m = p.matcher(url);
        if(m.matches())
            return true;
        else
        return false;
    }

    @Override
     public boolean onKeyDown(int keyCode, KeyEvent event) {
         if ((keyCode == KeyEvent.KEYCODE_BACK)) {
             AlertDialog.Builder alertbox = new AlertDialog.Builder(Registration_Form.this);

             alertbox.setTitle("Do you wish to exit ?");
             alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface arg0, int arg1) { 
                    // finish used for destroyed activity
                     finish();
                 }
             });

             alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface arg0, int arg1) {
                         // Nothing will be happened when clicked on no button 
                         // of Dialog     
               }
             });

             alertbox.show();
         }
         return super.onKeyDown(keyCode, event);
     }

}

1 个答案:

答案 0 :(得分:0)

保存共享首选项中的变量,如果用户已经登录,我之前已经为登录模块执行了该操作,那么我的启动器活动将不会启动并且

SharedPreferences.Editor editor = mPrefs.edit();
editor.putInt("login",201);
editor.commit();

你可以在你的启动器活动中检查它

Intent intent;
if(checkFristLogin()){
          intent = new Intent(SplashActivity.this, MyNewMainActivity.class);
}else{
    intent = new Intent(SplashActivity.this,MainActivity.class);
     }
startActivity(intent);

checkFirstLogin功能在这里

SharedPreferences mPrefs;  // make this field  in your activity class
private boolean checkFristLogin() {
    // TODO Auto-generated method stub
     if(mPrefs == null){
        mPrefs = this.getSharedPreferences("MyGamePreferences", android.content.Context.MODE_PRIVATE);
    }
        if(mPrefs.getInt("login", -401)==201)return true;

        else return false;
}

希望它能解决你的问题