I am trying to save a arrayadapter to sharedpreferences - java

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.

Related

Username and password store in shared preference

This is the register fiile:
The error is when I stored data and after that, I log in when I click on the login button app got crushed.
this is the register section;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
EditText textview1;
EditText textview2;
Button button1;
Button buttonlog;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textview1 = (EditText)findViewById(R.id.ediuser);
textview2 = (EditText)findViewById(R.id.edipassword);
button1 = (Button)findViewById(R.id.btnreg);
buttonlog = (Button)findViewById(R.id.onlogin);
}
public void onreg(View view){
String username = textview1.getText().toString();
String Password = textview2.getText().toString();
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
SharedPreferences.Editor editor1 = sharedPreferences.edit();
editor1.putString("username",username);
editor1.putString("password",Password);
editor1.apply();
Toast.makeText(this, "Register Successfully", Toast.LENGTH_SHORT).show();
}
public void onlog(View view){
Intent intent = new Intent(this,login.class);
startActivity(intent);
}
}
this is the login file:
package com.example.newshrd;
import androidx.appcompat.app.AppCompatActivity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class login extends AppCompatActivity {
EditText editText1;
EditText editText2;
Button button2;
SharedPreferences sharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
editText1 = (EditText) findViewById(R.id.userlog);
editText2 = (EditText) findViewById(R.id.passwordlog);
button2 = (Button) findViewById(R.id.btnlog);
sharedPreferences = getSharedPreferences("Dell", MODE_PRIVATE);
}
//this is the login section find error and let me know please
public void onloghere(View view){
String userlog = editText1.getText().toString();
String passlog = editText2.getText().toString();
String userlogin= sharedPreferences.getString("username",null);
String userpaswwords=sharedPreferences.getString("passowrd",null);
if (userlog.contains(userlogin) && passlog.contains(userpaswwords)){
Toast.makeText(this, "Your are in", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You are not", Toast.LENGTH_SHORT).show();
}
}
}
please, someone, find the error and let me know what I am missing in this code.
It is properly formatted (at least by the preview it is), so how can I fix this? I'm new to Stack Overflow formatting.
When you save, key is "password":
editor1.putString("password",Password);
But when get, you have a typo for the key here "passowrd":
String userpaswwords=sharedPreferences.getString("passowrd",null);
The userpaswwords you get is null (you set SharedPreferences.getString(String key, #Nullable String defValue) defValue value to be null), and here crashes:
passlog.contains(userpaswwords)
Cuz String.contains(CharSequence s) needs the argument to be non-null.

Cannot delete Shared Preference that is set in another Activity Android

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();

How to load, save, and show array to list?

I have XML layout like this:
[....textedit....][addbutton]
=======list1=========
=======list2=========
=======list3=========
=======list4=========
What to do if I want to Load and Show the list onCreate from SharePreferences, be able to Add "item" to the list, and save it to SharedPreferences? Any extra simple beginner explanation are welcome since I'm a total newb.
My code below is a big mess, and I got it 100% from stitching from one example to another example that I got from anywhere.
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.widget.EditText;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ListAdapter;
import android.widget.ArrayAdapter;
import android.widget.AdapterView;
import android.widget.Toast;
import android.view.View;
import android.content.SharedPreferences;
import android.content.Context;
public class MainActivity extends Activity {
String FileName = "myFile";
Button BtnSave;
EditText editName;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BtnSave = findViewById(R.id.btn1);
BtnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
saveFile();
}
});
lv = (ListView) findViewById(R.id.list1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,empty);
lv.setAdapter(adapter);
//Setting onClickListener on ListView
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Item Clicked: "+i,Toast.LENGTH_SHORT).show();
}
});
editName = findViewById(R.id.edit1);
}
private void saveFile() {
String strName = editName.getText().toString();
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("name", strName);
editor.commit();
Toast.makeText(this,"Data Saved Successfully",Toast.LENGTH_SHORT).show();
}
}
I think this should help you.
fun addProduct(productsItem: Product) {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
var gson=Gson()
var cartProduct=getAllProducts()
cartProduct.add(productsItem)
var json=gson.toJson(cartProduct)
println(json)
sharedPreferences.edit().putString("cart_products",json).apply()
}
fun getAllProducts(): ArrayList<Product?> {
sharedPreferences=context.getSharedPreferences(TAG,Context.MODE_PRIVATE)
val listType =
object : TypeToken<List<Product?>?>() {}.type
var productsItemList:ArrayList<Product?> = ArrayList();
val json=sharedPreferences.getString("cart_products",null)
if (json !=null){
var gson=Gson()
productsItemList=gson.fromJson(json,listType)
}
return productsItemList
}
Okay, so you need to:
1)input some word in EditText
2) show it in ListView
3) save it to preferences
right?
I think you must do next steps:
Create private ArrayList<String> list = new ArrayList();
When you input something in EditText and clicked on button, call list.add(editName.getText.toString()); and then call saveFile and save list.toString();
When you need to load file, create function
private void loadFile() {
SharedPreferences sharedPref = getSharedPreferences(FileName,Context.MODE_PRIVATE);
String string = sharedPref.getString("name", "");
ArrayList<String> newList = new ArrayList<String>(Arrays.asList(string.split(", ")));
}
Load in adapter your newList.

