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);
Related
When I try to run my app on the emulator I have a tab message saying
"unfortunately,GeoQuiz has stopped working" .......
GeoQuiz is my app's name .......
here is my activity class in the QuizActivity.java file
public class QuizActivity extends ActionBarActivity {
private Button mTrueButton;
private Button mFalseButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
mTrueButton=(Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this,R.string.correct_toast,Toast.LENGTH_SHORT).show();
}
});
mFalseButton=(Button) findViewById(R.id.false_button);
mFalseButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(QuizActivity.this, R.string.incorrect_toast, Toast.LENGTH_SHORT).show();
}
});
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
}
#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_quiz, 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);
}
}
I have no images at all in my app
and the min sdk version for this app is API 16:android 4.1 (jelly bean)
and the targeted version is API 21:android 5.0 (Lollipop)
you dont call setContentView at the right place:
you call it at the end of the onCreate method! You have to move these two lines to the beginning of the onCreate Method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
because of that you get a NullPointerException here:
mTrueButton=(Button) findViewById(R.id.true_button);
mTrueButton.setOnClickListener(new View.OnClickListener() { // NPE
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);
}
First time i had done coding without preferences the button can visible but when i put preferences code the button not visible
i have 3 class it is menu.class, levelone.class, leveltwo.class
this is the following code of menu.class like this
public class menu extends Activity {
Button f1, f2;
ImageView f2lock;
boolean levelTwoUnlocked;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.famouslevel);
f1 =(Button)findViewById(R.id.f1);
f1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level1 = new Intent ();
level1.setClassName ("com.example.game", "com.example.game.levelone");
startActivityForResult (level1, 0);
}
});
}
public void onActivityResult (int requestCode, int resultCode, Intent level1) {
super.onActivityResult (requestCode, resultCode, level1);
f2=(Button)findViewById(R.id.f2);
f2lock=(ImageView)findViewById(R.id.f2lock);
switch (resultCode) {
case 2: SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
if(levelTwoUnlocked){
f2.setVisibility(View.VISIBLE);
f2lock.setVisibility(View.GONE);
}
else {
f2.setVisibility(View.GONE);
f2lock.setVisibility(View.VISIBLE);
}
}
f2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
// TODO Auto-generated method stub
Intent level2 = new Intent ();
level2.setClassName ("com.example.game", "com.example.game.leveltwo");
startActivityForResult (level2, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.splashscreen, 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);
}
}
and in levelone.class i have put this code
public void onClick(View v){
setResult (2);
finish();
}
});
thats code is to make button visible in menu.class but when levelone.class finish(); is nothing happen with the button, it's still GONE
f2 button function is to open leveltwo.class and in leveltwo.class had same code to set f3 button visible
public void onClick(View v){
setResult (3);
finish();
}
});
and so on with the next level had a same code to make button visible
Did my code setResult is wrong or the preferences code make it not function?
Int the lines:
SharedPreferences preferences = getSharedPreferences("preferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("f2", levelTwoUnlocked);
editor.commit();
You just put always false to "f2", because levelTwoUnlocked is always false.
Assign a boolean value to leveTwoUnloacked
or
make changes in
editor.putBoolean("f2",true);
and check
if(prefernces.getBoolean("f2",false))
{
//your code
}
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?