Skip to content Skip to sidebar Skip to footer

Shared Preferences, Where Do They Go?

I know how shared preferences work but I just dont know where to insert the code in the code below to save the users data.I have a login , background task that does all the work an

Solution 1:

This is what I use in my every Android app for SharedPreferences

import android.content.Context;
import android.content.SharedPreferences;

/**
 * Created by Jimit Patel on 30/07/15.
 */publicclassPrefs {

    privatestatic final StringTAG = Prefs.class.getSimpleName();

    privatestatic final StringMY_APP_PREFS = "my_app";

    /**
     * <p>Provides Shared Preference object</p>
     * @paramcontext
     * @return
     */privatestaticSharedPreferencesgetPrefs(Context context) {
        return context.getSharedPreferences(MY_APP_PREFS, Context.MODE_PRIVATE);
    }

    /**
     * <p>Saves a string value for a given key in Shared Preference</p>
     * @paramcontext
     * @paramkey
     * @paramvalue
     */publicstaticvoidsetString(Context context, String key, String value) {
        getPrefs(context).edit().putString(key, value).apply();
    }

    /**
     * <p>Saves integer value for a given key in Shared Preference</p>
     * @paramcontext
     * @paramkey
     * @paramvalue
     */publicstaticvoidsetInt(Context context, String key, int value) {
        getPrefs(context).edit().putInt(key, value).apply();
    }

    /**
     * <p>Saves float value for a given key in Shared Preference</p>
     * @paramcontext
     * @paramkey
     * @paramvalue
     */publicstaticvoidsetFloat(Context context, String key, float value) {
        getPrefs(context).edit().putFloat(key, value).apply();
    }

    /**
     * <p>Saves long value for a given key in Shared Preference</p>
     * @paramcontext
     * @paramkey
     * @paramvalue
     */publicstaticvoidsetLong(Context context, String key, long value) {
        getPrefs(context).edit().putLong(key, value).apply();
    }

    /**
     * <p>Saves boolean value for a given key in Shared Preference</p>
     * @paramcontext
     * @paramkey
     * @paramvalue
     */publicstaticvoidsetBoolean(Context context, String key, boolean value) {
        getPrefs(context).edit().putBoolean(key, value).apply();
    }

    /**
     * Provides string from the Shared Preferences
     * @paramcontext
     * @paramkey
     * @paramdefaultValue
     * @return
     */publicstaticStringgetString(Context context, String key, String defaultValue) {
        returngetPrefs(context).getString(key, defaultValue);
    }

    /**
     * Provides int from Shared Preferences
     * @paramcontext
     * @paramkey
     * @paramdefaultValue
     * @return
     */publicstatic int getInt(Context context, String key, int defaultValue) {
        returngetPrefs(context).getInt(key, defaultValue);
    }

    /**
     * Provides boolean from Shared Preferences
     * @paramcontext
     * @paramkey
     * @paramdefaultValue
     * @return
     */publicstaticbooleangetBoolean(Context context, String key, boolean defaultValue) {
        returngetPrefs(context).getBoolean(key, defaultValue);
    }

    /**
     * Provides float value from Shared Preferences
     * @paramcontext
     * @paramkey
     * @paramdefaultValue
     * @return
     */publicstatic float getFloat(Context context, String key, float defaultValue) {
        returngetPrefs(context).getFloat(key, defaultValue);
    }

    /**
     * Provides long value from Shared Preferences
     * @paramcontext
     * @paramkey
     * @paramdefaultValue
     * @return
     */publicstatic long getLong(Context context, String key, long defaultValue) {
        returngetPrefs(context).getLong(key, defaultValue);
    }

    publicstaticvoidclearPrefs(Context context) {
        getPrefs(context).edit().clear().commit();
    }
}

to use it you can just use those functions from it

Solution 2:

Once you received the login success from the server, implement the below code

SharedPreferencessharedpreferences= getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);    
SharedPreferences.Editoreditor= sharedpreferences.edit();
editor.putString("hasLoggedIn", true);
editor.commit();

And wherever you want to check whether the user is logged in not, you can check by using the following code.

booleanhasLoggedIn= sharedpreferences.getBoolean("hasLoggedIn", false);

If the hasLogged boolean value is true then the user had logged in.

Solution 3:

You Created Share Preferenced Method And save it

You Can use This Code ...helpful For you

savaLoginValue(mobileno, password, userTypeId, clientid);

private voidsavaLoginValue(String mobileno, String password) 
{
        SharedPreferences login = getSharedPreferences("Preferance", MODE_PRIVATE);
        SharedPreferences.Editor editor = login.edit();
        editor.putString("SPMobileno", mobileno);
        editor.putString("SPPass", password);
        editor.commit();
}

BackgoundTask.Class

