Need some advice with my Project related to SharedPreferences - java

I want to log a user and save the username that logged in, and display it in the MainActivity as a Toast or TextView.
Here is the code I have currently:
Session.java
public class Session {
SharedPreferences sharepref;
SharedPreferences.Editor editor;
Context context;
public Session(Context context){
this.context = context;
sharepref = context.getSharedPreferences("mypref", Context.MODE_PRIVATE);
editor = sharepref.edit();
editor.commit();
}
public void setLoggedin(boolean loggedin){
editor.putBoolean("loggedInmode",loggedin);
editor.commit();
}
public boolean loggedin(){
return sharepref.getBoolean("loggedInmode", false);
}
}
LoginActivity.java
public class LoginActivity extends AppCompatActivity{
//private Button login, register;
private EditText etUser, etPass;
private DatabaseHelper dbHelper;
private Session session;
private static final String SALT = "50C7BC9D21";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
dbHelper = new DatabaseHelper(this);
session = new Session(this);
etUser = (EditText)findViewById(R.id.etUsername);
etPass = (EditText)findViewById(R.id.etPassword);
//login = (Button)findViewById(R.id.btnLogin);
//register = (Button)findViewById(R.id.btnRegister);
//login.setOnClickListener(this);
//register.setOnClickListener(this);
if(session.loggedin()){
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
}
/*
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btnLogin:
login();
break;
case R.id.btnRegister:
//register();
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
break;
default:
}
}*/
/**
* METHOD THAT WILL BE EXECUTED ONCE THE EXIT BUTTON IS CLICKED
* ITS SOLO PURPOSE IS TO TERMINATE THE APPLICATION.
* */
public void exitApp(View v){
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
/**
* METHOD THAT WILL BE EXECUTED ONCE THE REGISTER BUTTON IS CLICKED
* ITS SOLO PURPOSE IS TO TAKE THE USER TO THE REGISTER WINDOW.
* */
public void newUser(View v){
startActivity(new Intent(LoginActivity.this,RegisterActivity.class));
}
/**
* METHOD THAT WILL BE EXECUTED ONCE THE LOGIN BUTTON IS CLICKED
* ITS SOLO PURPOSE IT TO COMPARE THE INFORMATION ENTERED IN THE EDITTEXT BOXES
* AND SEE IF ITS EQUAL WITH THE INFORMATION STORED IN THE DATABASE.
* */
public void loginUser(View v){
String user = etUser.getText().toString();
String pass = etPass.getText().toString();
String passwordToHash = pass;
String generatedPassword = null;
String finalpw = null;
try {
// Create MessageDigest instance for MD5
MessageDigest md = MessageDigest.getInstance("SHA1");
//Add password bytes to digest
md.update(passwordToHash.getBytes());
//Get the hash's bytes
byte[] bytes = md.digest();
//This bytes[] has bytes in decimal format;
//Convert it to hexadecimal format
StringBuilder sb = new StringBuilder();
for(int i=0; i< bytes.length ;i++)
{
sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
}
//Get complete hashed password in hex format
generatedPassword = sb.toString();
finalpw = generatedPassword + SALT;
Toast.makeText(this, finalpw, Toast.LENGTH_SHORT).show();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
System.out.println(generatedPassword);
//THIS WAS FIXED AROUND BECAUSE THE OTHER WAY FETCHING AND EQUALLING WITH DB AN USER COULD PASS BY WITHOUT REGESTERING.
if(dbHelper.getUser(user,finalpw)){
session.setLoggedin(true);
startActivity(new Intent(LoginActivity.this, MainActivity.class));
finish();
}else{
Toast.makeText(getApplicationContext(), R.string.wrong_info,Toast.LENGTH_SHORT).show();
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_ADD_CONTACT = 1;
private Session session;
//private TaskAdapter taskAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
session = new Session(this);
if (!session.loggedin()) {
logout();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_ADD_CONTACT) {
if (resultCode == RESULT_OK) {
}
}
}
public void logout() {
session.setLoggedin(false);
finish();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_logout) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
}
To repeat want to log user login information. Specifically I want to save the username that logged in and display it in the MainActivity as a Toast or TextView.
For what I read, I tried it with intent.putextra and with bundle, it will work at first install but after that it will crash the application, so I tried it with sharedpreference and created a session.
I am a bit blocked here. How do I save in the session each different user and then display its username in the MainActivity?
Sorry if i am doing something wrong its my first post.

You can make another paramater that can be put to SharedPref. For example in your set loggin :
public void setLoggedin(boolean loggedin, String username){
editor.putBoolean("loggedInmode",loggedin);
editor.putString("username",username);
editor.commit();
}
And in your main activity to get the username, you can make another method :
public boolean getUsername(){
return sharepref.getString("username", "");
}
you can call it with String username = session.getUsername();

Related

Passing database value to variable

I'm rarely ask on here, so first of all I'm sorry if my question is readable or not allowed here. So what I'm trying to do here is passing the username from LoginActivity into the player1 variable at HomeActivity . here's the code for the HomeActivity.java class
public class HomeActivity extends Activity {
TextView NameTxt;
TextView CoinTxt;
TextView GemTxt;
String p1name = player1.getName();
int p1coin = player1.getCoins();
int p1gem = player1.getGems();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_screen);
//////TV declare///////
NameTxt = (TextView)findViewById(R.id.playerName);
CoinTxt = (TextView)findViewById(R.id.cointxt);
GemTxt = (TextView)findViewById(R.id.gemtxt);
NameTxt.setText(p1name);
CoinTxt.setText("Coin: " +p1coin);
GemTxt.setText("Gem: " +p1gem);
}
}
And this is LoginActivity.class
public class LoginActivity extends Activity {
EditText edit1;
EditText edit2;
EditText edit3;
Button registerBtn;
Button loginBtn;
DatabaseHelper myDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set fullscreen and no title//////////
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
///////////////////////////////////////
setContentView(R.layout.login_screen);
edit1 = (EditText)findViewById(R.id.editpname);
edit2 = (EditText)findViewById(R.id.editpemail);
edit3 = (EditText)findViewById(R.id.editppw);
registerBtn = (Button)findViewById(R.id.registerbtn);
loginBtn = (Button)findViewById(R.id.loginbtn);
myDb = new DatabaseHelper(this);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
User currentUser = myDb.Authenticate(new User(null, null, Email, Password));
if (currentUser != null) {
System.out.println("Successfull");
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
startActivity(intent);
finish();
} else {
System.out.println("Unsuccessfull");
}
}
}
});
registerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (validate()) {
String UserName = edit1.getText().toString();
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!myDb.isEmailExists(Email)) {
myDb.addUser(player1);
public User player1 = new User(null, UserName, Email, Password);
}
}
}
});
}
public boolean validate() {
boolean valid = false;
String Email = edit2.getText().toString();
String Password = edit3.getText().toString();
if (!android.util.Patterns.EMAIL_ADDRESS.matcher(Email).matches()) {
valid = false;
edit2.setError("Please enter valid email!");
} else {
valid = true;
edit2.setError(null);
}
if (Password.isEmpty()) {
valid = false;
edit3.setError("Please enter valid password!");
} else {
if (Password.length() > 5) {
valid = true;
edit3.setError(null);
} else {
valid = false;
edit3.setError("Password is to short!");
}
}
return valid;
}
}
And I also have simple User.java class
String id;
String userName;
String email;
String password;
int coins;
int gems;
public User(String id, String userName, String email, String password) {
this.id = id;
this.email = email;
//And so on. Don't mind this
}
public String getName() {
return this.userName;
}
public int getCoins() {
return this.coins;
}
public int getGems() {
return this.gems;
}
And I write the short code , for the sake of readability.
I get an error on
myDb.addUser(player1);
And the one below it.
I'm just trying to make so that the player name equals to the value of Username on the database . and also the coins and gems too. Can you guys help me to get the idea how to pass the value? It tooks me whole 3days to figure a way to fix this. And it just blew my brain. So maybe you guys can help me
Ignoring the database stuff and assuming that LoginActivity is started from another activity (MainActivity) then you could adapt the following which passes the Username and UserId (ample to then get any additional data in the HomeActivity from the database).
So this when it starts immediately invokes the LoginActivity.
Clicking Login (mimics getting user and id from db) starts the HomeActivity passing the Username and userid via Intent Extras.
The HomeActivity displays the username and userid, and additionally a DONE button.
Clicking the DONE button returns back through the stack (skippng LoginActivity as that was finished) to the MainActivity which changes the TextView from Hello World to Welcome Back (not that you'd ever see Hello World).
MainActivity.java :-
public class MainActivity extends AppCompatActivity {
TextView mMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMessage = this.findViewById(R.id.message);
// Immediately start Login Activity
Intent i = new Intent(MainActivity.this,LoginActivity.class);
startActivity(i);
}
#Override
protected void onResume() {
super.onResume();
mMessage.setText("Welcome back");
}
}
LoginActivity.java :-
public class LoginActivity extends AppCompatActivity {
public static final String INTENTKEY_USERNAME = "IK_USERNAME";
public static final String INTENTKEY_USERID = "IK_USERID";
Button mloginbtn;
Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
mContext = this;
mloginbtn = this.findViewById(R.id.loginbtn);
mloginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(mContext,HomeActivity.class);
i.putExtra(INTENTKEY_USERNAME,"Fred");
i.putExtra(INTENTKEY_USERID,99L);
startActivity(i);
finish();
}
});
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity {
TextView mUsername, muserid;
Button mDone;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
mUsername = this.findViewById(R.id.username);
muserid = this.findViewById(R.id.userid);
mDone = this.findViewById(R.id.done);
mDone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
Intent i = this.getIntent();
mUsername.setText(i.getStringExtra(LoginActivity.INTENTKEY_USERNAME));
muserid.setText(String.valueOf(i.getLongExtra(LoginActivity.INTENTKEY_USERID,0)));
}
}
I'd do the following:
...
Intent intent = new Intent(getApplicationContext(),HomeActivity.class);
intent.putExtra("username", Bob)
startActivity(intent);
finish();
...
and then in home have:
Intent intent = getIntent();
String easyPuzzle = intent.getExtras().getString("username");

