rivaille-sama
rivaille-sama

Reputation: 103

Android - SharedPreferences not working?

Here's the code where I get to have the SharedPreferences:

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


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




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



    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{

        SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);
        final SharedPreferences.Editor editor = preferences.edit();

        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();

                    editor.putString("rfid" ,rfid);
                    editor.commit();

                }
            });

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

    }catch(Exception e){
        dialog.dismiss();
        System.out.println("Exception : " + e.getMessage());
    }
}

This is where I'd like the get the Registration ID entered by the user and use it in all activities of the app.

Here is the code to check whether I get to have the SharedPreferences correctly. It displays it through I text view. I wonder why it would not show up. Did I do the SharePreferences correctly?

public class ViewGradesActivity extends ActionBarActivity {

TextView viewPref;

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

    SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
    String get = settings.getString("rfid", "");

    viewPref = (TextView) findViewById(R.id.tv);
    viewPref.setText(get);

}

}

By the way, the code above is from another class.

Thanks for the help in advance.

Upvotes: 0

Views: 1132

Answers (3)

olegr
olegr

Reputation: 2019

Are you sure that you put any value in rfid? Here

                public void run() {
                    Toast.makeText(MainActivity2.this,"Login Success", Toast.LENGTH_SHORT).show();

                    editor.putString("rfid" ,rfid);
                    editor.commit();

                }

I think rfid is null. I did not find any place where you are initializing it.

Put rfid in toast or log it and you will see.

And as everybody else say you have to use default shared preferences in both classes. Here you can find why Difference between getDefaultSharedPreferences and getSharedPreferences

Upvotes: 0

florianmski
florianmski

Reputation: 5643

That's because you don't read and write the preferences in the same preference file.

To write you use:

SharedPreferences preferences = getSharedPreferences(getPref, Context.MODE_PRIVATE);

To read you use:

PreferenceManager.getDefaultSharedPreferences(this);

So you write you preferences in a file getPref (which is null according to your code, don't you get any error?) but you read your preferences in the default file provided by the Android API.

Upvotes: 0

John P.
John P.

Reputation: 4398

You are receiving this error because you are writing to a different SharedPreferences than you are reading from. If you are using default SharedPreferences, make sure you read and write to the default preferences.

// Read the String from SharedPreferences
String awesomeString = PreferenceManager.getDefaultSharedPreferences(context).getString("key", "");

// Write the String to SharedPreferences
PreferenceManager.getDefaultSharedPreferences(context)
        .edit().putString("key", awesomeString).commit();

Upvotes: 2

Related Questions