I want to store a variable in my project. In fact, I want the user to choose an option via a drop down list, and store the value of this variable to be able to still use it in my other activities
My spinner code :
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
You can use the SharedPreferences to store information for future use in your App.
http://developer.android.com/reference/android/content/SharedPreferences.html
http://developer.android.com/reference/android/content/SharedPreferences.Editor.html
There are of course several other ways to solve it but this one is pretty straight forward.
More information about storage can be found here: http://developer.android.com/guide/topics/data/data-storage.html#pref
You can make this in two ways:
First method allows you to keep the data only while the application is running, the other method will keep the data even if the application is closed.
Create a class GlobalData
public enum GlobalData {
Data;
private boolean isBooleanVal= false;
public boolean isBooleanVal() {
return isBooleanVal;
}
public void setBooleanVal(boolean isQuizStartedAgain) {
this.isQuizStartedAgain = isBooleanVal;
}
}
And call it in other class:
GlobalData.Data.setBooleanVal(true);
OR
GlobalData.Data.isBooleanVal();
Using SharedPreferences
private SharedPreferences sharedpreferences;
private SharedPreferences.Editor editor;
sharedpreferences = getActivity().getSharedPreferences(ApplicationConstants.SHARED_PREFERENCES, Context.MODE_PRIVATE);
editor = sharedpreferences.edit();
editor.putBoolean(value,value);
editor.commit();
Example
Related
I implemented a spinner in my Unterkunft Activity which is populated by data from sqlite database.
In this activity I have a few edit texts and this spinner. I want the inserted values and the chosen value from the spinner to be saved in a database. There is no problem with the edit texts values. But how can I save the spinner value in the database?
I added the Unterkunft acitvity
public class activity_unterkunft extends AppCompatActivity {
DatabaseHelper myDb;
Button btn_save;
Spinner ChooseProject;
EditText Entfernung,Price,MWST;
private BottomNavigationView bottomNavigationView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_unterkunft);
myDb = new DatabaseHelper(this);
ChooseProject = (Spinner) findViewById(R.id.ChooseProject);
Entfernung = (EditText) findViewById(R.id.Entfernung);
Price = (EditText) findViewById(R.id.Preis);
MWST = (EditText) findViewById(R.id.MwSt);
btn_save=(Button) findViewById(R.id.btn_save);
loadSpinnerData();
SaveData();
//++++++++++++BOTTOM NAVIGATION BAR++++++++++++//
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(new BottomNavigationView.OnNavigationItemSelectedListener(){
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item){
if (item.getItemId()==R.id.menu_start){
startActivity(new Intent(activity_unterkunft.this, MainActivity.class));
} else if(item.getItemId()==R.id.menu_allgemein){
startActivity(new Intent(activity_unterkunft.this, activity_allgemein.class));
} else if(item.getItemId()==R.id.menu_transport){
startActivity(new Intent(activity_unterkunft.this, activity_transport.class));
} else if(item.getItemId()==R.id.menu_rechnung){
startActivity(new Intent(activity_unterkunft.this, activity_rechnung.class));
} else if(item.getItemId()==R.id.menu_unterkunft){
startActivity(new Intent(activity_unterkunft.this, activity_unterkunft.class));
}
return true;
}
});
bottomNavigationView.setSelectedItemId(R.id.menu_unterkunft);
}
/**
* Function to load the spinner data from SQLite database
* */
private void loadSpinnerData() {
// database handler
DatabaseHelper db = new DatabaseHelper (getApplicationContext());
// Spinner Drop down elements
List<String> projects = db.getAllProjects();
// Creating adapter for spinner
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, projects);
// Drop down layout style - list view with radio button
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
ChooseProject.setPrompt("Projekt auswählen");
// attaching data adapter to spinner
ChooseProject.setAdapter(dataAdapter);
}
//++++++++++++Save Data++++++//
public void SaveData(){
btn_save.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
boolean isInserted = myDb.createUnterkunft(
Integer.valueOf(Price.getText().toString()),
Integer.valueOf(MWST.getText().toString()),
Integer.valueOf(Entfernung.getText().toString())
);
if(isInserted=true)
Toast.makeText(activity_unterkunft.this, "Daten gespeichert", Toast.LENGTH_LONG).show();
else
Toast.makeText(activity_unterkunft.this, "Daten nicht gespeichert", Toast.LENGTH_LONG).show();
}
}
);
}
}
Use setOnItemSelectedListener to get the spinner value
String item;
ChooseProject.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
item =String.ValueOf(parent.getItemAtPosition(pos));
}
public void onNothingSelected(AdapterView<?> parent) {
}
});
Then you can save the item to databases.
I am new to android , I have an activity with 3 multiple spinners as bellow
Spinner 1:department
Spinner2:semester
Spinner3:subjects
and one button
spinner1 shows the department on select of department it has to display the semester on select of semester it has to display the subject spinner
NOTE:-SUBJECT SPINNER DEPENDS ON THE SELECTION OF SEMESTER SPINNER AS WELL AS DEPARTMENT SPINNER.
something like country, state, city spinners but suggest me some other ideas to do it because i am using string resources to list the items of spinners
Please help me
Try something like this in your activity.
Firstly, make your activity implement AdapterView.OnItemSelectedListener & View.OnClickListener.
private Spinner mDepartmentSpinner;
private Spinner mSemesterSpinner;
private Spinner mSubjectSpinner;
private Button mButton;
// Values to fill first spinner with.
private String[] mDepartments = {
"Department 1",
"Department 2",
"Department 3",
"Department 4",
};
private String[] mSemesters;
private String[] mSubjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// Find the spinners and button, declared in the activity's resource file
mDepartmentSpinner = (Spinner) findViewById(R.id.department_spinner);
mSemesterSpinner = (Spinner) findViewById(R.id.semester_spinner);
mSubjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
mButton = (Button) findViewById(R.id.button);
// Initialise spinner with values, placing them into a textview
mDepartmentSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mDepartments));
// Attach a listener for item selection
departmentSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Work out which spinner was selected
switch (view.getId()) {
case R.id.department_spinner:
// Get the selected item
String selectedDepartment = mDepartments[position];
// Get values to fill the semester spinner with, based on initial selection.
mSemesters = getSemestersFor(selectedDepartment);
// Initialise spinner with values, placing them into a textview
mSemesterSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mSemesters));
// Attach a listener for item selection
mSemesterSpinner.setOnItemSelectedListener(this);
break;
case R.id.semester_spinner:
// Get the selected item
String selectedSemester = mSemesters[position];
// Get values to fill the subject spinner with, based on second spinner selection.
mSubjects = getSubjectsFor(selectedSemester);
// Initialise spinner with values, placing them into a textview
mSubjectSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, subjects));
// Attach a listener for item selection
mSubjectSpinner.setOnItemSelectedListener(this);
break;
case R.id.subject_spinner:
mButton.setOnClickListener(this);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please select an option from each spinner.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
// Go to your new activity, passing the selected subject
Intent intent = new Intent(this, SubjectActivity.class);
intent.putExtra("KEY_SUBJECT", (String) mSubjectSpinner.getSelectedItem());
startActivity(intent);
}
You can get the selected subject in the SubjectActivity like so...
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().getExtras().containsKey("KEY_SUBJECT") {
String subject = getIntent().getExtras().getString("KEY_SUBJECT");
}
}
Code for R.layout.text_view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
You will need to implement the following methods yourself, I don't know your logic!
private String[] getSemestersFor(String department) {
// your code here
}
private String[] getSubjectsFor(String semester) {
// your code here
}
i want to add listview item dynamically. i had done this but when i restart the app listview item disappear. How can i save this item permanently to listview. please suggest
public class ChatWithAttorney extends Activity {
ImageView btnBack;
ListView chatList;
EditText etMsg;
Button btnSend;
String msg_to_send;
ArrayAdapter<String> adapter;
ArrayList<String> listMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwithattorny);
btnBack = (ImageView) findViewById(R.id.btnback);
chatList = (ListView) findViewById(R.id.chatList);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSend = (Button) findViewById(R.id.btnSend);
listMsg = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.chat_list_text, R.id.tvSentMsg,listMsg);
chatList.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
msg_to_send = URLEncoder.encode(etMsg.getText().toString(),
"utf-8");
listMsg.add(msg_to_send);
adapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
Put those ArrayList items in a database or SharedPreference and read those items when resuming your activity.
You can use Local database , SharedPreference or Static arraylist for storing the messages
AT the Time of Destroy Serialize the List data.
And Deserilize when Application Starts Again.
i've searched for a solution on google ,and on stack overflow.Yes i also know this could be a duplicate of another question asked in stack overflow but i tried the code snippets offered but none of them worked.Like: Taking user selection in a spinner, storing it in sharedPrefences, and using it in another activity and not getting integer value from SharedPreference and http://www.acnenomor.com/4379973p1/how-to-save-spinner-selecteditem-to-sharedpreferences
Here is my problem.I have the first activity,with two spinners from this tutorial http://www.mkyong.com/android/android-spinner-drop-down-list-example/ .On pressing the submit button,id like to save the selected values on SharesPreferences.On going to the second activity,i retrieve the selected values and display them on a text view.So that on the next app launch i go to the second activity to find the displayed saved values.I've been really stranded on this.Please point me in the right direction.Any help will be very much appreciated.
main activity
public class MyAndroidAppActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
// add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, list);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner1.setOnItemSelectedListener(new CustomOnItemSelectedListener());
}
// get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MyAndroidAppActivity.this,
"OnClickListener : " +
"\nSpinner 1 : "+ String.valueOf(spinner1.getSelectedItem()) +
"\nSpinner 2 : "+ String.valueOf(spinner2.getSelectedItem()),
Toast.LENGTH_SHORT).show();
}
});
}
}
CustomOnItemSelectedListener.java
public class CustomOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
I was finally able to do it. I used this tutorial (http://androidopentutorials.com/android-sharedpreferences-tutorial-and-example/)
I modified this code to fit what I wanted
public void onClick(View v) {
text = String.valueOf(spinner1.getSelectedItem()) + String.valueOf(spinner2.getSelectedItem());
sharedPreference.save(context, text);
I've create one spinner and I want to save all of spinner input when i close my application. How can I do? I think shared preferences can help me but i don't know how can use it!
This is my code:
private Spinner spinner;
private EditText Text;
private ArrayAdapter<String> adapter;
private Button addButton;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Text = (EditText) findViewById(R.id.et);
final List<String> planets = new ArrayList<String>(Arrays.asList(getResources().getStringArray(R.array.clienti_arrays)));
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, planets);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
addButton = (Button) findViewById(R.id.add_new);
addButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
addNewSpinnerItem();
Collections.sort(planets);
}
});
}
protected void addNewSpinnerItem()
{
String textHolder = "" + Text.getText().toString();
adapter.add(textHolder);
}
public int compare(String s1, String s2) { return s1.toLowerCase().compareTo(s2.toLowerCase());
}
}
Thanks a lot for your help..
Override onPause() of Activity to save selected values in Shared Preferences when your application going to close as:
#Override
public void onPause()
{
// get Spinner Slected text here
String selectedtext = spinner.getSelectedItem().toString();
//Create SharedPreferences to store selected value
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
SharedPreferences.Editor prefsEditor = spinnerPrefs.edit();
prefsEditor.putString("spinner_selectedtext", selectedtext);
prefsEditor.commit();
super.onPause();
}
and to retrieve values saved in SharedPreferences :
SharedPreferences spinnerPrefs = this.getSharedPreferences("spinnerPrefs",
MODE_WORLD_READABLE);
String selectedtext = spinnerPrefs.getString("spinner_selectedtext",
"nothing_selected");
I detail how to do this in this post. Each time you enter an item in the edittext, it saves it to the spinner which holds the x last items you enter. The memory stays until you uninstall the app or manually clear the data.