1

I strucked in storing and getting shared preferences.When a user has been registered if that registration is success then that values has to be stored in his profile nothing but my profile class.I don't know why am getting default value please give me a suggestion.

Thanks in advance.

Please tellmesomething Again I updated the code here.

  public class Register extends Activity  {


/**
 * Defining layout items.
 **/

EditText mFirstName, mLastName, mUsername, mMobile, mPassword;
ImageView img_back;
Button btnRegister, mbtnSignIn;
TextView registerErrorMsg;
String jsonresponce=null;
String enteredUsername,enteredPassword,enteredfname,enteredlname,enteredmobile;
String REGISTER_URL;
ProgressDialog pd;
private SharedPreferences sharedpreferences;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_register);
    mFirstName = (EditText) findViewById(R.id.fname);
    mLastName = (EditText) findViewById(R.id.lname);
    mUsername = (EditText) findViewById(R.id.username);
    mMobile = (EditText) findViewById(R.id.mobie);
    mPassword = (EditText) findViewById(R.id.pword);
    btnRegister = (Button) findViewById(R.id.register);
    mbtnSignIn = (Button) findViewById(R.id.signin);
    registerErrorMsg = (TextView) findViewById(R.id.tv);
    sharedpreferences = getSharedPreferences("a2a", Context.MODE_PRIVATE);
    img_back = (ImageView) findViewById(R.id.imageback);

    img_back.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent i_backtohome = new Intent(Register.this, HomeActivity.class);
            startActivity(i_backtohome);
        }
    });
    mbtnSignIn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i_backtosignin = new Intent(Register.this, Signin.class);
            startActivity(i_backtosignin);

        }
    });


    btnRegister.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            enteredUsername = mUsername.getText().toString();
            Log.e("username",enteredUsername);

            enteredPassword = mPassword.getText().toString();
            Log.e("username",enteredPassword);

            enteredfname = mFirstName.getText().toString();
            Log.e("username",enteredfname);

            enteredlname = mLastName.getText().toString();
            Log.e("username",enteredlname);

            enteredmobile = mMobile.getText().toString();
            Log.e("username",enteredmobile);

            REGISTER_URL = "http://ffhhhjkhjgh/register.php?UserName="+enteredUsername+"&FirstName="+enteredfname+"&LastName="+enteredlname+"&Mobile="+enteredmobile+"&Pass="+enteredPassword;

            // REGISTER_URL = REGISTER_URL + enteredUsername + enteredPassword + enteredfname + enteredlname + enteredmobile;
            Log.e("finalurl",REGISTER_URL);

            if (enteredUsername.equals("") || enteredfname.equals("") || enteredlname.equals("")
                    || enteredmobile.equals("") || enteredPassword.equals("")) {

                Toast.makeText(Register.this, "All Fields are Mandatory", Toast.LENGTH_LONG).show();

                return;
            }
            if (mUsername.length() <= 1 || mPassword.length() <= 1) {

                Toast.makeText(Register.this, "Username or password length must be greater than one", Toast.LENGTH_LONG).show();

                return;

            }
            new AsyncDataClass().execute();

        }
    });
}

  class AsyncDataClass extends AsyncTask<String, String, String> {

   /* String fName;
    String lName;
      public AsyncDataClass(){
        this.fName = enteredfname;
         this.lName = enteredlname;
      }*/

      @Override
      protected void onPreExecute() {
          super.onPreExecute();
          pd = new ProgressDialog(Register.this);
          pd.setMessage("Loading...");
          pd.setCanceledOnTouchOutside(false);
          pd.show();
          }

      @Override
      protected String doInBackground(String... params) {

          try{
              URL url = new URL(REGISTER_URL);
              String res;

              HttpURLConnection conn = (HttpURLConnection) url.openConnection();

              conn.setRequestMethod("POST");
              conn.setDoOutput(true);
              conn.setDoInput(true);
              conn.connect();
              res = conn.getResponseMessage();
              Log.e("res", res);


              InputStream in = conn.getInputStream();
              BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
              StringBuilder sb = new StringBuilder();
              String line = null;

              try{
                  while ((line = reader.readLine()) != null) {
                      sb.append(line + "\n");
                  }
                  in.close();
                  reader.close();
                  jsonresponce = sb.toString();
                  Log.e("jsondata", jsonresponce);
              }catch (Exception e) {
                  e.printStackTrace();
              }finally {
                  try {
                      conn.disconnect();
                  }
                  catch (Exception e) {
                      e.printStackTrace();
                  }
              }

          }catch (Exception e){
              e.printStackTrace();
          }
          return jsonresponce;
      }

      @Override
      protected void onPostExecute(String s) {

          pd.dismiss();

                if("SUCCESS".equals(jsonresponce)){
                    Toast.makeText(getApplicationContext(),jsonresponce,Toast.LENGTH_SHORT).show();
                    SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("a2a", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedpreferences.edit();
                    editor.putString("enteredfname", enteredfname);
                    editor.putString("enteredlname", enteredlname);
                    editor.commit();
                }else{
                    Toast.makeText(getApplicationContext(),jsonresponce,Toast.LENGTH_SHORT).show();
                }

          super.onPostExecute(s);
      }
  }
    }