public classBackgroundTaskextendsAsyncTask<String,Void,String>
{

private Context context;
private Activity activity;
private String reg_url = "http://blaah.com/register.php";
private String login_url = "http://blaah.com/login.php";
private AlertDialog.Builder builder;
private ProgressDialog progressDialog;


public BackgroundTask(Context context)
{

    this.context = context;
    activity = (Activity) context;
}

@Override
protected voidonPreExecute()
{
    builder = newAlertDialog.Builder(activity);
    progressDialog = newProgressDialog(context);
    progressDialog.setTitle("Please wait");
    progressDialog.setMessage("Connecting to Server...");
    progressDialog.setIndeterminate(true);
    progressDialog.setCancelable(false);
    progressDialog.show();
}

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

    String method = params[0];

    if (method.equals("register"))
    {

        try
        {
            URL url = newURL(reg_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = newBufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));
            String name = params[1];
            String email = params[2];
            String username = params[3];
            String password = params[4];
            String data = URLEncoder.encode("name", "UTF-8") + "=" + URLEncoder.encode(name, "UTF-8") + "&" +
                    URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(email, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = newBufferedReader(newInputStreamReader(inputStream));
            StringBuilder stringBuilder = newStringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {

                stringBuilder.append(line).append("\n");

            }


            httpURLConnection.disconnect();
            Thread.sleep(8000);
            return stringBuilder.toString().trim();

        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }

    }
    elseif (method.equals("login"))
    {
        try
        {
            URL url = newURL(login_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = newBufferedWriter(newOutputStreamWriter(outputStream, "UTF-8"));


            String username,password;

            username = params[1];
            password = params [2];
            String data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(username, "UTF-8") + "&" +
                    URLEncoder.encode("password", "UTF-8") + "=" + URLEncoder.encode(password, "UTF-8");
            bufferedWriter.write(data);
            bufferedWriter.flush();
            bufferedWriter.close();
            outputStream.close();

            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = newBufferedReader(newInputStreamReader(inputStream));
            StringBuilder stringBuilder = newStringBuilder();
            String line = "";
            while ((line = bufferedReader.readLine()) != null)
            {

                stringBuilder.append(line + "\n");

            }


            httpURLConnection.disconnect();
            Thread.sleep(5000);
            return stringBuilder.toString().trim();


        } catch (MalformedURLException e)
        {
            e.printStackTrace();
        } catch (ProtocolException e)
        {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        } catch (IOException e)
        {
            e.printStackTrace();
        } catch (InterruptedException e)
        {
            e.printStackTrace();
        }
    }

    returnnull;
}

@Override
protected voidonProgressUpdate(Void... values)
{
    super.onProgressUpdate(values);
}

@Override
protected voidonPostExecute(String json)
{
   try
   {

       progressDialog.dismiss();


       Log.v("JSON", json);
       JSONObject jsonObject = newJSONObject(json);
       JSONArray jsonArray = jsonObject.getJSONArray("server_response");
       JSONObject jsonobject = jsonArray.getJSONObject(0);
       String code = jsonobject.getString("code");
       String message = jsonobject.getString("message");



       if(code.equals("reg_true"))
       {
           showDialog("Sucessful registration.Thank you.Enjoy_AS!", message, code);
       }

       elseif (code.equals("reg_false"))
       {
           showDialog("User Already exists", message, code);
       }

       elseif (code.equals("login_true"))
       {
         
         // Please You Can Take The Username & Password And Save It For Shared Preference Then Share Preference File Any where To Use It.. Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
           Intent intent = newIntent(activity, SplashScreen.class);
           activity.startActivity(intent);


       } elseif (code.equals("login_false"))
       {
           showDialog("Login Error", message, code);
       }


   } catch (JSONException e){
       e.printStackTrace();
   }


}

public voidshowDialog(String title,String message,String code)
{

    builder.setTitle(title);
    if (code.equals("reg_true") || code.equals("reg_false"))
    {
        builder.setMessage(message);//message form server
        builder.setPositiveButton("OK", newDialogInterface.OnClickListener()

        {
            @Override
            public voidonClick(DialogInterface dialog, int which)
            {
                dialog.dismiss();
                activity.finish();

            }
        });


    }

    elseif (code.equals("login_false"))
    {


        builder.setMessage(message);
        builder.setPositiveButton("OK", newDialogInterface.OnClickListener()
        {
            @Override
            public voidonClick(DialogInterface dialog, int which)
            {
                EditText loginEmail, loginPassword;
                loginEmail = (EditText) activity.findViewById(R.id.email);
                loginPassword = (EditText) activity.findViewById(R.id.password);
                loginEmail.setText("");
                loginPassword.setText("");
                dialog.dismiss();

            }


        });


    }
    AlertDialog alertDialog = builder.create();
    alertDialog.show();
}

}

Solution 4:

Just create a class called SessionManagement.java and paste the below code

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import java.util.HashMap;

/**
* Created by naveen.tp on 21/4/2016.
*/publicclassSessionManagement {

SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
Context context;

intPRIVATE_MODE=0;

privatestaticfinalStringPREF_NAME="YourPreferences";

privatestaticfinalStringIS_LOGIN="isLogedIn";

//ConstructorpublicSessionManagement(Context context) {

    this.context = context;
    sharedPreferences = context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
    editor = sharedPreferences.edit();
}


//Create Login SessionpublicvoidcreateLoginSession(boolean flag)
{
    editor.putBoolean(IS_LOGIN, flag);
    editor.commit();
}

//check for isLogin returns True/falsepublicbooleanisLoggedIn()
{
    return sharedPreferences.getBoolean(IS_LOGIN, false);
}

}

In your code BackgroundTask.java onPostExcecute method

EDITED

elseif(code.equals("login_true"))
{
 SessionManagement session = new SessionManagement(context);
 session.createLoginSession(true);
 Toast.makeText(context, "You are logged in", Toast.LENGTH_LONG).show();
 Intent intent = new Intent(activity, SplashScreen.class);
 activity.startActivity(intent);
}

You can also check for Login status next time in your splash screen just by calling

EDITED

SessionManagementsession=newSessionManagement(this); 
booleanisLogin= session.isLoggedIn();
if(isLogin)
{
  //Already logged in
}
else
{
  //Not logged in
}

Hope that helps you!

Post a Comment for "Shared Preferences, Where Do They Go?"