How to use Spinner to Save selection to shared preference - java

I have a spinner view called Spinner_Gender, I made array, array adapter and made onItemSelectedListener. I want to save the selected item position which is integer to shared preference, I tried using a string with Editor and putInt, it saved well. But when reloading the saved data to the spinner using .setSelection it gives an error because it wants an integer not string. Also while trying Integer in sharedpreference I can't save the selected item position to it because the putInt needs only a string to put int in.
Sorry for long question but I searched a lot and can't find answer. Two more questions please:
what is the integer name for spinner selectedItemPosition? How can I store it to sharedpreference?
Code:
final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View itemSelected,
final int selectedItemPosition, long selectedId)
{
int selectedPosition = spinner.getSelectedItemPosition();
Editor editor = mGameSettings.edit();
editor.putInt(myNum,selectedPosition);
editor.commit();
}
}

I don't quite understand what's your issue with SharedPreferences.
When you want to save the value you do something like this :
SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
Editor editTest = test.edit();
editTest.putInt("key", id_from_spinner);
editTest.commit();
When you want to get the value you do something like this :
SharedPreferences test = getSharedPreferences("TEST", MODE_MULTI_PROCESS);
int id = test.getInt("key", -1);
if(id != -1) {
//use it in your spinner
} else {
//abort because value was not set
}

To convert an int to a String you can use Integer.toString(theInteger) and to convert a String to an int you can use Integer.parseInt(theString).

You should do something like this
spinner.setSelection(dataAdapter.getPosition(genderstring));
Update :
final Spinner spinner = (Spinner) findViewById(R.id.Spinner_Gender);
spinner.setAdapter(adapter);
spinner.setSelection(mGameSettings.getInt("gender", 0));
spinner.setOnItemSelectedListener( new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View itemSelected,
final int selectedItemPosition, long selectedId)
{
Editor editor = mGameSettings.edit();
editor.putInt("gender", selectedItemPosition);
editor.commit();
}
}

Related

How to get a value from listview with multidimensional array?

So I have a multidimensional array for my listview, it constructed like this:
String[][] listControls = {
{"Shutdown Host","10"},
{"Close Connection","1"}};
Let say the first String is the text I want to display in the list view, and the other one is a id/message to send via socket (lets say it a secret value).
I coded the Adapter like this:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.layout_listview);
for(int i = 0; i < listControls.length; i++) {
adapter.add(listControls[i][0]);
}
listView = (ListView) findViewById(R.id.controls_listView);
listView.setAdapter(adapter);
listView.setClickable(true);
And I constructed the click listener of an item:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = listView.getItemAtPosition(position);
//What should I add here? to get specific value from the array?
//Integer cmdId = Integer.parseInt( ... );
}
});
From the click listener, i want to get the other value, e.g. If I clicked "Close Connection" in list view, I want to get the "1" value from it and put it into a variable.
Thanks in advance for the help.
Write custom adapter for your case. Use HashMap which is always better.
HashMap<String, Integer> map = new LinkedHashMap<>();
map.add("Shut Down Host", 0);
map.add("Close connection", 1);
And most importantly use RecyclerView.
Tutorial for RecyclerView https://developer.android.com/guide/topics/ui/layout/recyclerview
What you could do is
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String value = listControls[position][1]
}
This will, of course work only if you have access to listControls. If not, I'd opt for creating an object SomethingWithCode(String text, Int code)[or just Pair in kotlin] and creating a custom adapter.
Hope this helps!
Also, you probably don't need multidimensional array for it, if you're always passing just two values(refer to object with string and int parameters)

Save textView position after drag and Drop using com.jmedeisis.draglinearlayout.DragLinearLayout

So I was able to have my textViews drag and drop properly. But when I close the application and re-open it doesn't save the position of the new textViews. In a previous application I was able to save data using SharedPreferences but I couldn't quite get it to work in this scenario. Any insight or help would be appreciated!
Thanks,
DragLinearLayout dragDropAndroidLinearLayout = (DragLinearLayout) findViewById(R.id.drag_drop_layout);
for (int i = 0; i < dragDropAndroidLinearLayout.getChildCount(); i++) {
View child = dragDropAndroidLinearLayout.getChildAt(i);
dragDropAndroidLinearLayout.setViewDraggable(child, child);
}
The code I'm using to implement the drag and drop feature. I guess I'm not sure what part in this code would I use to put into the SharedPreferences if that's the way I would even do it.
Try using setTag and getTag
for(i=0;i<5;i++){
final View items= View.inflate(this, R.layout.yourItemStyle, null);
items.setTag(i);
final TextView text1= (TextView) note.findViewById(R.id.textView1);
text1.setId(i);
dragLinearLayout.addDragView(items, text1,i);
dragLinearLayout.setOnViewSwapListener(new DragLinearLayout.OnViewSwapListener() {
#Override
public void onSwap(View firstView, int firstPosition, View secondView, int secondPosition) {
int ID= Integer.parseInt(String.valueOf(firstView.getTag()))
String strID = String.valueOf(ID);
Log.v("ID",strID );
}
});
}