Clicked list item into a String and transported to another activity

I have made this app where in one particular activity i have a all the items listed in a list view. when you click the list item it goes to another activity where similar thing is happening. after that i was the clicked list items to be converted into a strings and transported into a 3rd activity where i can display those.
when i try to display them this shows in the text view where the clicked text item should have appeared:
this is code for the first activity:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.internal.Objects;
import com.google.firebase.database.ChildEventListener;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
public class TicketCategory extends AppCompatActivity {
public static String Category;
public String getCategory() {
return Category;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ticket_category);
populateTicketCategoryList();
final ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Category = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(TicketCategory.this, Subcategory.class);
startActivity(intent);
}
}
});
}
private void populateTicketCategoryList()
{
ArrayList<CompTicketCategory> arrayOfTicket = CompTicketCategory.getTicket();
CompTicketCategoryAdapter adapter = new CompTicketCategoryAdapter(this, arrayOfTicket);
ListView listView = (ListView) findViewById(R.id.lvTicketCategory);
listView.setAdapter(adapter);
}
}
the code for the second activity is:
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class Subcategory extends AppCompatActivity {
public String Category;
public static String Subcat;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_subcategory);
populateSubcategoryList();
final ListView listView = (ListView) findViewById(R.id.lvSubcategory);
ArrayAdapter arrayAdapter = new ArrayAdapter<String>(Subcategory.this, android.R.layout.simple_list_item_1,arrayList);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Subcat = listView.getItemAtPosition(i).toString();
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
startActivity(intent);
}
});
and this is the code for the activity where both of the clicked items should be displayed:
public class SubmitTicket extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_submit_ticket);
Spinner spinner = (Spinner) findViewById(R.id.spinner_priority);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.priority_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
final Button butt = findViewById(R.id.submit);
butt.setOnClickListener(new View.OnClickListener()
{
public void onClick (View view){
Toast.makeText(getApplicationContext(), "The ticket has been submitted", Toast.LENGTH_SHORT).show();
}
});
TextView textView = (TextView)findViewById(R.id.Category_submit_report);
textView.setText(TicketCategory.Category);
TextView tv = (TextView)findViewById(R.id.Subcategory_submit_report);
tv.setText(Subcategory.Subcat);
}
Please help me. i would appreciate any output. thanks!
UPDATE:
after trying
CompTicketCategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory();
this error is shown;
screenshot
You can use Intent Extra Feature.
In the First Activity,
Intent intent = new Intent(Subcategory.this, SubmitTicket.class);
switch1.putExtra("deviceID", listView.getItemAtPosition(i).toString(););
startActivity(intent);
Then Next activity recall them,
Intent intent = getIntent();
String data = intent.getStringExtra("data");
Try this in your TicketCategory actvity
Use this:
CompSubcategory model = listView.getItemAtPosition(i);
Category=model.Category; // your Category variable
Category=model.getCategory(); // or use getter setter method
Instead of this:
Category = listView.getItemAtPosition(i).toString();

How can I use SharedPreferences with a spinner

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 );

Categories