When using my app the users inputs data and the data is supposed to be saved. However at the moment the back button erases the data from the EditText. Here is my java file for the activity, this activity is activated by a button press from the Main Activity. I've already tried to override the back button with no success. Any suggestions?
public class NewLocation extends ActionBarActivity {
public String coName;
public String coAddress;
public String coContact;
public String sqFt;
public String taxed;
public String concerns;
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
public static final String DEFAULT = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewLocation.this, RoomList.class));
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
coName = editCoName.getText().toString();
coAddress = editCoAddress.getText().toString();
coContact = editCoContact.getText().toString();
sqFt = editSqFt.getText().toString();
taxed = editTaxed.getText().toString();
concerns = editConcerns.getText().toString();
LoadPreferences();
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("coName", coName);
outState.putString("coAddress", coAddress);
outState.putString("coContact", coContact);
outState.putString("sqFt", sqFt);
outState.putString("taxed", taxed);
outState.putString("concerns", concerns);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
coName = savedInstanceState.get("coName").toString();
coAddress = savedInstanceState.get("coAddress").toString();
coContact = savedInstanceState.get("coContact").toString();
sqFt = savedInstanceState.get("sqFt").toString();
taxed = savedInstanceState.get("taxed").toString();
concerns = savedInstanceState.get("concerns").toString();
}
private void SavePreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("coName", coName);
editor.putString("coAddress", coAddress);
editor.putString("coContact", coContact);
editor.putString("sqFt", sqFt);
editor.putString("taxed", taxed);
editor.putString("concerns", concerns);
editor.apply();
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
coName = sharedPreferences.getString("coName", DEFAULT);
coAddress = sharedPreferences.getString("coAddress", DEFAULT);
coContact = sharedPreferences.getString("coContact", DEFAULT);
sqFt = sharedPreferences.getString("sqFt", DEFAULT);
taxed = sharedPreferences.getString("taxed", DEFAULT);
concerns = sharedPreferences.getString("concerns", DEFAULT);
editCoName.setText(coName);
editCoAddress.setText(coAddress);
editCoContact.setText(coContact);
editSqFt.setText(sqFt);
editTaxed.setText(taxed);
editConcerns.setText(concerns);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
switch(item.getItemId())
{
case R.id.home:
SavePreferences();
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
}
You should save/restore the persistent state of the activity in onSaveInstanceState/onRestoreInstanceState methods. You already override those, so just call SavePreferences/LoadPreferences from them.
Overriding the back button is not a good idea and saving state in onDestroy is also not recommended. Either onSaveInstanceState or onPause is intended for that.
If the data needs to be saved whenever the user leaves that activity, you could approach the problem with a TextWatcher. Override the onTextChanged() method of the TextWatcher with something like this:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length > 0) coName = s;
}
And then override onPause() to save the state of your variables if necessary.
[Edited] You can try:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
SavePreferences();
finish(); //<-- You need finish your activity after saved
return true;
}
return super.onKeyDown(keyCode, event);
}
Related
I'm creating a app that is for notes. I'm trying to figure out how to create a function that will delete the Note by having an option in a menu inside of the edit portion of the app that you can press and then it will delete the note. Can someone please point me in the right direction to doing something like this? I have included my code below for both my main activity Java file and my editor activity file
Main
public class MainActivity extends AppCompatActivity {
static ArrayList<String> notes = new ArrayList<>();
static ArrayAdapter arrayAdapter;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.add_note_menu, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.add_note) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
startActivity(intent);
return true;
}
return false;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = findViewById(R.id.listView);
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = (HashSet<String>) sharedPreferences.getStringSet("notes", null);
if (set == null) {
notes.add("Welcome To Notes!!!!!");
} else {
notes = new ArrayList(set);
}
// Using custom listView Provided by Android Studio
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_expandable_list_item_1, notes);
listView.setAdapter(arrayAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// Going from MainActivity to NotesEditorActivity
Intent intent = new Intent(getApplicationContext(), NoteEditorActivity.class);
intent.putExtra("noteId", i);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
final int itemToDelete = i;
// To delete the data from the App
new AlertDialog.Builder(MainActivity.this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete this note?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
notes.remove(itemToDelete);
arrayAdapter.notifyDataSetChanged();
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
}).setNegativeButton("No", null).show();
return true;
}
});
}
}
Editer
public class NoteEditorActivity extends AppCompatActivity {
int noteId;
static ArrayList<String> notes = new ArrayList<>();
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
if (item.getItemId() == R.id.add_note) {
}
int id = item.getItemId();
if(id == android.R.id.home){
Intent i= new Intent(this, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//To have the back button!!
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_note_editor);
EditText editText = findViewById(R.id.editText);
Intent intent = getIntent();
noteId = intent.getIntExtra("noteId", -1);
if (noteId != -1) {
editText.setText(MainActivity.notes.get(noteId));
} else {
MainActivity.notes.add("");
noteId = MainActivity.notes.size() - 1;
MainActivity.arrayAdapter.notifyDataSetChanged();
}
editText.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
// add your code here
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
MainActivity.notes.set(noteId, String.valueOf(charSequence));
MainActivity.arrayAdapter.notifyDataSetChanged();
// Creating Object of SharedPreferences to store data in the phone
SharedPreferences sharedPreferences = getApplicationContext().getSharedPreferences("com.example.notes", Context.MODE_PRIVATE);
HashSet<String> set = new HashSet(MainActivity.notes);
sharedPreferences.edit().putStringSet("notes", set).apply();
}
#Override
public void afterTextChanged(Editable editable) {
// add your code here
}
});
}
}
I am writing an app for a restaurant and would like to be able to select a specific dish that you would like to order and that it has been added to OrderActivity where, in the form of ListView, you will be displaying individual dishes selected by the user.
I do not know how to do it in the best way, do you need to use the interface and maybe just get the intention of a specific dish?
And how do I save a specific request in OrderActivity so that when I return to an earlier Activity I do not lose the saved data in the ListView?
I managed to solve the problem of transmitting data from one Activity to the second Activity and showing it on the ListView, I do not know how to save that data, say on the example of SharedPreferences?
If I click the back button in my second Activity, my list becomes empty.
I understand that the fault is on onResume() because I am killing the second Activity, when I come back to the first, is that so?
How to solve the problem?
FirstActivity:
public class DinnerDetailActivity extends AppCompatActivity {
public static final String EXTRA_DINNER = "dinner";
private final int requestCode = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_obiady_domowe_detail);
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
TextView textView = (TextView) findViewById(R.id.dinner_text);
textView.setText(dinnerName);
int dinnerImage = Dinner.dinn[dinner].getImageResourceId();
ImageView imageView = (ImageView) findViewById(R.id.dinner_image);
imageView.setImageDrawable(getResources().getDrawable(dinnerImage));
imageView.setContentDescription(dinnerName);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar_obiady_detail);
setSupportActionBar(myChildToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
/* #Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.add();
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
TextView textView = (TextView) findViewById(R.id.dinner_text);
CharSequence dinnerName = textView.getText();
MenuItem menuItem = menu.findItem(R.id.action_share);
ShareActionProvider shareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, dinnerName);
shareActionProvider.setShareIntent(intent);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, TopFragment.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
//Click button, and add dinnerName to SecondActivity ListView
public void addInOrder(View view) {
int dinner = (Integer) getIntent().getExtras().get(EXTRA_DINNER);
String dinnerName = Dinner.dinn[dinner].getName();
Intent intent1 = new Intent(this, CreateYourOrderActivity.class);
intent1.putExtra("OK", dinnerName);
startActivityForResult(intent1, requestCode);
}
}
Second Activity:
public class CreateYourOrderActivity extends AppCompatActivity {
private ListView listView;
private ArrayAdapter<String> adapter;
private ArrayList<String> listItems;
private String dinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_zloz_zamowienie);
Toolbar myChildToolbar = (Toolbar)
findViewById(R.id.my_child_toolbar);
setSupportActionBar(myChildToolbar);
ActionBar ab = getSupportActionBar();
ab.setDisplayHomeAsUpEnabled(true);
textView = (TextView) findViewById(R.id.text_view);
}
/*
#Override
protected void onResume() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", obiad);
editor.apply();
listItems.add(obiad);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
super.onResume();
}
*/
/* #Override
public void onBackPressed() {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("KEY", listItems.get(0).toString());
editor.apply();
Toast.makeText(getApplicationContext(), "Save!", Toast.LENGTH_SHORT).show();
}*/
public void saveInfo(View view) {
}
public void openInfo(View view) {
SharedPreferences sharedPref = getSharedPreferences("KEY", Context.MODE_PRIVATE);
String obiadNames = sharedPref.getString("KEY", "");
textView.setText(obiadNames);
//listItems.add(obiadNames);
//adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_create_order:
Intent intent = new Intent(this, MainActivity.class);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Intent intent = getIntent();
if(resultCode == RESULT_OK) {
if(requestCode == 1){
dinner = data.getExtras().getString("OK");
listView = (ListView) findViewById(R.id.listView);
listItems.add(dinner);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
// adapter.add(dinner);
adapter.notifyDataSetChanged();
finish();
}
}
}
So as you can see in the attached photos we have the first Activity, several dishes from which we go to the detailed Activity, where we have AddOrder Button.
I would like to click on this button to add the name of my specific dish in the 3 Activities that you see in the pictures.
This is to be added as a ListView.
Also, I would like to have the names of dishes not gone when I return to 1 Activity.
SharedPreferences are for simple values.
You'll need a proper database (Sqlite, Realm, or other) with which you can persistently store and query your data across the entire application without passing entire objects across Intent boundaries.
More specifically, you need to replace the Dinner.dinn array
To get specific items when you go to a detail view, you can pass the database ID of the object, then query it later.
When you add a new item and go back to the list, you will update the adapter with all the database entries
I am trying to save to shared preferences. I want to be able to load from shared preferences but when I save and or load at the moment my app crashes.
I also want to be able to have my handler/runnable resume when my app starts up. How can I do this?
Here is my code:
public class MainActivity extends ActionBarActivity {
public void save(){
Editor editor = pref.edit();
editor.putInt("countertest", counter);
editor.commit();
}//end of save
public void read(){
counter = pref.getInt("countertest", counter);
}//end of read
Handler testHandler = new Handler();
int counter;
TextView testView;
Button testButton;
Runnable Runnable0;
SharedPreferences pref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
testView = (TextView) findViewById(R.id.testView);
testButton = (Button) this.findViewById(R.id.testButton);
// read();
testView.setText(Integer.toString(counter));
}
#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 onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
//read();
final Runnable Runnable0 = new Runnable() {
#Override
public void run() {
counter += 1;
testView.setText(Integer.toString(counter));
testHandler.postDelayed(this, 1000);
// save();
}// end of if
};
/* button click */
testButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
/* Start runnable */
testButton.setEnabled(false);
counter -= 5;
//save();
testView.setText(Integer.toString(counter));
testHandler.post(Runnable0);
}// end of onClick
});// end of blingButton onClickListener
super.onResume();
}//end of onResume
#Override
protected void onPause() {
//save();
testHandler.removeCallbacks(Runnable0);
super.onPause();
}//end of onPause
}
You haven't initialize your pref object. You have just declared it. So you need to do it on onCreate() by
pref = getSharedPreferences("MySP", 0);
OR
pref = PreferenceManager.getDefaultSharedPreferences(this);
I want to change the background-color of another Activity (start) in my Settings-Activity (choose between different colors, sounds etc.).
How can I change the color of another Activity?
I tried to get the Background from my start-Activity (id:start) with:
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
but it seems it doesn´t work.
Full Code of the Settings-Activity:
public class activity_settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_settings);
ColorChange();
}
public void ColorChange() {
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
final RadioButton ChangeToBlue = (RadioButton) findViewById(R.id.button_blue);
final RadioButton ChangeToRed = (RadioButton) findViewById(R.id.button_red);
final Button button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ChangeOption(background);
}
});
ChangeToBlue.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToBlue(background);
}
});
ChangeToRed.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToRed(background);
}
});
}
public void ChangeOption(RelativeLayout background) {
if (background.isEnabled()) {
background.setEnabled(false);
} else {
background.setEnabled(true);
}
}
public void ChangeToBlue(RelativeLayout background) {
background.setBackgroundColor(Color.BLUE);
background.invalidate();
}
public void ChangeToRed(RelativeLayout background) {
background.setBackgroundColor(Color.RED);
background.invalidate();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity_settings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}}
Save color code i.e. #F0F0F0 from your setting-activity in a sharedPreference and get this value in onCreate() of activity in which you want to set background.
I am a newbie to android, so please be patient.
I am trying to learn preferences. I have an app that has a mainActivity, when the menu icon it's pressed a MyPreferenceActivity is shown. It allows the user setting some preferences related to a subject.
In my mainActivity I have a loadPrefernces method that works fine when the app is installed, but the first time it throws an error: unable to start activity component info[..] java.lang.NullPointerException
Here is my code:
MainActivity
public class MainActivity extends Activity {
public static final String PREFERENCE_FILENAME = "com.id11298775.exercise6_preferences";
SharedPreferences mSharedPreferences;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPreferences(); // this cause the error
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent i = new Intent(MainActivity.this, MyPreferenceActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
protected void onResume() {
super.onResume();
loadPreferences();
}
private void loadPreferences() {
mSharedPreferences = getSharedPreferences(PREFERENCE_FILENAME,
MODE_PRIVATE);
// Setting the textView related to the subject
TextView subjectTv = (TextView) findViewById(R.id.activitymain_favouritesubjectresult_tv);
subjectTv.setText(mSharedPreferences.getString("list_subject_pref",
null));
// Setting the TextView related to the URL
TextView urlTv = (TextView) findViewById(R.id.activitymain_handbookurlresult_tv);
urlTv.setText(mSharedPreferences.getString("et_subject_pref", null));
// Setting the TextView related to the times selected
TextView labTimeTv = (TextView) findViewById(R.id.activitymain_labtimeresult_tv);
// #SuppressWarnings("unchecked")
Map<String, ?> map = mSharedPreferences.getAll();
Object cs = map.get("list_times_pref");
labTimeTv.setText(cs.toString());
}
#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;
}
}
this is my MyPreferenceActivity
public class MyPreferenceActivity extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preference);
}
#SuppressWarnings("deprecation")
#Override
protected void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
protected void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#SuppressWarnings("deprecation")
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equals("list_subject_pref")) {
ListPreference preference = (ListPreference) findPreference(key);
CharSequence currText = preference.getEntry();
preference.setSummary(currText);
} else if (key.equals("et_subject_pref")) {
EditTextPreference preference = (EditTextPreference) findPreference(key);
String newUrl = preference.getText().toString();
preference.setSummary(newUrl);
} else if (key.equals("list_times_pref")) {
Set<String> selections = sharedPreferences.getStringSet(
"list_times_pref", null);
String[] selected = selections.toArray(new String[] {});
String listSelection = "";
for (int i = 0; i < selected.length; i++) {
listSelection += selected[i] + " ";
}
MultiSelectListPreference multi = (MultiSelectListPreference) findPreference(key);
multi.setSummary(listSelection);
} else if (key.equals("ringtonePref")) {
RingtonePreference preference = (RingtonePreference) findPreference("ringtonePref");
String strRingtonePreference = ((SharedPreferences) preference).getString("ringtonePref", "none");
Uri ringtoneUri = Uri.parse(strRingtonePreference);
Ringtone ringtone = RingtoneManager.getRingtone(this, ringtoneUri);
String name = ringtone.getTitle(this);
preference.setSummary("select " + name);
}
}
}
here is logcat:
I think that the first time the app is installed there are no preference set, therefore the error, but I can't figure out a good way to prevent the exception.
Anybody can please help me?