How to auto login with Firebase in Android Studio?

I am creating a restaurant app for members & non-members. The home page consist of 3 buttons- menu, sign-in and sign-up. I want to let non-members auto login (default phoneId)into the system when they tap on the menu button and members will just sign-in or sign-up each time.
I tried to use sharedPreferences (default phoneId) for the non-member auto login but I don't know whether the default phoneId can be sync with firebase. I want to track the transaction orders for the non-members. Is there any way to only let the default phoneId to have auto login function?
p/s I am just a beginner and doing this app for my project. pls help thanks.
MainActivity.java
public class MainActivity extends AppCompatActivity {
Button btnSignIn, btnSignUp, btnMenu;
public AppPreferences appPreference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appPreference = new AppPreferences(this);
btnMenu = (Button)findViewById(R.id.btnMenu);
btnSignUp = (Button)findViewById(R.id.btnSignUp);
btnSignIn = (Button)findViewById(R.id.btnSignIn);
btnMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent home = new Intent(MainActivity.this, Home.class);
//Here save user info to preferences
appPreference.setUserPhoneId(Constant.DEFAULT_PHONE_ID);
appPreference.setUserPassword(Constant.DEFAULT_PASSWORD);
startActivity(home);
}
});
btnSignUp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signUp = new Intent(MainActivity.this, SignUp.class);
startActivity(signUp);
}
});
btnSignIn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent signIn = new Intent(MainActivity.this, SignIn.class);
startActivity(signIn);
}
});
}
}
AppPreferences.java
public class AppPreferences {
// Class variables
private Context context;
private static SharedPreferences sharedPreferences;
private static SharedPreferences.Editor editor;
public static final String PREF_NAME = "iMenuApp";
private int PRIVATE_MODE = 0;
// Define your preferences key
private static final String USER_PHONE = "9876543210";
private static final String USER_PASSWORD = "12345";
public AppPreferences(Context context)
{
this.context = context;
sharedPreferences = this.context.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
if (sharedPreferences != null)
{
editor = sharedPreferences.edit();
}
}
//Store user PhoneId
public void setUserPhoneId(String userId){
String TAG = "AppPref:setUserId";
try
{
editor.putString(USER_PHONE, userId);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPhoneId
public String getUserPhoneId(){
return sharedPreferences.getString(USER_PHONE,"default_phone");
}
//Store userPassword
public void setUserPassword(String userPassword){
String TAG = "AppPref:setUserPassword";
try
{
editor.putString(USER_PASSWORD, userPassword);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
// Get userPassword
public String getUserPassword(){
return sharedPreferences.getString(USER_PASSWORD,"default_password");
}
}
the whole approach is rather questionable, because there is an anonymous authentication provider, which should be used for those "non-members" (and it can also be used together with security rules). storing the state of the authentication to Preferences is prone to errors, because it does not consider the actual state of the authentication - which will result in access denied, once the token expired.
I've also seen your previous question, while nevertheless the whole business logic is flawed.
... better see AccountManager, for how to properly store accounts on Android.
You need to do something like this,
MainActivity -> SignIn -> if SignIn success -> Next time you launch the app land to Home Activity
Try this,
1.) First, you define a new boolean preferences key, USER_LOGGED_IN and create setUserLoggedIn() and getUserLoggedIn() methods in your AppPreferences class as below.
private static final boolean USER_LOGGED_IN = false;
public static void setUserLoggedIn(boolean value) {
String TAG = "AppPref:setUserLoggedIn";
try{
editor.putBoolean(USER_LOGGED_IN, value);
editor.commit();
} catch (Exception e) {
Log.e(TAG, String.valueOf(e));
}
}
public static boolean getUserLoggedIn() {
return sharedPreferences.getBoolean(USER_LOGGED_IN, false);
}
2.) Then, in your SignIn Activity, If login success, set UserLoggedIn as true in your sharedPreferences.
3.) Finally, In your MainActivity, override onResume() method as follows,
#Override
protected void onResume() {
super.onResume();
boolean userLoggedIn = AppPreferences.getUserLoggedIn();
if(userLoggedIn){
MainActivity.this.startActivity(new Intent(getApplicationContext(), Home.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK));
}
}
Try this and let me know your feedback.
Thanks!

how to perform logout in actionbar

I need help. I have actionbar in my app. And I want my logout inside of it. How can I do that? I have already these things. But I don't have that session.java. I have attempt to copy others' code but it showed some errors. Please help me. Thanks guys!
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
logout();
return true;
}
return super.onOptionsItemSelected(item);
}
private void logout() {
session.logout();
startActivity(new Intent(this, MainActivity.class));
finish();
}
you need to use shared preference to keep the session and i think session.logout();this method created in a class where they keep the session using shared preference. ok right now i will tell you how can you keep your login session and how to logout.
step one : when you are trying to login and you got the success response through JSON Api or from your sqlite database just use shared preference and set positive flag value there.
setp two : and then when you click logout button from toolbar in onOptionsItemSelected method just change that shared preference's value to negative.
Like this sir?
public class LoginActivity extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String my_shared_preferences = "my_shared_preferences";
public static final String session_status = "session_status";
Boolean session = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
final TextView mShowDialog =(TextView) findViewById(R.id.txtShowDialog);
final TextView tvRegisterLink = (TextView) findViewById(R.id.tvRegisterLink);
//Check session login if TRUE then go directly MainActivity
sharedpreferences = getSharedPreferences(my_shared_preferences, Context.MODE_PRIVATE);
session = sharedpreferences.getBoolean(session_status, false);
if (session) {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
finish();
startActivity(intent);
}
tvRegisterLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LoginActivity.this, RegisterActivity.class);
LoginActivity.this.startActivity(registerIntent);
}
});
mShowDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder mbuilder = new AlertDialog.Builder(LoginActivity.this);
View mView = getLayoutInflater().inflate(R.layout.dialog_login,null);
final EditText hehe= mView.findViewById(R.id.etUsername);
final EditText hehe1= mView.findViewById(R.id.etPassword);
final Button bLogin = mView.findViewById(R.id.bSignIn);
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String Username = hehe.getText().toString();
final String Password = hehe1.getText().toString();
// Response received from the server
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putBoolean(session_status, true);
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
LoginActivity.this.startActivity(intent);
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
builder.setMessage("Login Failed")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
LoginRequest loginRequest = new LoginRequest(Username, Password, responseListener);
RequestQueue queue = Volley.newRequestQueue(LoginActivity.this);
queue.add(loginRequest);
}
});
mbuilder.setView(mView);
AlertDialog dialog = mbuilder.create();
dialog.show();
}
});
}
}

