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);
}
Related
I am trying to make an app where the user types in text and presses enter and a button is dynamically placed on a different activity with its text set as what the user inputs. I am not sure how to do this, I was thinking of saving the user input in a sharedPreference but I am not sure where to go from there.
package com.example.opisa;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
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 AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences sharedPref= getSharedPreferences("mypref", 0);
//now get Editor
SharedPreferences.Editor editor= sharedPref.edit();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
}
public void addGoalText(View view) {
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
} else {
mText.setText(name.getText().toString());
}
}
//put your value
editor.putString("goals", name);
//commits your edits
editor.commit();
}
After the user types in what he wants,I would like the mText to be the value of text on a button that dynamically appears on a different activity.
In Your First Activity Write
public class AddGoalsActivity extends AppCompatActivity {
// Create object of SharedPreferences.
SharedPreferences setValue ;
//now get Editor
SharedPreferences.Editor valueEditor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_goals);
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
}
public void addGoalText() {
valueEditor = setValue.edit();
EditText name = (EditText) findViewById(R.id.editText1);
TextView mText = (TextView) findViewById(R.id.textView);
if (name.getText().toString().isEmpty()) {
mText.setText("Didnt type anything");
valueEditor.putString("key","Didn't type");
} else {
mText.setText(name.getText().toString());
valueEditor.putString("key", String.valueOf(name.getText()));
}
valueEditor.apply();
}
}
If you are calling addGoalText somewhere , if not use onchangelistener
In Your Second Activity in which you have button
public class SecondActivity extends AppCompatActivity {
SharedPreferences setValue ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);// your layout
setValue = getSharedPreferences("key",Context.MODE_PRIVATE);
Button your_button =findViewById(R.id.buttonId);//write your own ID
String S = setValue.getString("key","defaultValue");
your_button.setText(S);
}
}
When i try to save a variable to shared preferences then call it in an editext it is not being saved? I've been looking around for hours but i cannot find anything on it. I know that sharedPrefrences acts like a dictionary in a way but other than that i don't understand why this is not working :(
package com.example.gatorblocks;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.wearable.activity.WearableActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class block1Settings extends WearableActivity{
private TextView mTextView;
Context context = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_block1_settings);
configureBackButton();
configureColor();
Button addTextButton = (Button) findViewById(R.id.Apply);
TextView simpleEditText = findViewById(R.id.simpleEditText);
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("classes1","1-1")); //set textbox to equal current class
final EditText vEditText = (EditText) findViewById(R.id.simpleEditText);
mTextView = (TextView) findViewById(R.id.text);
// Enables Always-on
setAmbientEnabled();
addTextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String enteredText = vEditText.getText().toString(); //sets the array value of block to the editText
test(enteredText);
}
});
}
private void configureColor() {
Button Block1 = (Button) findViewById(R.id.colorButton);
Block1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, colorBlock1.class));
overridePendingTransition(R.anim.slide_in_right,R.anim.slide_out_left);
}
});
}
private void configureBackButton(){
Button backbutton = (Button) findViewById(R.id.backButton);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(block1Settings.this, classes.class));
overridePendingTransition(R.anim.slide_in_left,R.anim.slide_out_right);
finish();
}
});
}
public void test(String enteredText){
SharedPreferences pref = getSharedPreferences("classes.txt", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("class1", enteredText);
editor.apply();
}
}
How did you get data from SharedPreferences which is not saved? You saved data using key class1 and want to get it by classes1 which is not correct way. You have to use same key. Try using
SharedPreferences prefs = getSharedPreferences("classes.txt", 0);
simpleEditText.setText(prefs.getString("class1","1-1"));
I want to change & save button text onLongClick permanently(until & unless I change it again). This is screenshot of overall code. But when I close the App & reopen it, the Button text remains default. What mistake am I doing?
package com.demo.buttontextedit;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
SharedPreferences sharedPreferences;
private Button btn;
private EditText edit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button) findViewById(R.id.button);
edit = (EditText) findViewById(R.id.edit_text);
btn.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
showDialog(edit.getText().toString());
return true;
}
});
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "You clicked Button" +
btn.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
}
private void showDialog(String str) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("input text");
View view = LayoutInflater.from(this).inflate(R.layout.dialog_view, null);
final EditText edit_dialog = (EditText) view.findViewById(R.id.edit_dialog);
edit_dialog.setText(str);
builder.setView(view);
builder.setNegativeButton("cancel", null);
builder.setPositiveButton("confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sharedPreferences = getSharedPreferences("myPref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("Name", edit_dialog.getText().toString());
editor.commit();
btn.setText(sharedPreferences.getString("Name", ""));
}
});
builder.show();
}
}
you are missing get text from shared preferences on Oncrete activity.
Solution
put this lines :
if (sharedPreferences.getString("Name", "").equals(""))
{
btn.setText("YES");
}else{
btn.setText(sharedPreferences.getString("Name", "YES"));
}
below this line :
btn = (Button) findViewById(R.id.button);
Flow of control causing this behavior.
you need to fetch data from preference in oncreate and set it on the button
like
oncreate(Bundle b) {
// initialize preference and layout
String btntext=sharedPreferences.getString("btnkey","Yes")
btn.setText(btntext);
}
so when application is recreated, you find the stored text from preference and set it on the button and it's done.
The main problem as I can see is that this line:
btn.setText(sharedPreferences.getString("Name", "YES"));
is called before the button is initialized and found in the view. This causes the string to be set to a nullpointer which(if not try-catched) crashes the app. As long as you define the button before you set the text, no nullpointer and text is set.
btn = (Button) findViewById(R.id.button);
btn.setText(sharedPreferences.getString("Name", "YES"));
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));