I am working on a app and while getting my shared preferences(which are saved in login activity), i am trying to get it in dashboard fragment but i am not be able to get it. After this i checked whether the is saved or not so then i used
boolean ok= editor.commit();
Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();
My toast shows message as Saved:true
After this try i am assuming that my data is saved to preferecnces but i am unable to fetch it. Below is my dashboard fragmenr code.
public class dashboard extends Fragment {
private TextView comp_text,mail_text,gst_text;
private String mUsername;
private SharedPreferences mSharedPreferences;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//this inflates out tab layout file.
View x = inflater.inflate(R.layout.dashboard_frag, null);
comp_text=(TextView)x.findViewById(R.id.company_id);
mail_text=(TextView)x.findViewById(R.id.email_id);
gst_text= (TextView)x.findViewById(R.id.gst_id);
initSharedPreferences();
Toast.makeText(getActivity(), "Logged member-> "+mUsername, Toast.LENGTH_LONG).show();
return x;
}
private void initSharedPreferences() {
mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");
}
}
Here my Toast show **logged member-> **, that means musername have nothing to print and preferences are unable get.
I'm still confused this is my point of view if you want i can show where i saved preferences.
Help will be appreciated !
THANKS !
EDIT 1 ----
Here is my onResponse function where i saved preferences.
public void onResponse(Call<ServerResponse> call, retrofit2.Response<ServerResponse> response) {
if(response.isSuccessful()) {
ServerResponse serverResponse = response.body();
if(serverResponse.getMessage().equals(username)) {
SharedPreferences.Editor editor = mSharedPreferences.edit();
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
Toast.makeText(Login.this, "Saved: "+ok, Toast.LENGTH_LONG).show();
goToProfile();
}
} else {
Gson gson = new Gson();
ServerResponse errorResponse = null;
try {
errorResponse = gson.fromJson(response.errorBody().string(), ServerResponse.class);
} catch (IOException e) {
e.printStackTrace();
}
Snackbar.make(loginButton,errorResponse.getMessage(),Snackbar.LENGTH_SHORT).show();
}
}
Try this
SharedPreferences.Editor editor = getSharedPreferences("my_prefs", MODE_PRIVATE).edit();;
editor.putBoolean("LoggedIn",true);
editor.putString(Constants.USERNAME,serverResponse.getMessage());
boolean ok= editor.commit();
And then in Fragment
mSharedPreferences = getActivity().getSharedPreferences("my_prefs", MODE_PRIVATE); ;
mUsername = mSharedPreferences.getString(Constants.USERNAME, "");
Related
I have a login activity that works fine,after successfully login i get token which i send it to the webview fragment by SharedPreferences and pass it to WebviewClient but it doesn't redirect to the homepage URL of the site which is inside webview,it's redirect to login page URL of the site inside Webview.I didn't find helpful solution.
Thanks in advance
My code:
Login Activity
btnSignin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fetchToken();
}
});
}
private void fetchToken() {
String email = txtUsername.getText().toString();
String password = txtPassword.getText().toString();
UserRequest userRequest = new UserRequest(email, password);
RxUtil.asyncConsumer(service.getToken(userRequest), new Consumer<TokenResponse>() {
#Override
public void accept(TokenResponse response) throws Exception {
Log.d("ResponseToken", "" + response.getSuccess().getToken());
if (response.getSuccess() != null) {
String token = response.getSuccess().getToken();
setKeyToken(token);
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
}else {
Toast.makeText(LoginActivity.this, "Something went wrong please try again", Toast.LENGTH_LONG).show();
}
}
});
}
private void setKeyToken(String token) {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString(KEY_TOKEN, token);
editor.apply();
}
public String getKeyToken() {
preferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
return preferences.getString(KEY_TOKEN, "");
}
Web Fragment inside Main Activity
public class WebFragment extends Fragment {
private WebView webView;
private ProgressBar progressBar;
private String url = "some_url";
private String token;
private SharedPreferences preferences;
public WebFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_web, container, false);
webView = view.findViewById(R.id.web_view);
progressBar = view.findViewById(R.id.progress_bar);
preferences = getActivity().getSharedPreferences(LoginActivity.SHARED_PREFS, Context.MODE_PRIVATE);
initWebView(url);
return view;
}
private void initWebView(String url) {
webView.loadUrl(url);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebClient());
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
webView.getSettings().setAppCacheEnabled(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setSupportMultipleWindows(true);
webView.getSettings().setUseWideViewPort(true);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
}
public class WebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
progressBar.setVisibility(View.VISIBLE);
super.onPageStarted(view, url, favicon);
}
#Nullable
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
try {
String token = preferences.getString(LoginActivity.KEY_TOKEN, "DEFAULT");
Log.d("Arg", "" + token);
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder().url(url).addHeader("Authorization", "Bearer " + token).build();
Response response = okHttpClient.newCall(request).execute();
return new WebResourceResponse(response.header("text/html", response.body().contentType().type()),
response.header("content-encoding", "utf-8"),response.body().byteStream());
} catch (ProtocolException e) {
//return null to tell WebView we failed to fetch it WebView should try again.
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
#Override
public void onPageFinished(WebView view, String url) {
progressBar.setVisibility(View.GONE);
super.onPageFinished(view, url);
}
}
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!
I have an Activity that receives and displays information from the web server and saves it to the database and, if it has already received the information once, it will read from the database.
There is no problem running the program, only when the user enters the activity and still does not receive the information from the server, exit the activity, in another Activity the application crashes.
This problem is to quit the activity because when staying in activity and loaded data completely, we have not any problems. also when reading data from the database we have not any problems.
How can stop receive data when the user quit the activity or solve this problem form another way.
This is my activity codes:
public class ShowProduct extends AppCompatActivity {
private RequestQueue mQueue;
private String id;
private Products products;
private DatabaseHelper databaseHelper;
private ProgressBar progressBar;
private Typeface IranSans,IranSansBold;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_product);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
databaseHelper = new DatabaseHelper(this);
products = new Products();
progressBar = (ProgressBar)findViewById(R.id.progressBar);
IranSans = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb.ttf");
IranSansBold = Typeface.createFromAsset(getAssets(),"fonts/IRANSansWeb_Bold.ttf");
Bundle extras = getIntent().getExtras();
id= extras.getString("id");
try {
if (databaseHelper.dbContentChecker(id)) {
if (connectionCheck() == false){
Intent intent = new Intent(this, NoInternetConnection.class);
startActivity(intent);
}
String url = "https://website.com/webserver/?id=" + id;
mQueue = Volley.newRequestQueue(this);
jsonParse(url);
} else {
products = databaseHelper.getOneProduct(id);
showFromDB(products);
}
}catch (Exception ex){
}
//footer set
Footer footer = new Footer();
footer.footerSet(ShowProduct.this, this);
}
private void showFromDB(Products products) {
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(products.getName());
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(products.getImage())
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(products.getContent()));
progressBar.setVisibility(View.GONE);
}
private void jsonParse(String url) {
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONArray("send");
JSONObject send = jsonArray.getJSONObject(0);
String title = send.getString("title");
String image = send.getString("image");
String content = send.getString("content");
TextView tx = (TextView)findViewById(R.id.title);
tx.setTypeface(IranSansBold);
tx.setText(title);
ImageView im = (ImageView)findViewById(R.id.image);
Glide.with(ShowProduct.this)
.asBitmap()
.load(image)
.into(im);
TextView tc = (TextView)findViewById(R.id.content);
tc.setTypeface(IranSans);
tc.setText(Html.fromHtml(content));
//Save in Database
try {
products.setProductId(id);
products.setName(title);
products.setImage(image);
products.setContent(content);
databaseHelper.editProduct(products);
}catch (Exception ex){
Toast.makeText(ShowProduct.this, "Error DB", Toast.LENGTH_SHORT).show();
}
progressBar.setVisibility(View.GONE);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
error.printStackTrace();
}
});
mQueue.add(request);
//Toast.makeText(getApplicationContext(), ""+Temp , Toast.LENGTH_SHORT).show();
}
public boolean connectionCheck() {
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
return true;
}
else
return false;
}
}
First of all you should think about your architecture. Handling fetching data inside an Activity is not a good practice. Look at MVVM or MVP and try to put your data fetching logic in another layer.
For your specific problem you should try to cancle the request in the onStop() method of the Activity, see:
https://developer.android.com/training/volley/simple#cancel
I have an app where I have a fragment.Let's call it mainScreen. In mainScreen there's a button and onClick() opens second fragment. Let's call it FragmentHomePage. In FragmentHomePage i have a retrofit. There's a button named logOut. My problem is, when user not clicked logOut, i want to save this fragment and load this fragment. In default when app starts, opens mainScreen, but if user not clicks logOut, i need open FragmentHomePage on app start. How can i do this?
public class FragmentHomePage extends BaseFragment {
View mainView;
TextView fullName, userName, email;
Button logOut;
ApiClient apiClient = ApiClient.getInstance();
SupportObjToken supportopToken = new SupportObjToken();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mainView = inflater.inflate(R.layout.home_page, container, false);
init(mainView);
newTokenCall();
return mainView;
}
private void init(View v) {
fullName = v.findViewById(R.id.fullName);
userName = v.findViewById(R.id.user);
email = v.findViewById(R.id.mail);
logOut = v.findViewById(R.id.logOut);
}
public void newTokenCall() {
String clientID = SharedPreferencesManager.getInstance().getClientID();
String clientSecret = SharedPreferencesManager.getInstance().getClientSecret();
String refreshToken = SharedPreferencesManager.getInstance().getRefreshToken();
String newRefreshToken = SharedPreferencesManager.getInstance().getNewRefreshToken();
final String firstName = SharedPreferencesManager.getInstance().getFirstName();
final String lastName = SharedPreferencesManager.getInstance().getLastName();
final String mail = SharedPreferencesManager.getInstance().getEmail();
final String user = SharedPreferencesManager.getInstance().getUsername();
supportopToken.setGrantType("refresh_token");
supportopToken.setClientId(clientID);
supportopToken.setClientSecret(clientSecret);
supportopToken.setRefreshToken(refreshToken);
Call<ResponseBody> newToken = apiClient.newToken(supportopToken);
newToken.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (IOException | JSONException e) {
e.printStackTrace();
}
} else if (response.code() == 401) {
supportopToken.setRefreshToken(SharedPreferencesManager.getInstance().getNewRefreshToken());
Call<ResponseBody> newToken1 = apiClient.newToken(supportopToken);
newToken1.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
try {
String newDataAccess = response.body().string();
JSONObject obj = new JSONObject(newDataAccess);
String newAccessToken = obj.getString("accessToken");
String newRefreshToken = obj.getString("refreshToken");
SharedPreferencesManager.getInstance().setNewAccessToken(newAccessToken);
SharedPreferencesManager.getInstance().setNewRefreshToken(newRefreshToken);
fullName.setText(firstName + " " + lastName);
userName.setText(user);
email.setText(mail);
} catch (JSONException | IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getActivity(), "Error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Toast.makeText(getActivity(), "You're on failure getting new Token", Toast.LENGTH_SHORT).show();
}
});
}}
How can i do this part? Thanks. Yeah and not give negative vote. I'm a beginner on this site)).
Here's the activity where i'm launching the fragments.
public class MainActivity extends AppCompatActivity implements FragmentChangeListener {
FragmentActivity fragmentActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ApiClient.initializeInstance("simple web page");
fragmentActivity = new FragmentActivity();
this.replaceFragment(fragmentActivity, true);
SharedPreferencesManager.init(this);
}
#Override
public void replaceFragment(BaseFragment fragment, Boolean isAddToBackStack) {
String backStateName = fragment.getClass().getName();
FragmentManager manager = getFragmentManager();
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(R.id.container, fragment, fragment.toString());
transaction.addToBackStack(backStateName);
transaction.commit();
}}
In your mainScreen button onclick, add a key to shared preferences like this
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_in");
editor.apply();
inside your logOut button onclick in FragmentHomePage add the following code
SharedPreferences.Editor editor = getSharedPreferences("APP_PREF", MODE_PRIVATE).edit();
editor.putString("state", "logged_out");
editor.apply();
Now inside your first fragment's oncreate add this
SharedPreferences prefs = getSharedPreferences("APP_PREF", MODE_PRIVATE);
String state = prefs.getString("state", "state");
if(state.equals("logged_in"){
//load second fragment here
}
save a boolean value in SharedPreferences with default value false.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
when ever you come to the FragmentHomePage , set this value to true.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", true).apply();
When user clicks logout button , set this value to false again.
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).edit().putBoolean("ISUSERALREADYLOGGEDIN", false).apply();
From the Base Activity which is keeping these fragments,
When you launch the mainScreen fragment, check this value, with this code :
PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
If the value is true, launch the HomeFragment, else launch the mainScreen fragment.
Use this function to launch the fragment:
public void launchFragmentByReplacing(Fragment fragment, String incomingFragmentTag) {
FragmentTransaction transaction = manager.beginTransaction();
transaction.replace(frameLayout.getId(), fragment, incomingFragmentTag);
transaction.commit();
manager.executePendingTransactions();
}
In your case, right before :
this.replaceFragment(fragmentActivity, true);
check for the SharedPref value.
Boolean isloggedIn = PreferenceManager.getDefaultSharedPreferences(AppLevelConstraints.getAppContext()).getBoolean("ISUSERALREADYLOGGEDIN", false);
if(isloggedIn) //is true
this.replaceFragment(new FragmentActivity(), true);
else
this.replaceFragment(new FragmentHomePage(), true);
I am creating an android app for which I have created login and signup pages.
I want to implement the "keep me logged in" functionality in the login page.
I think I know what to do but almost anything I try is giving an error.
I have to store the state of checkbox in a SharedPreference and then use it with an if else statement, if it is checked it will skip the login activity and start the main activity, otherwise the login activity.
It would be helpful if someone could provide a sample code.
ChechBox keeplog = (CheckBox)findBiewById(R.Id.checkbox1)
How can I store the check state in Shared Preference and how to fetch its state in the form of boolean or string so that it can be used with if-else statement?
Try the following way, declare one boolean variable.
CheckBox keeplog = (CheckBox) findViewById(R.id.checkBox1);
boolean isChecked = false;
Then store the state of checkbox in shared preferences with CheckedChangeListener.
keeplog.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("isChecked", isChecked);
editor.commit();
}
});
Then now get the state of checkbox from SharedPreferences using following way.
SharedPreferences settings1 = getSharedPreferences("PREFS_NAME", 0);
isChecked = settings1.getBoolean("isChecked", false);
Now check with the if statement and start your activity like the following
if (isChecked) {
Intent i = new Intent(MainActivity.this, ThirdActivity.class);
startActivity(i);
} else {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivity(i);
}
Thank you.
Try the following, I have pasted the code about how to connect & login to ejabberd server as without it the code was looking incomplete for Remember Me functionality. I have added comments for explaining how to store & retrieve values in SharedPrefernces.
public class Login extends Activity
{
private XMPPConnection connection;
private ProgressBar progressBar;
private EditText userId;
private EditText password;
private CheckBox rememberMe;
private SharedPreferences sharedPreferences;
private Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
userId = (EditText) findViewById(R.id.user_id);
password = (EditText) findViewById(R.id.password);
rememberMe = (CheckBox) findViewById(R.id.remember_me);
progressBar = (ProgressBar) findViewById(R.id.login_progress);
//Retrieving SharedPreferences
sharedPreferences = this.getPreferences(Context.MODE_PRIVATE);
//Retrieving editor
editor = sharedPreferences.edit();
//Retrieving remember me checkbox's set value which if was stored in SharedPreferences
if(sharedPreferences.getBoolean(getString(R.string.remember_me), false))
{
String uId, pass;
uId = sharedPreferences.getString(getString(R.string.user_id), "");
pass = sharedPreferences.getString(getString(R.string.password), "");
userId.setText(uId);
password.setText(pass);
rememberMe.setChecked(sharedPreferences.getBoolean(getString(R.string.remember_me), false));
new Connection().execute(uId, pass);
}
}
public void login(View view)
{
new Connection().execute(userId.getText().toString(), password.getText().toString());
}
private class Connection extends AsyncTask<String, Void, Integer>
{
private static final int CONNECTION_FAILURE = 0;
private static final int LOGIN_FAILURE = 1;
private static final int SUCCESS = 2;
protected void onPreExecute()
{
progressBar.setVisibility(ProgressBar.VISIBLE);
}
protected Integer doInBackground(String... strings)
{
ConnectionConfiguration conConfig = new ConnectionConfiguration("192.168.1.66", 5222, "domain");
connection = new XMPPConnection(conConfig);
try
{
connection.connect();
Log.i("TESTING", "CONNECTED TO " + connection.getHost());
}
catch(Exception e)
{
Log.e("TESTING", e.getMessage());
return CONNECTION_FAILURE;
}
try
{
connection.login(strings[0], strings[1]);
Log.i("TESTING", "LOGGED IN AS " + connection.getUser());
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
}
catch(Exception e)
{
Log.e("TESTING", e.getMessage());
return LOGIN_FAILURE;
}
return SUCCESS;
}
protected void onPostExecute(Integer integer)
{
progressBar.setVisibility(ProgressBar.GONE);
switch(integer)
{
case CONNECTION_FAILURE:
Toast.makeText(getApplicationContext(), "Failed to connect to the server.", Toast.LENGTH_LONG).show();
break;
case LOGIN_FAILURE:
Toast.makeText(getApplicationContext(), "Please check your user id and or password.", Toast.LENGTH_LONG).show();
break;
case SUCCESS:
if(rememberMe.isChecked())
{
//Setting value in SharedPrefernces using editor.
editor.putBoolean(getString(R.string.remember_me), rememberMe.isChecked());
editor.putString(getString(R.string.user_id), userId.getText().toString());
editor.putString(getString(R.string.password), password.getText().toString());
//Committing the changes.
editor.commit();
}
else
//Clearing SharedPreferences.
sharedPreferences.edit().clear().commit();
startActivity(new Intent(getApplicationContext(), Home.class));
}
}
}
}