Mounika12
  • 33
  • 8
  • 2
    `Context#getSharedPreferences()` and `PreferenceManager.getDefaultSharedPreferences()` are using two different preference files. Use one of them consistently. – Mike M. Apr 26 '16 at 06:03
  • Am not getting can you explain clearly – Mounika12 Apr 26 '16 at 06:05
  • use as in the answer SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(mContext); – Sanoop Surendran Apr 26 '16 at 06:06
  • yes i saw that code then i have to create a custom sharedpreference file in that i have to store the value – Mounika12 Apr 26 '16 at 06:07
  • 2
    `PreferenceManager.getDefaultSharedPreferences()` uses a file named `_preferences`. Your call to `getSharedPreferences()` is using a file named `a2a`, so it's going to have different settings than the default one. – Mike M. Apr 26 '16 at 06:08
  • 1
    Possible duplicate of [Difference between getDefaultSharedPreferences and getSharedPreferences](http://stackoverflow.com/questions/5946135/difference-between-getdefaultsharedpreferences-and-getsharedpreferences) – Mike M. Apr 26 '16 at 06:11
  • yes i updated the whole code can you please tell according to that – Mounika12 Apr 26 '16 at 07:18

4 Answers4

1

You are using getSharedPreferences and getDefaultSharedPreferences together.

Do like this -

SharedPreferences sharedpreferences = getApplicationContext().getSharedPreferences("a2a", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("enteredfname", enteredfname);
editor.putString("enteredlname", enteredlname);
editor.commit();

And later -

SharedPreferences preferences = getApplicationContext().getSharedPreferences("a2a", Context.MODE_PRIVATE);
String value = preferences.getString("enteredfname", "enteredfname");
Supratim Haldar
  • 2,376
  • 3
  • 16
  • 26
0

try something like this.. Create a class

public class SharedPreferenceCustom {
  private Context mContext;
  private String defValue = "";

  public SharedPreferenceCustom(Context context) {
    this.mContext = context;
  }

  public void setSharedPref(String inputKey, Object inputValue) {
    final SharedPreferences sharedPreferences = mContext.getSharedPreferences("a2a", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(inputKey, String.valueOf(inputValue));
    editor.apply();

    }

  public String getSharedPref(String inputKey) {
    SharedPreferences sharedPreferences = mContext.getSharedPreferences("a2a", Context.MODE_PRIVATE);
    return sharedPreferences.getString(inputKey, defValue);
 }
}

and call whenever needed

Call by

   SharedPreferenceCustom sp = new SharedPreferenceCustom(mContext);
   sp.setSharedPref("KEY", "VALUE");
   // or
   sp.getSharedPref("KEY");
Sanoop Surendran
  • 3,484
  • 4
  • 28
  • 49
0

You've used SharedPreferences.Editor for storing value and then inside another Activity you're using PreferenceManager to retrieve the value. That's why you're getting default value always.

PreferenceManager is used for storing Preferences for a particular app. They are used for storing app settings where as SharedPreferences are used for saving data or values for working inside the app. They cannot be used for app settings. These are two separate files, though both use the Preferences class.

You need to use SharedPreferences object the retrieve the value in place of PreferenceManager. you've already created a SharedPreferences object named "preferences" inside your AnotherActivity. Just use this SharedPreferences object to retrieve the data you want to as shown below:

String value = preferences.getString("key", def_value);
Varun Kumar
  • 1,241
  • 1
  • 9
  • 18
0

To save value:

  @Override
          protected void onPostExecute(String s) {

              pd.dismiss();

                    if("SUCCESS".equals(jsonresponce)){
                        Toast.makeText(getApplicationContext(),jsonresponce,Toast.LENGTH_SHORT).show();
                         SharedPreferences sharedpreferences = getSharedPreferences("a2a", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = sharedpreferences.edit();

                        editor.putString("enteredfname", enteredfname);
                        editor.putString("enteredlname", enteredlname);
                        editor.commit();

                    }else{
                        Toast.makeText(getApplicationContext(),jsonresponce,Toast.LENGTH_SHORT).show();
                    }

              super.onPostExecute(s);
          }
      }

To retrive value:

 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_myprofile, container, false);

    mfname = (EditText)rootView.findViewById(R.id.fname);
    mlname = (EditText)rootView.findViewById(R.id.lname);
    mcontact = (EditText)rootView.findViewById(R.id.contact);
    mpassword = (EditText)rootView.findViewById(R.id.editpass);
    SharedPreferences sharedpreferences = getSharedPreferences("a2a", Context.MODE_PRIVATE)

    value = sharedpreferences.getString("enteredfname", "enteredfname")

    mfname.setText(value);
    return rootView;
}
Hello World
  • 2,764
  • 1
  • 11
  • 23