android共享偏好获取错误

时间:2015-10-15 11:20:14

标签: android

我需要在共享首选项中存储用户登录名和密码详细信息,但我收到错误。我需要在会话中维护用户登录详细信息。当用户登录用户邮件和密码时,应该存储在编辑文本中。从下次用户可以点击登录按钮直接进入。我现在需要做什么。这是我的代码。当我尝试下面的代码时,我很遗憾地收到错误。我需要修改代码的地方。这段代码有什么问题。

    public class MainActivity extends Activity {

Button b;
EditText email,password;
HttpPost httppost;
StringBuffer buffer;
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String Name = "nameKey";
public static final String Phone = "phoneKey";
String email1,passw;
SharedPreferences sh_Pref;
Editor toEdit;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;

DBHelper db = new DBHelper(this);

private boolean isValidEmaillId(String email){

    return Pattern.compile("^(([\\w-]+\\.)+[\\w-]+|([a-zA-Z]{1}|[\\w-]{2,}))@"
              + "((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\."
              + "([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\\.([0-1]?"
              + "[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"
              + "([a-zA-Z]+[\\w-]+\\.)+[a-zA-Z]{2,4})$").matcher(email).matches();
     }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button)findViewById(R.id.Button01);  
    email = (EditText)findViewById(R.id.username);
    password= (EditText)findViewById(R.id.password);


    sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {

            if(!isValidEmaillId(email.getText().toString().trim())){
                  Toast.makeText(getApplicationContext(), "Invalid Email Address", Toast.LENGTH_SHORT).show();
                }
            else if(password.getText().toString().equals(""))
            {           
              Toast.makeText(getApplicationContext(), "Please enter password", Toast.LENGTH_SHORT).show();
            }
            else
            {

                 email1 = email.getText().toString().trim();
                 passw = password.getText().toString().trim();

                 SharedPreferences.Editor editor = sharedpreferences.edit();

                editor.putString(Name, email1);
                editor.putString(Phone, passw);
                editor.commit();

                System.out.println("sharde    :" +Name+Phone);

            dialog = ProgressDialog.show(MainActivity.this, "", 
                    "Validating user...", true);
             new Thread(new Runnable() {
                    public void run() {
                        login();                          
                    }
                  }).start();             
        }
        }
    });


}

void login(){
    try{            
        final User user = new User();

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://ip:8080/ActCFWeb/login"); // make sure the url is correct.
        //add your data
        nameValuePairs = new ArrayList<NameValuePair>(2);
        // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar, 
        nameValuePairs.add(new BasicNameValuePair("email",email1));  // $Edittext_value = $_POST['Edittext_value'];
        nameValuePairs.add(new BasicNameValuePair("pass",passw)); 
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        //Execute HTTP Post Request
        System.out.println(response);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        final String response = httpclient.execute(httppost, responseHandler);
        System.out.println("Response : " + response); 
        runOnUiThread(new Runnable() {
            public void run() {

                dialog.dismiss();
            }
        });

        if(response.contains("success")){

            runOnUiThread(new Runnable() {
                public void run() {

                    Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();

                }
            });
            Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);

          //Sending data to another Activity
            nextScreen.putExtra("email", email.getText().toString());

            Log.e("n", email.getText()+"."+ email.getText());

            startActivity(nextScreen);
        }else{
            showAlert();                
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
public void showAlert(){
    MainActivity.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setTitle("Login Error.");
            builder.setMessage("User not Found.")  
                   .setCancelable(false)
                   .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                       public void onClick(DialogInterface dialog, int id) {
                       }
                   });                     
            AlertDialog alert = builder.create();
            alert.show();               
        }
    });
}
public boolean isOnline() {
    ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = conMgr.getActiveNetworkInfo();

    if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
        Toast.makeText(getApplicationContext(), "No Internet connection!", Toast.LENGTH_LONG).show();
        return false;
    }
return true; 
}

}

3 个答案:

答案 0 :(得分:0)

我想你从线程调用了views方法。您有女性登录方法,可能会调用dialog或其他视图。您无法从非主要线程访问ui元素。您必须使用处理程序 asynck任务

答案 1 :(得分:0)

可能你在谈论这个

SharedPreferences.Editor editor = sharedpreferences.edit();

            editor.putString(Name, email1);
            editor.putString(Phone, passw);
            editor.commit();

            System.out.println("sharde    :" +sharedpreferences.getString(Name, "def").toString()+ ", "sharedpreferences.getString(Phone, "def");

答案 2 :(得分:0)

从SharedPreferences存储中获取值。

SharedPreferences  sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
String emailString = sharedPreferences.getString("email", null); 
String passwordString = sharedPreferences.getString("password", null); 

在onCreate方法中,首先检查首选项是否包含电子邮件和密码的值。

 if((emailString != null) && (passwordString != null)) {
   //Populate the email and password edit texts using stored email and password values.
   etEmail.setText(emailString);
   etPassword.setText(passwordString);
 }

应在主(UI)线程中执行启动活动。您可以使用Handler或runOnUiThread。

if(response.contains("success")){

        runOnUiThread(new Runnable() {
            public void run() {

                Toast.makeText(MainActivity.this,"Login Success", Toast.LENGTH_SHORT).show();

                Intent nextScreen = new Intent(getApplicationContext(), FeedBack.class);

               //Sending data to another Activity
                nextScreen.putExtra("email", email.getText().toString());
                Log.e("n", email.getText()+"."+ email.getText());
                startActivity(nextScreen);
            }
        });
    }else{
        showAlert();                
    }