Android: Storing multiple EditText values to a ListView using SharedPreferences

Scenario:
I have four edittexts and three buttons, where, when the user provides some input in one of the edittexts and either clicks on button 1 or button 2, the provided input by the user should be saved in the activity associated with the button 3. In general, button 3 activity stores the "history" of provided inputs by the user.
Currently, I am using sharedpreferences approach which I know that it is not a good approach if you want to store multiple values. I have tried solving this problem using SQLite database and I was not successful with it.
Here is my method called "saveHistory" which is defined in the button 1's and button 2' onclick methods.
private void saveHistory()
{
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
fd=sharedPreferences.edit();
String et1 = et1.getText().toString();
String et2 = et2.getText().toString();
String et3 = et3.getText().toString();
String et4 = et4.getText().toString();
fd.putString("et1" , et1);
fd.putString("et2" , et2);
fd.putString("et3" , et3);
fd.putString("et4" , et4);
fd.apply();
}
And here is my another class (when clicking on button 3 this class gets called) which retrieves the edittexts values.
public class history extends Activity
{
public static final String DEFAULT = "No data";
ListView listView;
SharedPreferences sharedPreferences;
SharedPreferences.Editor sp;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
listView = (ListView) findViewById(R.id.listViewMain);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sp = sharedPreferences.edit();
String et1 = sharedPreferences.getString("et1", DEFAULT);
String et2 = sharedPreferences.getString("et2", DEFAULT);
String et3 = sharedPreferences.getString("et3", DEFAULT);
String et4 = sharedPreferences.getString("et4", DEFAULT);
if (et1.equals(DEFAULT) || et2.equals(DEFAULT) || et3.equals(DEFAULT) || et4.equals(DEFAULT))
{
Toast.makeText(this, "No history found", Toast.LENGTH_LONG).show();
}
else
{
String [] values = new String[]{et1,et2,et3,et4};
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, values);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
sp.apply();
}
}
}
The problem I am facing is that I am only seeing one listview with only 1 value being displayed which is obvious as there is no code which does incrementation. When I enter a new value the old value gets overridden. As there are two buttons associated with saveHistory method I am only able to get one value as there is only one listview. So my needs are that I want to store more than one value using sharedpreferences and also clicking on both buttons should save the values and not override each other's value. I know that I am asking too much, but if you can help me find out how to correctly do incrementation with this scenario and with this code, then I would be grateful.
I have gone through many stackoverflow questions and most of them are associated with having one edittext and one button and storing and retrieving those value. However, My application requirements are different, and, as a result, I have posted this question.
You are retrieving the EditTexts values but you are putting something else in your sharedPreferences.
Replace your saveHistory() code with this:
private void saveHistory(){
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
fd = sharedPreferences.edit();
String bt = et1.getText().toString();
String an = et2.getText().toString();
String cn = et3.getText().toString();
String in = et4.getText().toString();
fd.putString("et1" , bt); //These lines were the problem
fd.putString("et2" , an); //These lines were the problem
fd.putString("et3" , cn); //These lines were the problem
fd.putString("et4" , in); //These lines were the problem
fd.apply();
}
Edit: I'm sorry I think that I understand your question now.
You can store multiple String values with a single SharedPreferences key with PutStringSet(). You need to make the validation of what button is calling the saveHistory() and then create a Set with this info.
Check the link below for an example.
https://stackoverflow.com/a/9054240/2503185
In your case, you would put something like (for each EditText value):
Set<String> faveSet = faves.getStringSet("et1");
faveSet.add(button + ":" + et1_value);
SharedPreferences.Editor editor = faves.edit();
editor.putStringSet("et1", faveSet);
editor.commit();
And then retrieve that and validate each EditText.

How to display seekBar value and selected spinner item from Activity A to Activity B?

