rivaille-sama
rivaille-sama

Reputation: 103

android - Accessing SharedPreferences on all activities

I'm making an application wherein a student can enter a registration once and he can access the rest of the features of the app.

My question is, how can I save the registration number he's going to enter, save it in a variable and use it in other activities in the app?

I've got this code for the login activity:

public class MainActivity2 extends Activity {
Button b;
EditText et,pass;
TextView tv;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;


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



    et = (EditText)findViewById(R.id.rfid);
    b = (Button)findViewById(R.id.loginnext);
    tv = (TextView)findViewById(R.id.tv);

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("language", et.toString().toString());
    editor.commit();

    b.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            dialog = ProgressDialog.show(MainActivity2.this, "",
                    "Validating user...", true);
            new Thread(new Runnable() {
                public void run() {
                    login();
                }
            }).start();
        }
    });
}

void login(){
    try{

        httpclient=new DefaultHttpClient();
        httppost= new HttpPost("http://usamobileapp.pe.hu/webservice/check.php");

        nameValuePairs = new ArrayList<NameValuePair>(2);

        nameValuePairs.add(new BasicNameValuePair("username",et.getText().toString().trim()));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        response=httpclient.execute(httppost);

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

        if(response.equalsIgnoreCase("User Found")){
            runOnUiThread(new Runnable() {
                public void run() {
                    Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();
                }
            });

            startActivity(new Intent(MainActivity2.this, MainActivity3Activity.class));
        }else{
            showAlert();
        }

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}
public void showAlert(){
    MainActivity2.this.runOnUiThread(new Runnable() {
        public void run() {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity2.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();
        }
    });
}

}

I'm not sure if I did the SharePreferences right of if places it in a right class.

And also, how would I know if I can use the SharedPreferences to other activities?

Thanks for the help in advanced.

Upvotes: 0

Views: 71

Answers (2)

Surender Kumar
Surender Kumar

Reputation: 1123

Make sharedprefernce like this ;

SharedPrefrences preferences = getSharedPreferences(key_value,
                Context.MODE_PRIVATE);
Editor editor = preferences.edit();
 //Now put values in editor 
editor.putString(key_value_for_access ,string_value_to_store );
editor.commit();

//Now for accessing this into every activity you have to write the same thing:

SharedPrefrences preferences = getSharedPreferences(key_value,
                Context.MODE_PRIVATE);
if(prefernces.contains(key_value_for_access)){
//getting data
String get = preferences.getString(key_value_for_access, null);
}

Upvotes: 1

ρяσѕρєя K
ρяσѕρєя K

Reputation: 132972

I'm not sure if I did the SharePreferences right of if places it in a right class.

Currently saving value from EditText in SharePreferences in onCreate of Activity which save default value of EditText.

Save value in SharePreferences in login() method after validating user:

if(response.equalsIgnoreCase("User Found")){
 //save value here            

}

how would I know if I can use the SharedPreferences to other activities?

To get values in other activities use getString :

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
String user_name = settings.getString("language", "");

Upvotes: 1

Related Questions