I am wanting to delete my authToken that was set on the LoginActivity but I cannot from my LogoutFragment which is part of the the MainActivity. Wondering where I could be going wrong. I seen a few threads about this but none seem to work. I am able to easily clear the shared pref when in the LoginActivity
Thanks
package com.mpl.mpl.ui.logout;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebView;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.mpl.mpl.LoginActivity;
import com.mpl.mpl.databinding.FragmentLogoutBinding;
import com.mpl.mpl.ui.logout.LogoutViewModel;
public class LogoutFragment extends Fragment {
private LogoutViewModel logoutViewModel;
private FragmentLogoutBinding binding;
private WebView webView;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
logoutViewModel =
new ViewModelProvider(this).get(LogoutViewModel.class);
binding = FragmentLogoutBinding.inflate(inflater, container, false);
View root = binding.getRoot();
CookieSyncManager cookieSyncMngr = CookieSyncManager.createInstance(getActivity());
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
Intent intent = new Intent(getActivity(), LoginActivity.class);
SharedPreferences preferences = getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
startActivity(intent);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
}
The LoginFragment:
package com.mpl.mpl.ui.login;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.mpl.mpl.MainActivity;
import com.mpl.mpl.R;
import com.mpl.mpl.databinding.FragmentLoginBinding;
import com.mpl.mpl.restClient.MplRestClient;
import org.json.JSONException;
import org.json.JSONObject;
public class LoginFragment extends Fragment implements View.OnClickListener {
private LoginViewModel loginViewModel;
private FragmentLoginBinding binding;
private WebView webView;
private Button button;
private Button forgottenPasswordBtn;
private Button registerBtn;
private EditText email;
private EditText password;
private EditText errorMessageField;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
loginViewModel =
new ViewModelProvider(this).get(LoginViewModel.class);
binding = FragmentLoginBinding.inflate(inflater, container, false);
View root = binding.getRoot();
webView = (WebView) root.findViewById(R.id.loginWebView);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
SharedPreferences pref;
pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String token = pref.getString("authToken", null);
if (token != null) {
webView.loadUrl("javascript:testFunction('" + token + "');");
}
try {
getLoginStatus();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
webView.loadUrl("hidden");
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new IJavascriptHandler(), "cpjs");
password = (EditText) root.findViewById(R.id.passwordField);
email = (EditText) root.findViewById(R.id.emailField);
errorMessageField = (EditText) root.findViewById(R.id.statusMessage);
button = (Button) root.findViewById(R.id.buttonTest);
button.setOnClickListener(this);
registerBtn = root.findViewById(R.id.registerBtn);
registerBtn.setOnClickListener(this);
forgottenPasswordBtn = (Button) root.findViewById(R.id.forgottenPasswordBtn);
forgottenPasswordBtn.setOnClickListener(this);
return root;
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}
#Override
public void onClick(View v) {
//do what you want to do when button is clicked
switch (v.getId()) {
case R.id.buttonTest:
try {
getLoginStatus();
} catch (JSONException e) {
e.printStackTrace();
}
break;
case R.id.forgottenPasswordBtn:
Uri uri = Uri.parse("hidden"); // missing 'http://' will cause crashed
Intent forgottenIntent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(forgottenIntent);
break;
case R.id.registerBtn:
NavController navController = Navigation.findNavController(getActivity(), R.id.nav_host_fragment_login_content_main);
navController.navigate(R.id.nav_register);
break;
}
}
public void getLoginStatus() throws JSONException {
MplRestClient.post("ajax/logintest.php?eml=" + email.getText().toString() + "&pwdr=" + password.getText().toString(), null, new JsonHttpResponseHandler() {
#SuppressLint("SetTextI18n")
#Override
public void onSuccess(int statusCode, cz.msebera.android.httpclient.Header[] headers, JSONObject response) {
// If the response is JSONObject instead of expected JSONArray
try {
String message = response.getString("status");
switch (message) {
case "verify":
errorMessageField.setText("Please Verify Your Email");
errorMessageField.setVisibility(View.VISIBLE);
break;
case "success":
String token = response.getString("token");
errorMessageField.setText("");
errorMessageField.setVisibility(View.GONE);
webView.loadUrl("javascript:testFunction('" + token + "');");
break;
default:
errorMessageField.setText("Please Check Your Details");
errorMessageField.setVisibility(View.VISIBLE);
break;
}
} catch (Exception e) {
Toast.makeText(getActivity(), "fail",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(int statusCode, cz.msebera.android.httpclient.Header[] headers, String responseString, Throwable throwable) {
super.onFailure(statusCode, headers, responseString, throwable);
}
});
}
final class IJavascriptHandler {
IJavascriptHandler() {
}
#JavascriptInterface
public void sendToAndroid(String text) {
if (text.length() > 11) {
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.commit();
pref = getActivity().getPreferences(Context.MODE_PRIVATE);
String id = pref.getString("authToken", null);
Intent intent = new Intent(getActivity(), MainActivity.class);
startActivity(intent);
}
}
}
}
The LoginFragment is part of the LoginActivity, the shared preference is set in the IJavascriptHandler part
Your Problem
This is how you're setting the preference:
SharedPreferences pref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.commit();
This is how you're clearing:
SharedPreferences preferences = getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.clear();
editor.apply();
See the difference?
When you set the preferences with getActivity().getPreferences(Context.MODE_PRIVATE) you're setting it to an Activity-specific file named after the activity: see the documentation.
When you get the preferences with getContext().getSharedPreferences("authToken", Context.MODE_PRIVATE) you're trying to access an app-wide set of preferences named "authToken": see the documentation.
So you're writing to one place and reading from another so of course it's not going to match up.
A Solution
Be consistent in how you get and set preferences. The easiest way to go about that is to use PreferenceManager.getDefaultSharedPreferences for app-wide preferences.
To set:
SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(getActivity())
SharedPreferences.Editor edt = pref.edit();
edt.putString("authToken", text);
edt.apply();
To clear:
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getContext())
SharedPreferences.Editor editor = preferences.edit();
editor.remove("authToken")
editor.apply();
Related
so i am making a password manager app for android and i have 1 activity and fragments im using room for sql and all of that works fine but when i rotate the screen the app crashes and im not sure why, it says that it cant find the constructor on the configuration change but if that was the case why would it work in the first place :(
the fragment code
package app.web.fragments.passwords;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import com.google.firebase.analytics.FirebaseAnalytics;
import app.web.R;
import app.web.room_password.Password;
import app.web.view_model.PasswordViewModel;
public class Password_Add_Fragment extends Fragment {
private EditText username, password;
// priority is number picker
private NumberPicker numberPicker;
private Button insert, yeetAll;
private PasswordViewModel passwordViewModel;
private FirebaseAnalytics firebaseAnalytics;
public Password_Add_Fragment(FirebaseAnalytics firebaseAnalytics){
this.firebaseAnalytics = firebaseAnalytics;
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
if (container==null){
return null;
}
View view = inflater.inflate(R.layout.fragment_all_passwords_by_category, container, false);
setButtons(view);
return view;
}
private void setButtons(View view) {
passwordViewModel = new ViewModelProvider(getActivity()).get(PasswordViewModel.class);
username = view.findViewById(R.id.edit_text_add_username);
password = view.findViewById(R.id.edit_text_add_password);
numberPicker = view.findViewById(R.id.number_picker_priority_password);
numberPicker.setMinValue(1);
numberPicker.setMaxValue(100);
insert = view.findViewById(R.id.btn_password_save);
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getContext(), "Insert", Toast.LENGTH_SHORT).show();
String usernameP = username.getText().toString().trim();
String passwordP = password.getText().toString().trim();
int x = numberPicker.getValue();
if (!usernameP.isEmpty() && !passwordP.isEmpty() && x >= 1){
Password passwordX = new Password(usernameP,passwordP,x);
passwordViewModel.insert(passwordX);
Toast.makeText(getContext(), "Saved", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getContext(), "Cant be empty", Toast.LENGTH_SHORT).show();
}
}
});
yeetAll = view.findViewById(R.id.btn_password_delete_all);
yeetAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
passwordViewModel.deleteAllPasswords();
Toast.makeText(getContext(), "Deleted All", Toast.LENGTH_SHORT).show();
}
});
}
}
the crash log
Full crash log
nevermind the fix was to just have an empty constructor in the fragment class.
The title says it all. I am attempting to send an ArrayList that has data inside from one fragment to another and then switch and show the second fragment (the one that just received the ArrayList).
here is my MainActivity.java:
package;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import com.google.android.material.navigation.NavigationView;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import android.view.Menu;
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration mAppBarConfiguration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
NavigationView navigationView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each menu should be considered as top level destinations.
mAppBarConfiguration = new AppBarConfiguration.Builder(
R.id.nav_home, R.id.nav_display)
.setDrawerLayout(drawer)
.build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, mAppBarConfiguration);
NavigationUI.setupWithNavController(navigationView, navController);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
return NavigationUI.navigateUp(navController, mAppBarConfiguration) || super.onSupportNavigateUp();
}
}
here is my HomeFragment.java (the sending fragment):
package;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import androidx.navigation.Navigation;
import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.vision.FirebaseVision;
import com.google.firebase.ml.vision.common.FirebaseVisionImage;
import com.google.firebase.ml.vision.text.FirebaseVisionText;
import com.google.firebase.ml.vision.text.FirebaseVisionTextDetector;
import com.mvsolutions.snap.R;
import com.mvsolutions.snap.ui.display.DisplayFragment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import static android.app.Activity.RESULT_OK;
public class HomeFragment extends Fragment {
private HomeViewModel homeViewModel;
private ImageView imageView;
private Button captureImageButton, detectButton, pickButton;
private Bitmap imageBitmap;
private TextView capturedTextView;
static final int REQUEST_IMAGE_CAPTURE = 1;
private static final int RESULT_LOAD_IMAGE = 101;
public View onCreateView(#NonNull final LayoutInflater inflater,
final ViewGroup container, Bundle savedInstanceState) {
//View view = inflater.inflate(R.layout.fragment_home, container, false);
View root = inflater.inflate(R.layout.fragment_home, container, false);
detectButton = root.findViewById(R.id.action_homeFragment_to_displayFragment2);
//detectButton.setOnClickListener((View.OnClickListener) this);
//return view;
homeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
//View v = inflater.inflate(R.layout.fragment_display, container, false);
imageView = root.findViewById(R.id.home_image_view_img);
capturedTextView = root.findViewById(R.id.home_text_view_txt);
captureImageButton = root.findViewById(R.id.capture_image_btn);
detectButton = root.findViewById(R.id.detect_text_btn);
//pickButton = root.findViewById(R.id.pick_image_btn);
captureImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
captureImage();
}
});
// pickButton.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// pickImage();
// }
// });
detectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Navigation.findNavController(v).navigate(R.id.action_homeFragment_to_displayFragment2);
// DisplayFragment displayFragment = new DisplayFragment();
// FragmentManager fragmentManager = getFragmentManager();
// fragmentManager.beginTransaction()
// .replace(R.id.DisplayFragment, displayFragment, displayFragment.getTag())
// .commit();
//detectTextFromImage();
}
});
return root;
}
private void detectTextFromImage() {
capturedTextView.setText("");
FirebaseVisionImage firebaseVisionImage = FirebaseVisionImage.fromBitmap(imageBitmap);
FirebaseVisionTextDetector visionTextDetector = FirebaseVision.getInstance().getVisionTextDetector();
visionTextDetector.detectInImage(firebaseVisionImage).addOnSuccessListener(new OnSuccessListener<FirebaseVisionText>() {
#Override
public void onSuccess(FirebaseVisionText firebaseVisionText) {
List<FirebaseVisionText.Block> textBlocks = firebaseVisionText.getBlocks();
if (textBlocks.size() == 0) {
Toast.makeText(getContext(), "No Text Found", Toast.LENGTH_SHORT).show();
} else {
for (FirebaseVisionText.Block block : textBlocks) {
String text = block.getText();
ArrayList textBlobs = new ArrayList();
textBlobs.add(text);
for(int i = 0; i < textBlobs.size(); i++) {
capturedTextView.setText(capturedTextView.getText() + ", " + textBlobs.get(i));
}
// capturedTextView.setText(capturedTextView.getText() + " " + text);
}
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getContext(), "Something went wrong", Toast.LENGTH_SHORT).show();
Log.d("Error", e.getMessage());
}
});
}
private void pickImage() {
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
}
private void captureImage() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getActivity().getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
imageBitmap = (Bitmap) extras.get("data");
imageView.setImageBitmap(imageBitmap);
}
// else if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
// Uri imageUri = data.getData();
// imageBitmap = MediaStore.Images.Media.decodeBitmap(this.);
// imageView.setImageBitmap(imageBitmap);
// }
}
}
here is my DisplayFragment.java (the receiving fragment):
package com.mvsolutions.snap.ui.display;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;
import com.mvsolutions.snap.R;
public class DisplayFragment extends Fragment {
private DisplayViewModel DisplayViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
DisplayViewModel =
ViewModelProviders.of(this).get(DisplayViewModel.class);
View root = inflater.inflate(R.layout.fragment_display, container, false);
// final TextView textView = root.findViewById(R.id.text_gallery);
DisplayViewModel.getText().observe(this, new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
I am currently using a navigation fragment xml file to make the button switch from the first fragment to the second, but I want it to send the data to the second fragment as well.
My two questions are:
Is it possible to both send the data to the second fragment and switch to the second fragment with one button press? or do I have to split it into two?
How do I send the data from the first fragment to the second?
You are using ViewModel so I think the easiest way is to use the same ViewModel for both fragments. In android docs, You can find an example Share data between fragments
It's very common that two or more fragments in an activity need to communicate with each other. Imagine a common case of split-view (master-detail) fragments, where you have a fragment in which the user selects an item from a list and another fragment that displays the contents of the selected item.
public class SharedViewModel extends ViewModel {
private final MutableLiveData<Item> selected = new MutableLiveData<Item>();
public void select(Item item) {
selected.setValue(item);
}
public LiveData<Item> getSelected() {
return selected;
}
}
public class MasterFragment extends Fragment {
private SharedViewModel model;
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
itemSelector.setOnClickListener(item -> {
model.select(item);
});
}
}
public class DetailFragment extends Fragment {
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
SharedViewModel model = new ViewModelProvider(requireActivity()).get(SharedViewModel.class);
model.getSelected().observe(getViewLifecycleOwner(), { item ->
// Update the UI.
});
}
}
Notice that both fragments retrieve the activity that contains them. That way, when the fragments each get the ViewModelProvider, they receive the same SharedViewModel instance, which is scoped to this activity.
Just saying, im new at android proggaming, what i wanna do it's just store the email and pass if the user check the check "checarSessao" CheckBox, and stay logged, if he closes the app, when he opens again, i wanna show the Home automatically instead of login screen again...
Here is my Login
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
private Session session;
private CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText)findViewById(R.id.loginEmail);
loginSenha = (EditText)findViewById(R.id.loginSenha);
btLogar = (Button)findViewById(R.id.btLogar);
refCadastrar = (TextView)findViewById(R.id.refCadastrar);
checkBox = (CheckBox)findViewById(R.id.checarSessao);
refCadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
checkBox = (CheckBox) findViewById(R.id.checarSessao);
if (!new Session(this).Logado()) {
//user's email and password both are saved in preferences
startActivity(new Intent(Login.this, Home.class));
}
btLogar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if(email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.103/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
} else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
#Override
protected void onPostExecute(String resultado) {
if(resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
abreHome.putExtra("sobreusu", dados[2]);
abreHome.putExtra("emailusu", dados[3]);
abreHome.putExtra("senhausu", dados[4]);
String email = loginEmail.getText().toString();
String password = loginSenha.getText().toString();
if (checkBox.isChecked()) {
salvarLogin(email, password);
startActivity(abreHome);
finish();
}
overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_in);
startActivity(abreHome);
finish();
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
private void salvarLogin(String email, String password) {
new Session(this).salvarLogin(email, password);
}
}
Here is my Session
package complete.lyne.myapplication;
import android.content.Context;
import android.content.SharedPreferences;
/**
* Created by Higor on 10/08/2017.
*/
public class Session {
Context context;
Session(Context context) {
this.context = context;
}
public void salvarLogin(String email, String senha) {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Email", email);
editor.putString("Senha", senha);
editor.commit();
}
public String getEmail() {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
return sharedPreferences.getString("Email", "");
}
public boolean Logado() {
SharedPreferences sharedPreferences = context.getSharedPreferences("LoginDetails", Context.MODE_PRIVATE);
boolean isEmailEmpty = sharedPreferences.getString("Email", "").isEmpty();
boolean isPasswordEmpty = sharedPreferences.getString("Password", "").isEmpty();
return isEmailEmpty || isPasswordEmpty;
}
}
And my Home
package complete.lyne.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.annotation.NonNull;
import android.support.design.widget.NavigationView;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.Layout;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import static complete.lyne.myapplication.R.layout.header_navegacao;
public class Home extends AppCompatActivity {
// Fragmentos
FragmentTransaction fragmentTransaction;
NavigationView navigationView;
// Fim dos Fragmentos
TextView bdNome;
String uNome;
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle aToggle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
Home.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
drawerLayout = (DrawerLayout)findViewById(R.id.DrawerLayout);
aToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.abrir, R.string.fechar);
navigationView = (NavigationView)findViewById(R.id.navigation_view);
View header = navigationView.getHeaderView(0);
bdNome = (TextView) header.findViewById(R.id.bdNome);
uNome = getIntent().getExtras().getString("nomeusu");
bdNome.setText(uNome);
drawerLayout.addDrawerListener(aToggle);
aToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Fragmentos
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.add(R.id.main_container,new HomeFragment());
fragmentTransaction.commit();
getSupportActionBar().setTitle("Line");
navigationView = (NavigationView)findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.mConta:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new ContaFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Minha Conta");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mPerfil:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new PerfilFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Perfil");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mAmigos:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new AmigosFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Amigos");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mSobre:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new SobreFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
getSupportActionBar().setTitle("Sobre");
item.setChecked(true);
drawerLayout.closeDrawers();
break;
case R.id.mSair:
fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
fragmentTransaction.replace(R.id.main_container,new SobreFragment());
fragmentTransaction.addToBackStack("tag");
fragmentTransaction.commit();
item.setChecked(true);
drawerLayout.closeDrawers();
break;
}
return true;
}
});
// Fim Fragmentos
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(aToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
DrawerLayout layout = (DrawerLayout)findViewById(R.id.DrawerLayout);
Home.this.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
if (layout.isDrawerOpen(GravityCompat.START)) {
layout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
SOLUTION
Login
package complete.lyne.myapplication;
import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
public class Login extends AppCompatActivity {
EditText loginEmail, loginSenha;
Button btLogar;
TextView refCadastrar;
String url = "";
String parametro = "";
private CheckBox checkBox;
public static final String info_usuario = "info_usuario";
public static final String email = "email";
public static final String senha = "senha";
public static final String nomeusu = "nomeusu";
public static final boolean isLogin = Boolean.parseBoolean("islogin");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
loginEmail = (EditText) findViewById(R.id.loginEmail);
loginSenha = (EditText) findViewById(R.id.loginSenha);
btLogar = (Button) findViewById(R.id.btLogar);
refCadastrar = (TextView) findViewById(R.id.refCadastrar);
checkBox = (CheckBox) findViewById(R.id.checarSessao);
SharedPreferences sharedPref;
sharedPref = getSharedPreferences("info_usuario", Context.MODE_PRIVATE);
boolean login = sharedPref.getBoolean(String.valueOf(isLogin), false);
if(login){
Intent abreHome = new Intent(Login.this, Home.class);
startActivity(abreHome);
}
refCadastrar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent abreCadastro = new Intent(Login.this, Cadastro.class);
startActivity(abreCadastro);
}
});
btLogar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ConnectivityManager connectivityManager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
String email = loginEmail.getText().toString();
String senha = loginSenha.getText().toString();
if (email.isEmpty() && senha.matches(".*[a-z].*")) {
loginEmail.setError("Insira seu endereço de Email.");
} else if (email.matches(".*[a-z].*") && senha.isEmpty()) {
loginSenha.setError("Insira sua Senha.");
} else if (email.isEmpty() && senha.isEmpty()) {
Toast.makeText(getApplicationContext(), "Nenhum campo pode ficar vazio.", Toast.LENGTH_LONG).show();
} else {
// Casa
url = "http://192.168.1.103/lyne/logar.php";
// Badran
// url = "http://172.16.2.15/lyne/logar.php";
parametro = "email=" + email + "&senha=" + senha;
new SolicitaDados().execute(url);
}
} else {
Toast.makeText(getApplicationContext(), "Nenhuma conexão com a Internet foi encontrada.", Toast.LENGTH_LONG).show();
}
}
});
}
private class SolicitaDados extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
return Conexao.postDados(urls[0], parametro);
}
#Override
protected void onPostExecute(String resultado) {
if (resultado != null) {
if (resultado.contains("login_ok")) {
String[] dados = resultado.split(",");
Intent abreHome = new Intent(Login.this, Home.class);
abreHome.putExtra("idusu", dados[0]);
abreHome.putExtra("nomeusu", dados[1]);
abreHome.putExtra("sobreusu", dados[2]);
abreHome.putExtra("emailusu", dados[3]);
abreHome.putExtra("senhausu", dados[4]);
if (checkBox.isChecked()) {
SharedPreferences sharedPref = getSharedPreferences("info_usuario", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(email, loginEmail.getText().toString());
editor.putString(senha, loginSenha.getText().toString());
editor.putString(nomeusu, "Higor");
editor.putBoolean(String.valueOf(isLogin), true);
editor.commit();
editor.apply();
Toast.makeText(getApplicationContext(), "Esta marcado.", Toast.LENGTH_LONG).show();
startActivity(abreHome);
finish();
}
overridePendingTransition(android.R.anim.fade_out, android.R.anim.fade_in);
startActivity(abreHome);
finish();
} else {
Toast.makeText(getApplicationContext(), "Usuário ou senha incorretos.", Toast.LENGTH_LONG).show();
}
}
}
}
public class Global extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String recentSearches = sharedPreferences.getString("email", "");
if (recentSearches.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), Home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
}
Use below code;
For storing values;
SharedPreferences sp=getSharedPreferences("Login", Context.MODE_PRIVATE);
SharedPreferences.Editor Ed=sp.edit();
Ed.putString("id",login_id.getText().toString() );
Ed.putString("password",login_password.getText().toString() );
Ed.commit();
For getting values;
SharedPreferences sharedPreferences = getSharedPreferences("Login", MODE_PRIVATE);
String uName = sharedPreferences.getString("id", "");
String password = sharedPreferences.getString("password", "");
Following code is working for me. try this.
to store value in preferences
SharedPreferences preferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("email",Email);
editor.putString("password",Password);
editor.commit();
editor.apply();
to get value from preferences
SharedPreferences preferences = getSharedPreferences("MyPrefs", MODE_PRIVATE);
String email = preferences.getString("email", "");
String pass = preferences.getString("password", "");
If you want to check it, only for the first time per application start is better to make general class.
you can do that like this: (this class run once per application start)
public class Global extends Application {
#Override
public void onCreate() {
super.onCreate();
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String email = sharedPreferences.getString("email", "");
if(email.isEmpty()){
Intent intent = new Intent(getApplicationContext(), YOUR_ACTIVITY.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
And then you should register the class in Manifest:
<application
android:name=".Global"
android:label="#string/app_name">
<activity android:name="MyActivity"
</activity>
</application>
I want to use SharedPreferences to save the selected item that's chosen in the spinner
here is my coding
package com.mulder.jip.schoolroosterbeta2;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class CustumMaandag extends Activity {
Context Context = this;
private Spinner les1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custum_maandag);
{
les1 = (Spinner) findViewById(R.id.les1);
List<String> list = new ArrayList<String>();
list.add("Test1");
list.add("Test2");
list.add("Test3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item,list);
dataAdapter.setDropDownViewResource
(android.R.layout.simple_spinner_dropdown_item);
les1.setAdapter(dataAdapter);
les1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object obj = parent.getItemAtPosition(pos);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(Context);
SharedPreferences.Editor prefsEditor = prefs.edit();
prefsEditor.putString("object", obj.toString());
prefsEditor.commit();
}
public void onNothingSelected(AdapterView<?> parent) { }
});
}
}
}
What am I doing wrong?
Try using this inside onItemSelected(...){ *here }
String selectedText = les1.getSelectedItem().toString();
SharedPreferences.Editor editor = getSharedPreferences("your_prefs_name", MODE_PRIVATE).edit();
editor.putString("your_key", selectedText);
editor.commit();
try this.
String selecteditem = les1 .getSelectedItem().toString();
and save in shared pref like this
prefsEditor.putString("object", selecteditem );
I am trying to save a ArrayAdapter to shared preferences. I can get one string recovered using this code, but only one, I was not able to recover the entire ArrayAdapter.
package com.example.eduleito.listacompras;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText edt_item;
private Button btn_limpar;
private ImageButton btn_adcionar;
private ListView lst_item;
private ArrayAdapter adp_item;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_main);
edt_item = (EditText) findViewById(R.id.edt_item);
btn_limpar = (Button) findViewById(R.id.btn_limpar);
btn_adcionar = (ImageButton) findViewById(R.id.btn_adcionar);
lst_item = (ListView) findViewById(R.id.lst_item);
btn_adcionar.setOnClickListener(this);
btn_limpar.setOnClickListener(this);
adp_item = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
lst_item.setAdapter(adp_item);
loadSavedPreferences();
}
private void loadSavedPreferences(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String item = sharedPreferences.getString("storeditem", "");
adp_item.add(item);
}
private void savePreferences(String key, String value){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
#Override
public void onClick(View v) {
if (v == btn_adcionar) {
String item = edt_item.getText().toString();
adp_item.add(item);
savePreferences("storeditem", item);
edt_item.setText("");
} else if (v == btn_limpar) {
adp_item.clear();
}
}
}
Google:
Storage Options on developer.android.com
The SharedPreferences class provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types.