I have a listView in Activity A , which the value are returned from Activity B.When the list is clicked, it will intent to Activity B for edit.
Activity B
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.add_details_information);
addItemsOnSpinner();
if(getIntent().getExtras()!=null) // if has value pass from A
{
final String Project1=getIntent().getStringExtra("ReceiveProject");
final String Description1=getIntent().getStringExtra("ReceiveDescription");
final String Progress1=getIntent().getStringExtra("ReceiveProgress");
final String TimeIn1=getIntent().getStringExtra("ReceiveTimeIn");
final String TimeOut1=getIntent().getStringExtra("ReceiveTimeOut");
//project.setText(Project1);
description.setText(Description1);
//progressText.setText("Covered:")
timeIn.setText(TimeIn1);
timeOut.setText(TimeOut1);
}
save.setOnClickListener(new View.OnClickListener()
{ // return to A
#Override
public void onClick(View v)
{
Intent returnIntent=new Intent();
Project=project.getSelectedItem().toString(); // Spinner Value
Description=description.getText().toString(); //from editText
progress=seekBar.getProgress(); // From SeekBar
returnIntent.putExtra("Project",Project);
returnIntent.putExtra("Description", Description);
returnIntent.putExtra("progress", progress);
Toast.makeText(getApplicationContext(), progress+"", Toast.LENGTH_LONG).show();
returnIntent.putExtra("TimeIn", TimeIn);
returnIntent.putExtra("TimeOut",TimeOut);
setResult(Activity.RESULT_OK,returnIntent);
finish();
}
});
public void addItemsOnSpinner()
{
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add("TRN-XXX-XXX");
list.add("Pro-XXX-XXX);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
}
Activity A
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { // if listView is clicked
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
mClickedPosition = position;
Intent i = new Intent(getApplication(), Add_Details_Information.class);
i.putExtra("ReceiveProject", ReceiveProject);
i.putExtra("ReceiveDescription", ReceiveDescription);
i.putExtra("ReceiveProgress", ReceiveProgress);
i.putExtra("ReceiveTimeIn", ReceiveTimeIn);
i.putExtra("ReceiveTimeOut", ReceiveTimeOut);
startActivityForResult(i,PROJECT_REQUEST_CODE);
}
});
}
I know that we can use setText to display the passed value from A to B for editText, but how about the spinner and seekBar value ?
This is the listView in Activity A. Value are returned from Activity B.
When listView is clicked, it will goes to B again to edit.
So how can I make the spinner in B display Pro-XXX-XXX and the seekBar goes to 48 ? Any idea or suggestion ? Thanks a lot
Edited
After used the answer from #Clairvoyant, now I get this (for spinner value).
Activity A
There are 4 list in Activity A.
Assume first list is clicked.
Everything works fine just the spinner(Project/Service/Training) display wrong value. It display the spinner value from last list(PRO-SKM-D5) instead of itself(Pro-XXX-XXX)
First Step: Make your addItemsOnSpinner like as below:
public void addItemsOnSpinner(String value)
{
int position = 0;
project=(Spinner)findViewById(R.id.SpinnerProject);
List<String> list = new ArrayList<String>();
list.add(position,"TRN-XXX-XXX");
list.add("Pro-XXX-XXX");
for(int i=0; i<list.size() ; i++){
if(list.get(i).equalsIgnoreCase(value)){
position = i;
break;
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String> (getApplicationContext(),R.layout.spinner_item, list);
//adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
project.setAdapter(adapter);
project.setSelection(position);
}
Second Step: call the above method when you are assigning value to the variable you have to show in spinner here for eg: project1 is the string value which you want to show in spinner then call the method as follows:
final String Project1=getIntent().getStringExtra("ReceiveProject");
addItemsOnSpinner(Project1);
Use SharedPreferences. Next time, googling helps.
Get SharedPreferences
SharedPreferences prefs = getDefaultSharedPreferences(context);
Read preferences:
String key = "test1_string_pref";
String default = "returned_if_not_defined";
String test1 = prefs.getString(key, default);
To edit and save preferences
SharedPreferences.Edtior editor = prefs.edit(); //Get SharedPref Editor
editor.putString(key, "My String");
editor.commit();
Shorter way to write
prefs.edit().putString(key, "Value").commit();
Additional info for SharedPreferences: JavaDoc and Android Developers Article

want a simple code for the getting the state name and city name depend on the selection

I am new to both android and java. I am developing a simple app which contain country , state and city which are selected by spinner. Now consider while am selecting the country(India) then i need to get only states of india. And then while selecting any state(Andhra pradesh) then the cities of A.P should be shown in the next spinner. Can any one suggest me with some sample code.
thanks in advance
you can add this logic(for two spinners) to your code:
public void onCreate() {
....
Country[] mCountries = ... ;
final Spinner spinner1 = ...;
final Spinner spinner2 = ...;
spinner1.setAdapter(new ArrayAdapter(mCountries);
spinner1.setOnItemSelectedListener( new OnItemSelectedListener() {
void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Country country = (Country) parent.getAdapter().getItem(position);
spinner2.setAdapter(new ArrayAdapter(country.getStates());
}
void onNothingSelected(AdapterView<?> parent) {
spinner2.setAdapter(null);
}
});
....
}

Categories