sharedpreferences not loading or saving

I'm trying to used sharedpreferences for when a user chooses a specific custom image they want in their storage for a part of a grid of images. I want the image they chose to show up even after they close the application and reopen it. The problem I'm having is that the sharedpreferences don't seem to be working. Nothing shows up as the background image for the grid item they've selected once they've closed the app or even just pressed the back button.
Do I have to create a sharedpreferences file myself? I can't figure out how to get to it or create one if so using androidstudio.
Here's my code for the class (Sorry if it's long and messy...I am new to coding and still testing things):
public class editCreations extends Activity {
public int mPosition = 0;
protected static Sounds sound = new Sounds();
private static int RESULT_LOAD_IMAGE = 1;
private MediaRecorder mRecorder;
private MediaPlayer mPlayer;
private String mOutputFile = Environment.getExternalStorageDirectory().getAbsolutePath();
private Drawable mImageFileName;
private Button recordBtn;
private Button stopBtn;
private Button playBtn;
private Button stopPlayBtn;
private ImageButton imgBtn;
private Drawable bg;
private String mPicturePath;
private ImageAdapter img = new ImageAdapter(this);
View.OnClickListener playListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(editCreations.this, "test", Toast.LENGTH_SHORT);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mRecorder.setOutputFile(mOutputFile);
recordBtn = (Button)findViewById(R.id.create_record_button);
recordBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
start(view);
}
});
stopBtn = (Button)findViewById(R.id.create_stop_record_button);
stopBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stop(view);
}
});
playBtn = (Button)findViewById(R.id.create_play_button);
playBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
play(view);
}
});
stopPlayBtn = (Button)findViewById(R.id.create_stop_button);
stopPlayBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
stopPlay(view);
}
});
imgBtn = (ImageButton)findViewById(R.id.imageButton);
Intent extra = getIntent();
Bundle extras = extra.getExtras();
// gave mPosition a default int to debug and find problem -> found it
mPosition = extras.getInt("position");
getSelectedFile(mPosition);
imgBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
});
}
public void start (View view) {
try {
mRecorder.prepare();
mRecorder.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recordBtn.setEnabled(false);
stopBtn.setEnabled(true);
Toast.makeText(editCreations.this, mPosition + "!", Toast.LENGTH_SHORT).show();
}
public void stop(View view){
try {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
stopBtn.setEnabled(false);
recordBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Stop recording...",
Toast.LENGTH_SHORT).show();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (RuntimeException e) {
e.printStackTrace();
}
}
public void play(View view) {
try{
mPlayer = new MediaPlayer();
mPlayer.setDataSource(mOutputFile);
mPlayer.prepare();
mPlayer.start();
playBtn.setEnabled(false);
stopPlayBtn.setEnabled(true);
Toast.makeText(getApplicationContext(), "Start play the recording...",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
public void stopPlay(View view) {
try {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
playBtn.setEnabled(true);
stopPlayBtn.setEnabled(false);
Toast.makeText(getApplicationContext(), "Stop playing the recording...",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e){
e.printStackTrace();
}
}
public void getSoundPosition(int position) {
mOutputFile = mOutputFile + "/Lollatone_clip_" + mPosition + ".3gpp";
// use to get proper image and sound files and edit output file to proper name
}
public void getSelectedFile(int position) {
switch (mPosition) {
case 0:
imgBtn.setBackgroundResource(R.drawable.sample_0);
imgBtn.refreshDrawableState();
break;
case 1:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 2:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 3:
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
break;
case 4:
imgBtn.setBackgroundResource(R.drawable.sample_4);
imgBtn.refreshDrawableState();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_creations, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode,resultCode,data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null,null,null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
mPicturePath = cursor.getString(columnIndex);
cursor.close();
imgBtn.setImageBitmap(BitmapFactory.decodeFile(mPicturePath));
imgBtn.refreshDrawableState();
// String picturePath contains the path of
// selected image
}
}
protected void onPause() {
super.onPause();
//need an editor object to make preference changes
// all objects are from android.context.Context
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("img_" + mPosition, mPicturePath);
editor.commit();
}
protected void onResume() {
super.onResume();
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
mPicturePath = sharedPref.getString("img_" + mPosition, "img_" + mPosition);
}
}
You are using SharedPreferences correctly but you are not placing the code in the right activity lifecycle methods. You are reading the preference on onCreate() and saving on onStop() so maybe what you can do it save the preference on onPause() (to make sure it gets saved earlier) and reload on onResume() instead of onCreate() (the latter only occurs once in the life cycle of an activity).
Also, you might want to check if Context.getSharedPreferences() would be a better choice for this, since it's shared between more than just one activity.

How can I make my android app have SharedPreferences as just one set of preferences, so that I can control it and clear the preferences with a button

I am trying to have SharedPreferences once and control it to different methods rather than having different SharedPreferences in different methods. I have SharedPreferences in the onCreate, LoadPreferences, SavePreferences and ClearTextViews methods. I want to make it so that I have preferences saved to the TextViews from entered text in the EditText and then be able to clear them all with a button. Please help me if you can. Here is the relevant code:
public class notesActivity extends Activity implements OnClickListener
{
Button saveNote;
Button clearText;
EditText note;
TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
SharedPreferences spNote;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes);
saveNote = (Button)this.findViewById(R.id.saveNotes);
saveNote.setOnClickListener(this);
clearText = (Button)this.findViewById(R.id.clearAllText);
clearText.setOnClickListener(this);
textSavedNote1 = (TextView)findViewById(R.id.stringSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.stringSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.stringSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.stringSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.stringSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.stringSavedNote6);
note = (EditText)this.findViewById(R.id.notes);
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// Goes back to the home screen
case R.id.item1: Intent i = new Intent(notesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
// Refreshes the page.
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
public void onClick (View v){
if(v==saveNote){
SavePreferences("NOTE1", note.getText().toString());
LoadPreferences();
note.setText("");
if(textSavedNote1.getText().toString().length()>0){
SavePreferences("NOTE2", note.getText().toString());
LoadPreferences();
note.setText("");
}
else{
}
}
else if(v==clearText){
ClearTextViews();
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
textSavedNote1.setText(strSavedNote1);
textSavedNote2.setText(strSavedNote2);
textSavedNote3.setText(strSavedNote3);
textSavedNote4.setText(strSavedNote4);
textSavedNote5.setText(strSavedNote5);
textSavedNote6.setText(strSavedNote6);
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}
There are some links that can be helpfull
How to use SharedPreferences in Android to store, fetch and edit values
http://developer.android.com/reference/android/content/SharedPreferences.html
Examples
How to use SharedPreferences
http://android-er.blogspot.com.br/2011/01/example-of-using-sharedpreferencesedito.html
Try the code below.
/*I have added one more button, on click on that button i have set call clearText function and set all text empty, each time before clicking on save button you click first clear button then next value will be inserted in next textview.*/
public class SharedPreferenceJustOneSetOfPreferencesActivity extends Activity implements OnClickListener{
private Button saveNote,clearText,ClearAll;
static TextView textSavedNote1, textSavedNote2, textSavedNote3, textSavedNote4, textSavedNote5, textSavedNote6;
private EditText note;
private SharedPreferences spNote;
private static final String TAG = SharedPreferenceJustOneSetOfPreferencesActivity.class.getSimpleName();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initView();
saveInPreference();
}
private void initView() {
textSavedNote1 = (TextView)findViewById(R.id.textSavedNote1);
textSavedNote2 = (TextView)findViewById(R.id.textSavedNote2);
textSavedNote3 = (TextView)findViewById(R.id.textSavedNote3);
textSavedNote4 = (TextView)findViewById(R.id.textSavedNote4);
textSavedNote5 = (TextView)findViewById(R.id.textSavedNote5);
textSavedNote6 = (TextView)findViewById(R.id.textSavedNote6);
note = (EditText)findViewById(R.id.note);
saveNote = (Button)findViewById(R.id.saveNote);
clearText = (Button)findViewById(R.id.clearText);
ClearAll = (Button)findViewById(R.id.ClearAll);
saveNote.setOnClickListener(this);
clearText.setOnClickListener(this);
ClearAll.setOnClickListener(this);
}
private void saveInPreference() {
spNote = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = spNote.edit();
edit.putString("note"+saveNote,note.getText().toString());
edit.commit();
}
public boolean onCreateOptionsMenu(Menu menu){
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.item1: Intent i = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, UserSettingActivity.class);
startActivity(i);
case R.id.item2:
Intent intent = new Intent(SharedPreferenceJustOneSetOfPreferencesActivity.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
return true;
case R.id.item3:
finish();
startActivity(getIntent());
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onClick(View view) {
if (view == saveNote) {
String textvedNote1 =textSavedNote1.getText().toString();
String textvedNote2= textSavedNote2.getText().toString();
String textvedNote3 =textSavedNote3.getText().toString();
String textvedNote4= textSavedNote4.getText().toString();
String textvedNote5 =textSavedNote5.getText().toString();
String textvedNote6= textSavedNote6.getText().toString();
if (textvedNote1.equals("")) {
SavePreferences("NOTE1", note.getText().toString());
Log.e(TAG,"textvedNote1: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
}else if (textvedNote2.equals("")&& !textvedNote1.equals("")) {
SavePreferences("NOTE2", note.getText().toString());
Log.e(TAG,"textvedNote2: Inside "+textvedNote1.length());
LoadPreferences();
note.setText("");
} else if (textvedNote3.equals("")&& !textvedNote2.equals("")) {
Log.e(TAG,"textvedNote3: Inside "+textvedNote2.length());
SavePreferences("NOTE3", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote4.equals("")&& !textvedNote3.equals("")) {
Log.e(TAG,"textvedNote4: Inside "+textvedNote3.length());
SavePreferences("NOTE4", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote5.equals("")&& !textvedNote4.equals("")) {
Log.e(TAG,"textvedNote5: Inside "+textvedNote4.length());
SavePreferences("NOTE5", note.getText().toString());
LoadPreferences();
note.setText("");
} else if (textvedNote6.equals("")&& !textvedNote5.equals("")) {
SavePreferences("NOTE6", note.getText().toString());
Log.e(TAG,"textvedNote6: Inside "+textvedNote5.length());
LoadPreferences();
note.setText("");
}
} else if (view == clearText) {
ClearTextViews();
}else if (view == ClearAll){
ClearTextViews();
textSavedNote1.setText("");
textSavedNote2.setText("");
textSavedNote3.setText("");
textSavedNote4.setText("");
textSavedNote5.setText("");
textSavedNote6.setText("");
}
}
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedNote1 = sharedPreferences.getString("NOTE1", "");
String strSavedNote2 = sharedPreferences.getString("NOTE2", "");
String strSavedNote3 = sharedPreferences.getString("NOTE3", "");
String strSavedNote4 = sharedPreferences.getString("NOTE4", "");
String strSavedNote5 = sharedPreferences.getString("NOTE5", "");
String strSavedNote6 = sharedPreferences.getString("NOTE6", "");
if (!strSavedNote1.equals("")) {
Log.e(TAG,"LoadPreferences1: "+strSavedNote1);
textSavedNote1.setText(strSavedNote1);
} else if (!strSavedNote2.equals("")) {
Log.e(TAG,"LoadPreferences2: "+strSavedNote2);
textSavedNote2.setText(strSavedNote2);
} else if (!strSavedNote3.equals("")) {
Log.e(TAG,"LoadPreferences3: "+strSavedNote3);
textSavedNote3.setText(strSavedNote3);
} else if (!strSavedNote4.equals("")) {
textSavedNote4.setText(strSavedNote4);
} else if (!strSavedNote5.equals("")) {
textSavedNote5.setText(strSavedNote5);
} else if (!strSavedNote6.equals("")) {
textSavedNote6.setText(strSavedNote6);
}
}
private void ClearTextViews(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.commit();
}
}

Categories

Resources