I want to create a simple app to upload my location .I have two activities and in first activity the user can input parameters url for upload with editbox , a checkbox if user wish upload location save preferences button and start button for go to get location activity.I try this but no work...How i call my function start and save?Any help?I have errors when debug...after click button
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
String strValue = preferences.getString("Url",strValued);
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
edittxtUrl.setText(strValue);
Button buttonStart = (Button)findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(startListener);
Button buttonSave = (Button)findViewById(R.id.buttonSave);
buttonSave.setOnClickListener(saveListener);
}
private OnClickListener startListener = new OnClickListener() {
public void onClick(View v) {
Start();
}
};
private OnClickListener saveListener = new OnClickListener() {
public void onClick(View v) {
Save();
}
};
public void Save() {
SharedPreferences preferences = getSharedPreferences("gpstracker" , MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
edittxtUrl = (EditText)findViewById(R.id.txtUrl);
String strUrl = edittxtUrl.getText().toString();
CheckBox chkTandC = (CheckBox)findViewById(R.id.chkTandC);
boolean blnTandC = chkTandC.isChecked();
editor.putString("Url", strUrl); // value to store
editor.putBoolean("TandC", blnTandC); // value to store
// Commit to storage
editor.commit();
}
public void Start() {
startActivity(new Intent(this, LocTracker.class));
}
Without your log cat it is somewhat hard to tell what your problem is, but what I think is happening is that you are passing a null view to the start method, and this is a problem because you are then trying to get a context. Effectively what you have written is
null.getContext()
which doesn't work. You can fix this by replacing view.getContext() with getApplicationContext()
Related
i am kind of new to android programming , i am designing a program that has login page and main page.When i sign in for the first time with a username and password, i created a sharedpreferences to remember that username and whenever i enter program , it skips login page and redirects me to main page.What i want to do is, when i press logout button in login page ,i want sharedpreferences forget the value of username in my database(it wont delete it from database) and force me to login me again with the same or different username and password , and i dont want to be redirected to main page when i enter application.I found something like SharedPreferences.Editor.remove() , SharedPreferences.Editor.clear(),commit() ,etc.. But code didnt work.Can you help?
public static class SaveSharedPreference {
static final String PREF_USER_NAME = "username";
static SharedPreferences getSharedPreferences(Context ctx) {
return PreferenceManager.getDefaultSharedPreferences(ctx);
}
public static void setUserName(Context ctx, String userName) {
SharedPreferences.Editor editor = getSharedPreferences(ctx).edit();
editor.putString(PREF_USER_NAME, userName);
editor.commit();
}
public static String getUserName(Context ctx) {
return getSharedPreferences(ctx).getString(PREF_USER_NAME, "");
}
}
Button btnSignIn, btnSignUp;
LoginDataBaseAdapter loginDataBaseAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_uye_kayit_giris);
if (SaveSharedPreference.getUserName(UyeKayitGirisActivity.this).length() == 0) {
Intent i = new Intent(UyeKayitGirisActivity.this, MainActivity.class);
startActivity(i);
// finish();
}
// create a instance of SQLite Database
loginDataBaseAdapter = new LoginDataBaseAdapter(this);
loginDataBaseAdapter = loginDataBaseAdapter.open();
// Get The Refference Of Buttons
btnSignIn = (Button) findViewById(R.id.buttonSignIN);
btnSignUp = (Button) findViewById(R.id.buttonSignUP);
// Set OnClick Listener on SignUp button
btnSignUp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
/// Create Intent for SignUpActivity abd Start The Activity
Intent intentSignUP = new Intent(getApplicationContext(), SignUPActivity.class);
startActivity(intentSignUP);
}
});
Button btn_exit;
// super.onCreate(savedInstanceState);
// setContentView(R.layout.main1);
btn_exit = (Button) findViewById(R.id.buttonLogOUT);
btn_exit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// WHAT SHOULD I WRITE IN HERE?????????????
Toast.makeText(UyeKayitGirisActivity.this, "ÜYE GİRİŞİ TEKRAR ZORUNLU HALE GETİRİLDİ!!!", Toast.LENGTH_LONG).show();
}
});
}
Try like this
SharedPreferences pref = mContext.getSharedPreferences(PREF_NAME, PRIVATE_MODE);
Editor editor = pref.edit();
editor.clear();
editor.commit();
Here is the Method
private void removePreference(Context context, String prefsName, String key) {
SharedPreferences preferences = context.getSharedPreferences(prefsName, Activity.MODE_PRIVATE);
android.content.SharedPreferences.Editor editor = preferences.edit();
editor.remove(key);
editor.apply();
}
You can call it like:
public void removeUser() {
removePreference(context, FILENAME, KEY_USER);
}
Since you have mentioned that you do NOT want to delete the value of login from shared preference but only ask for login page each time, I believe you are looking for something where you want to clear application cache programatically.
Please check, Clear Cache in Android Application programmatically and Clear Application's Data Programmatically
It is also worth reading this wonderful answer - Don't delete database or shared Preference on clear app
To remove them all SharedPreferences.Editor.clear() followed by a commit()
I am making a game like logo quiz. I have the question activity and the levels activity so when users answer correctly they score 1. Then I want to put the score in the levels activity so in that way users could unlock the next level, but I don't want users leave the question activity and until now I have only found this method:
Intent resultIntent = new Intent(this, NextActivity.class);
resultIntent.putExtra("score", score);
startActivity(resultIntent);
However, with this method the user goes to the levels activity.
I will leave my code for reference:
public class Big extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_big);
init();
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true); }
public boolean onOptionsItemSelected(MenuItem item){
Intent myIntent = new Intent(getApplicationContext(), Level1.class);
startActivityForResult(myIntent, 0);
return true;
}
private Button buttonSaveMem1;
private EditText escrive;
private TextView respuest;
private String [] answers;
int score=0;
int HighScore;
private String saveScore = "HighScore";
private int currentQuestion;
public void init()
{
answers = new String[]{"Big"};
buttonSaveMem1 = (Button)findViewById(R.id.button1);
respuest = (TextView) findViewById(R.id.textView2);
escrive = (EditText) findViewById(R.id.editText1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
LoadPreferences();
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
checkAnswer();
// TODO Auto-generated method stub
SavePreferences();
LoadPreferences();
}};
public boolean isCorrect(String answer)
{
return (answer.equalsIgnoreCase(answers[currentQuestion]));
}
public void checkAnswer() {
String answer = escrive.getText().toString();
if(isCorrect(answer)) {
update();
respuest.setText("You're right!" + " The Answer is " + answer + " your score is:" + score +" " +
"HighScore: " + HighScore);
score =1;
}
else {
respuest.setText("Sorry, The answer is not right!");
}
}
private void update() {
if (score > HighScore)
{ HighScore = score; }
}
private void SavePreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("MEM1", respuest.getText().toString());
sharedPreferences.edit().putInt(saveScore, HighScore).commit();
editor.commit();
}
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
HighScore = sharedPreferences.getInt(saveScore, 0);
respuest.setText(strSavedMem1);
}
#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;
}
}
And here is the levels activity:
public class Level extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level);
Button salir = (Button) findViewById(R.id.button3);
salir.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, MainActivity.class)); }
}
)
;
Button leve2 = (Button) findViewById(R.id.button1);
leve2.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level2.class)); }
}
)
; }
Button leve1 = (Button) findViewById(R.id.button1);
leve1.setOnClickListener( new View.OnClickListener() {
#Override public void onClick(View v) {
startActivity(new Intent(Level.this, Level1.class)); }
}
)
;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level, menu);
return true;
}
}
Thanks for the help!
In your questions activity, store the score of the user in the SharedPreferences
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
prefs.edit.putLong(USER_SCORE, score).commit();
And then when you return to your level's activity, you can fetch from the preferences.
SharedPreferences prefs = getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE);
long userScore = prefs.getLong(USER_SCORE, 0);
USER_SCORE is just a string key like USER_SCORE = "user_score" to allow the device to find the date you stored in the prefs.
Shared preferences are saved to the phone and not accessible except through the app that they belong to. So upon starting the app again, you can get the User's score that was saved last time they used the app.
You can make make the score as static and then modify it from the other activity class. IT would automatically change it in the original.
Store the score in a SharedPreferences instead of passing it to Level in an intent. You can then retrieve that score within the levels Activity (or any other for that matter), whenever the user may navigate there. You already use SharedPreferences in your code with:
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
However that returns a Shared Preference using the calling Activity's class name as the Shared Preference name, i.e. those preference values are private to your Activity 'Big'. To use preference values that have application scope, use getSharedPreferences(), providing a Shared Preferences name:
SharedPreferences sharedPreferences = getSharedPreferences("MYPREFS", Activity.MODE_PRIVATE);
Create an Editor from that and store the value of 'score'. Then retrieve it your Level activity, most likely in its onCreate().
After looking here and there, I've finally found out my answer to this question by following other answers and I basically used the following combination of codes to do so.
In a first activity:
import:
import android.content.Context;
import android.content.SharedPreferences;
declare:
public static int totalCount;
and add onCreate():
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);`
totalCount++;`
editor.putInt("counter", totalCount);`
editor.apply();`
Then, on a second activity:
import:
import static com.example.myapp.totalCount
and add onCreate():
((TextView) findViewById(R.id.text_view_id)).setText(String.valueOf(totalCount));
In the layout for the second activity:
place a TextView with:
android:id="#+id/text_view_id"
And pay attention to what the documentation says about naming shared preferences.
When naming your shared preference files, you should use a name that's
uniquely identifiable to your app. An easy way to do this is prefix
the file name with your application ID. For example:
"com.example.myapp.PREFERENCE_FILE_KEY"
I have a single string which the user will edit and will be displayed back to him when he uses the app. He can edit the string at any time. I am familiar with SQLite databases, but because for this purpose I am using only one string/one record, I felt SharedPreferences would be better. However, after following two different tutorials, I am unable to get it so save the data. In both cases I have needed to amend the tutorial code because I will be using two activities, one to view the code, the other to edit it. I was unable to find a tutorial for using sharedpreferences for two activities. Below is the code.
Class to view the code:
public class MissionOverviewActivity extends Activity {
TextView textSavedMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_view);
textSavedMem1 = (TextView)findViewById(R.id.textSavedMem1);
LoadPreferences();
textSavedMem1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finish();
return;
}});
};
private void LoadPreferences(){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
String strSavedMem1 = sharedPreferences.getString("MEM1", "");
textSavedMem1.setText(strSavedMem1);
}
}
Class to edit the code and return to the view page
public class MissionDetailActivity extends Activity {
EditText editText1;
Button buttonSaveMem1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mission_edit);
editText1 = (EditText)findViewById(R.id.editText1);
buttonSaveMem1 = (Button)findViewById(R.id.buttonSaveMem1);
buttonSaveMem1.setOnClickListener(buttonSaveMem1OnClickListener);
}
Button.OnClickListener buttonSaveMem1OnClickListener
= new Button.OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
SavePreferences("MEM1", editText1.getText().toString());
viewStatement();
}
};
private void SavePreferences(String key, String value){
SharedPreferences sharedPreferences = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
protected void viewStatement() {
Intent i = new Intent(this, MissionOverviewActivity.class);
startActivity(i);
}
}
If any body could answer this question, or point me in the direction of a sharedpreferences tutorial that uses two classes (for edit and displaying), It would be greatly appreciated!
Thanks
getPreferences(int) is private for Activity, you want to share the same SharedPreference between activities you should use this way:
SharedPreferences prefs = this.getSharedPreferences(
"yourfilename", Context.MODE_PRIVATE);
and use the same method when you want to reload it. here the doc for getPrerences(int)
When I click on an option I want a check sign to appear to show it has been purchased. I am using SharedPreferences and have made all the links; however, when I click back or exit and then re-enter the application, the check is gone and any history of anything I did before is gone. How do I save the data so that it is kept even when the application is off or I'm at another page in the game. This is my code so far:
ImageView tick1;
int mYellCheck, mYellCheck1;
public static String sharedPrefs = "MyData";
SharedPreferences data;
SharedPreferences.Editor editor;
int mYellAlpha;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.upgrades);
update();
coins = Replay.totalCoins + Replay4.totalCoins + Replay5.totalCoins
+ Replay6.totalCoins;
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
tick1.setAlpha(mYellCheck);
}
public void update() {
TextView coinScore = (TextView) findViewById(R.id.tvScore);
coinScore.setText("You have " + coins + " coins");
tick1 = (ImageView) findViewById(R.id.ivtick1);
ImageView moreYellow = (ImageView) findViewById(R.id.ivMoreYellow);
ImageView back = (ImageView) findViewById (R.id.ivBack);
back.setOnClickListener(this);
moreYellow.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ivMoreYellow:
mYellAlpha = 255;
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
data = getSharedPreferences(sharedPrefs, MODE_PRIVATE);
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
break;
case R.id.ivBack:
Intent i = new Intent ("m.k.zaman.SpotActivity");
startActivity(i);
break;
}
}
EDIT
or Should i just use internal storage?
Try replacing your current onClick call to R.id.ivMoreYellow with this:
case R.id.ivMoreYellow:
mYellAlpha = 255;
mYellCheck = data.getInt("MoreYellowUpgrade", 0);
tick1.setAlpha(mYellCheck);
SharedPreferences.Editor editor = data.edit();
editor.putInt("MoreYellowUpgrade", mYellAlpha);
editor.commit();
break;
You were first overwriting all of the data in the SharedPreferences, and then calling to receive that data that you just overwrote, so I placed the getInt() call before the putInt(). Do you change mYellAplha to anything other than 255 though? If you don't you will never notice a change in SharedPreferences if you are always saving and getting 255.
I decided to use sharedPreferences so I could store the value of a togglebutton on my activity Preferences. On my main activity I want to hide a twitter button when the user clicks the twitter button in the Preferences activity.
private SharedPreferences prefs;
private String prefName = "MyPref";
private ToggleButton timer, twitter;
// this is the key used to set the timer to visible or hidden
private static final String TIMER_KEY = "timekey";
private static final String TWITTER_KEY= "tweet";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.preferences);
timer = (ToggleButton)findViewById(R.id.timer_pref);
twitter =(ToggleButton)findViewById(R.id.twitter_pref);
timer.setChecked(true);
twitter.setChecked(true);
// Toast.makeText(Preferences.this, timer, Toast.LENGTH_SHORT).show();
Button b = (Button) findViewById(R.id.home_btn);
b.setOnClickListener(new View.OnClickListener()
{
// now add the new screen
public void onClick(View arg0) {
// TODO Auto-generated method stub
// get the shared perference data
Intent i = new Intent(Preferences.this, AndroidGUIActivity.class);
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
prefs = getSharedPreferences("MyPref", 0 );
SharedPreferences.Editor editor = prefs.edit();
if (timer.isChecked() == true)
{
editor.putBoolean("twitterButtonStatus", true);
}
else if(timer.isChecked() == false)
{
editor.putBoolean("twitterButtonStatus", false);
}
// now save the value that is passed to the editor.putBoolean function
// the twitter data hase been saved
editor.commit();
// now store the variable so that it can be copied to another activity
Bundle b = new Bundle();
}
});
There is no need to transfer Preferences through activities using intent.
You can access your "shared"Preferences from any activity.
You just put the button status with a string key inside:
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean("twitterButtonStatus", buttonStatus);
And in another activity you retrieve these preferences using string key ("twitterButtonStatus"):
SharedPreferences settings = getSharedPreferences("MyPrefs", 0);
boolean buttonStatus = settings.getBoolean("twitterButtonStatus", false); // second param is default!
See: http://developer.android.com/guide/topics/data/data-storage.html
Edit:
Youre saving SharedPrefs now, to get them back and set your Button Gone do something like this:
SharedPreferences settings = getSharedPreferences(prefName, 0);
boolean buttonStatus = settings.getBoolean(TWITTER_KEY, true); //2nd is default
if(buttonstatus==false) twitter.setVisibility(View.GONE);