I am working with SharedPreference but I cannot save info.
These is my code:
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class SharedPrefApp extends Activity implements View.OnClickListener {
Button buton1 , buton2 ;
EditText etv1 , etv2 ;
TextView tv1;
private static SharedPreferences sharedPref;
protected void onCreate(Bundle bambam){
super.onCreate(bambam);
setContentView(R.layout.sharedpref_xml);
buton1 = ( Button) findViewById(R.id.button12);
buton2 = ( Button) findViewById(R.id.button13);
etv1= (EditText) findViewById(R.id.editText4);
etv2= (EditText) findViewById(R.id.editText5);
tv1 = (TextView) findViewById(R.id.textView12);
buton1.setOnClickListener(this);
buton2.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.button12:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("isim" , etv1.getText().toString());
editor.putString("sifre" , etv2.getText().toString());
editor.apply();
Toast.makeText(this , "Kaydedildi" , Toast.LENGTH_SHORT).show();
break;
case R.id.button13:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE);
String a = sharedPref.getString("isim", "olmadı");
String b = sharedPref.getString("sifre" , "olmadı");
tv1.setText(a + " " + b);
Toast.makeText(this, "Gosterildi" , Toast.LENGTH_SHORT).show();
break;
}
}
}
It returns olmadı olmadı in application. Why it doesn't work?
You have a typo in your code. You spelled name as nama, resulting in that you are trying to store and fetch values from two different preferences.
Your first button (R.id.button12) call to get shared preferences is:
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
change it to:
sharedPref = getSharedPreferences("namepassword" , Context.MODE_PRIVATE );
Why are you using editor.apply() method
try to using commit() method
For example
editor.commit()
Try the below code
sharedPref = getSharedPreferences("namapassword" , Context.MODE_PRIVATE );
sharedprefs.edit.putString("isim" , etv1.getText().toString()).commit();
Oh Boy... Your getString shouldb like the follows..
String a = sharedPref.getString("isim", null);
String b = sharedPref.getString("sifre" , null);
Related
This is my code:
package com.example.scheda_ais;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.File;
public class MainActivity extends AppCompatActivity {
EditText degustatore;
Button completa;
SharedPreferences sharedPref;
String generalita;
String appoggio;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
}
When I press the Button with an empty EditText (no input at all), nothing is printed by Log, while Log should print "generalita" + "vuoto".
Why String appoggio is empty?
If I input something in EditText, Log prints correctly "generalita" + appoggio.
Please someone help me. Thanks.
By using != to compare your string you are comparing "object instance" but "" and generalita string is not the same object so you are entering in the if and put "" to your preference so the preference is not null when you log it and the default value is not print.
that's what appens:
sharedPref = this.getSharedPreferences("il_sottoscritto",Context.MODE_PRIVATE);
degustatore = findViewById(R.id.degustatore);
completa = findViewById(R.id.completa);
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
// generalita instance and "" intance are not equal so the trest will pass
if(generalita != ""){
SharedPreferences.Editor editor = sharedPref.edit();
// here you're putting "" to your preference
editor.putString("generalita", generalita);
editor.commit();
}
// sharedPref.getString("generalita", "vuoto") return ""
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
you should do like that
completa.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
generalita = degustatore.getText().toString();
if(!generalita.equals("")){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
}
});
change this appoggio = sharedPref.getString("generalita", "vuoto");
to appoggio = sharedPref.getString("generalita", "");
There are two issues with what you wrote.
As #SebastienRieu said correctly
the first one , you can't do == for Strings in java.
You need to write:
if(!"".equals(generalita)){
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("generalita", generalita);
editor.commit();
}
And the 2nd one, you said you were expecting "generalita" + "vuoto"
However in this code:
appoggio = sharedPref.getString("generalita", "vuoto");
Log.d("generalita", appoggio);
in the Log the first word "generalita" is not text printed in the log, but rather a TAG that is filterable. If you want to see "generalita vuoto", then you'd have to put both on the right side.
Replace generalita != "", by !generalita.isEmpty() to check the length of your String.
I have a simple android page with a spinner, two check boxes and a submit button. The java code for the screen is as follows:
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import org.json.JSONException;
import org.json.JSONObject;
public class Main extends AppCompatActivity implements View.OnClickListener{
private Button submit;
private Button edit;
Spinner place;
private CheckBox male;
private CheckBox female;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
submit = (Button) findViewById(R.id.btn_submit);
submit.setOnClickListener(this);
edit = (Button) findViewById(R.id.btn_edit);
edit.setVisibility(View.GONE);
place = (Spinner) findViewById(R.id.place);
place.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapter, View v,
int position, long id) {
// On selecting a spinner item
String item = adapter.getItemAtPosition(position).toString();
str_specimen = item;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
male = (CheckBox) findViewById(R.id.male);
male.setChecked(false);
female = (CheckBox) findViewById(R.id.female);
female.setChecked(false);
submit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(Main.this,
home.class);
startActivity(intent);
}
});
}
}
I have a edit button that is not visible initially. When I choose a value from spinner and check a value in the check box and click on submit button. These values are sent to database and home page will launch.
What I want to do is that, when I visit the main page again, I want the previously selected values to appear and the spinner and checkbox should not be clickable, and the edit button should show up. If i click on the edit button the spinner and checkbox should be clickable and i should be able to submit again.
Can someone tell me how to do this?
Have a method, say isFirstVisit(), that returns a boolean if this is the first time the user is on that activity:
private boolean isFirstVisit() {
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
return prefs.getBoolean("IsFirstVisit", true);
}
Call it before you start adjusting your UI and then based on its value show/hide/check/uncheck/enable/disable various UI elements:
boolean firstTime = isFirstVisit();
edit = (Button) findViewById(R.id.btn_edit);
if(firstTime) {
edit.setVisibility(View.GONE);
}
Don't forget to set IsFirstVisit to false when done:
SharedPreferences prefs = getApplicationContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
SharedPreferences.Editor ed = prefs.edit();
ed.putBoolean("IsFirstVisit", false);
ed.commit();
Use SharedPreferences after click
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("place", place.getSelectedItem().toString(););
editor.putInt("male", male.getText());
editor.putInt("female", female.getText());
editor.commit();
Retrieve data from preference after setContentView(R.layout.main);
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
String restoredText = prefs.getString("text", null);
if (restoredText != null) {
String place = prefs.getString("place" null);
String male = prefs.getString("male", null);
String female = prefs.getString("female", null);
}
I'm developing a simple game in Android and even i followed the steps found in the net, the highscore of my app is never saved. I'm using SharedPreferences to store, but I'm quietly sure the problem is in there, because I don't understand at all how to use it.Hope you guys can help me, thanks.
package com.example.memory;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Final extends Activity implements OnClickListener{
TextView levelReachedText;
TextView bestScoreText;
int levelReached, bestScore;
Intent intent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.finals);
levelReachedText = (TextView) this.findViewById(R.id.nivel);
bestScoreText = (TextView) this.findViewById(R.id.best);
Button menu = (Button) findViewById(R.id.inicio);
menu.setOnClickListener(this);
intent = getIntent();
levelReached = intent.getIntExtra("nivel", 1);
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
int savedScore = preferences.getInt("selectedScore", 0);
levelReachedText.setText("You reached level "+levelReached );
if(savedScore>levelReached){
bestScore = savedScore;
}else{
bestScore = levelReached;
}
bestScoreText.setText("Maximum level reached "+levelReached);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.inicio:
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
preferences.edit().putInt("selectedScore", bestScore).commit();
this.finish();
break;
}
}
}
you are saving score value in mejorScore and trying to get it from bestScore.So either change
SharedPreferences preferences = this.getSharedPreferences("mejorScore", MODE_PRIVATE);
to
SharedPreferences preferences = this.getSharedPreferences("bestScore", MODE_PRIVATE);
or vice-versa.
I am trying to have it so when you click one of the answeers (Q1A1 or Q1A2) it will add a number of points to the testScore int so I can then later call that in a later class so the score they got would be posted there. Thanks to anyone who helps in advance!
here's my code,
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class Test extends Activity implements OnClickListener
{
TextView Q1A1;
TextView Q1A2;
TextView test;
public static final String PREFS_NAME = "MyPrefsFile";
public static final int testScore = 0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Q1A1 = (TextView) findViewById(R.id.Q1A1);
Q1A2 = (TextView) findViewById(R.id.Q1A2);
Q1A1.setOnClickListener(this);
Q1A2.setOnClickListener(this);
test = (TextView) findViewById(R.id.test);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
test.setText(settings.getString("YourScore", "No Score"));
}
public void onClick(View v)
{
switch(v.getId())
{
case R.id.Q1A1:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("YourScore", (testScore + 10));
editor.commit();
//Intent FinalScore = new Intent(this, FinalScore.class);
//startActivity(FinalScore);
break;
case R.id.Q1A2:
break;
}
}
}
thanks for the help
You are are saving your score as an int but calling it as a string.
Change
test.setText(settings.getString("YourScore" , "No Score"));
To
test.setText(""+settings.getInt("YourScore" , 0));
I want to save the value of a string at exit of my application(process kill) in last activity , so that when I start that application again I can retrieve that value in first activity.
I tried the sharedpreferences but that does not solve my problem. Here is the code snippet.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Intent int1 = getIntent();
String pth = prefs.getString("pathreturned", "true");
to retrieve in the first activity.
and this one to save it in the previous activity:
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
SharedPreferences.Editor e = myPrefs.edit();
e.putString("pathreturned", path);
e.commit();
In your previous Activity, use the same code as the one you used before...
Instead of
SharedPreferences myPrefs = getSharedPreferences("myPrefs", MODE_PRIVATE);
use
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
Here is a complete Example of Saving Strings Via SharedPreferences
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class SharedPrefs extends Activity implements OnClickListener{
private EditText dataInput;
private TextView dataView;
private SharedPreferences sharedString;
public static final String myFile = "MySharedDataFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sharedprefs);
setUpVariables();
sharedString = getSharedPreferences(myFile, 0);
}
public void setUpVariables(){
dataInput = (EditText) findViewById(R.id.dataToUse);
dataView = (TextView) findViewById(R.id.showDataView);
Button save = (Button) findViewById(R.id.savedataButton);
Button load = (Button) findViewById(R.id.loadDataButton);
save.setOnClickListener(this);
load.setOnClickListener(this);
}
public void onClick(View arg0) {
switch(arg0.getId()){
case R.id.savedataButton:
String dataToSave = dataInput.getText().toString();
Editor storeData = sharedString.edit();
storeData.putString("key", dataToSave);
storeData.commit();
break;
case R.id.loadDataButton:
sharedString = getSharedPreferences(myFile, 0);
String savedData = sharedString.getString("key", "No data Found");
dataView.setText(savedData);
break;
}
}
}
Unless you know which Activity is going to be "last" you should save your value at the close of each activity. Override the onStop method and save it there.