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);
}
}
Related
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 fill the TextView of another activity based on preference on checkBox event but its working please help me to sort the issue..It is forcefully stopping.Please help in the if else statement part .what we need to write in activity 2 to select based on the checkBox in activity 1
Activity 1:
package com.example.rajatanurag.shoppingsites;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
public class Book extends AppCompatActivity {
Button b1,b2;
public static CheckBox cb1,cb2,cb3;
TextView tv1,tv2,tv3;
SharedPreferences sp1;
ImageView iv1,iv2,iv3;
String x,y,z;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
b1=(Button)findViewById(R.id.b1);
b2=(Button)findViewById(R.id.b2);
cb1=(CheckBox)findViewById(R.id.cb1);
cb2=(CheckBox)findViewById(R.id.cb2);
cb3=(CheckBox)findViewById(R.id.cb3);
tv1=(TextView)findViewById(R.id.tv4);
tv2=(TextView)findViewById(R.id.tv2);
tv3=(TextView)findViewById(R.id.tv3);
iv1=(ImageView)findViewById(R.id.iv1);
iv2=(ImageView)findViewById(R.id.iv2);
iv3=(ImageView)findViewById(R.id.iv3);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
}
public void OnClick1(View view)
{
SharedPreferences.Editor editor = sp1.edit();
if(cb1.isChecked()==true) {
editor.putString("price1", tv1.getText().toString());
editor.putBoolean("x",true);
}
if(cb2.isChecked()==true)
{
editor.putString("price2",tv2.getText().toString());
editor.putBoolean("y",true);
}
if(cb3.isChecked()==true)
{
editor.putString("price3",tv3.getText().toString());
editor.putBoolean("z",true);
}
editor.commit();
Intent i=new Intent(this,MyCart.class);
startActivity(i);
}
}
2.Activity
package com.example.rajatanurag.shoppingsites;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MyCart extends AppCompatActivity {
SharedPreferences sp1;
TextView tv4,tv5,tv6;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_cart);
tv4=(TextView)findViewById(R.id.tv4);
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
if(Book.cb1.isChecked()==true){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(Book.cb1.isChecked()==true){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(Book.cb1.isChecked()==true){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
}
}
You shouldn't be using static variables for view members because you might get memory leaks. Also the views you are referencing are destroyed when activity is destroyed, so they are not accessible in your second activity. You can send checkboxes checked values as intent extras.
Put this in your Activity 1 in OnClick1() method:
Intent i=new Intent(this,MyCart.class);
i.putExtra("cb1", cb1.isChecked());
i.putExtra("cb2", cb2.isChecked());
i.putExtra("cb3", cb3.isChecked());
startActivity(i);
This is how you get values in Activity 2 (in onCreate() method):
Intent intent = getIntent();
if(intent.getBooleanExtra("cb1", false)){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
if(intent.getBooleanExtra("cb2", false)){
String price21=sp1.getString("price2","");
tv5.setText(price21);
}
if(intent.getBooleanExtra("cb3", false)){
String price31=sp1.getString("price3","");
tv6.setText(price31);
}
public void OnClick1(View view)
{
if(view.getID() == R.id.cb1)
{
if(cb1.isChecked())
editor.putBoolean("x",true);
else
editor.putBoolean("x",false);
}
}
In your second activity
sp1=getSharedPreferences("SHOPPING",MODE_PRIVATE);
boolean isChecked = sp1.getBoolean("x", false);
if(isChecked){
String price11 = sp1.getString("price1", "");
tv4.setText(price11);
}
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 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);
}
Hello I am new to android and actually i am developing a application whereby the user would be clicking on a button and the button should record the click event - the counter should be incremented at each time the button is clicked. The button would be displayed in one activity and once the user has clicked the button, another activity would be displayed whereby the results would be shown.
Actually i am having problems in assigning the sharedPreferences to the button and then displaying it into the next activity hence having the number of clicks.
The code i am using is as follows:
MainActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
/** Declare the variables being used */
public static final String GAME_PREFERENCES = "GamePrefs";
public static final String GAME_PREFERENCES_SCORE = "Score"; // Integer
int counter;
Button add;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
Intent openClickActivity2 = new Intent("com.android.jay.Results");
startActivity(openClickActivity2);
}
});
}
}
Results.java
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.TextView;
public class Results extends MainActivity{
public void onCreate(Bundle savedInstanceState) {
SharedPreferences mGameSettings;
super.onCreate(savedInstanceState);
mGameSettings = getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE);
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
if (mGameSettings.contains(GAME_PREFERENCES_SCORE)) {
DisplayResults.setText(mGameSettings.getString(GAME_PREFERENCES_SCORE, “counter”));
}
}
}
Any help to guide me would be much appreciated.Thank you
You will have to set GAME_PREFERENCES_SCORE in MainActivity. Do something like this after counter++:
getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE).edit().setInt(GAME_PREFERENCES_SCORE, counter). commit();
Simply make a Preferences class
public class Preferences {
String MASTER_NAME = "mysticmatrix_master";
SharedPreferences mysticMatrixPref;
Preferences(Context context) {
mysticMatrixPref = context.getSharedPreferences(MASTER_NAME, 0);
}
public void setAddCount(int count) {
SharedPreferences.Editor prefEditor = mysticMatrixPref.edit();
prefEditor.putInt("count", count);
prefEditor.commit();
}
public int getAddCount() {
return mysticMatrixPref.getInt("count", 0);
}
}
and in your MainActivity.java put this code
public class MainActivity extends Activity implements OnClickListener {
ImageButton add;
Preferences cpObj;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
preferences = new Preferences(getApplicationContext());
/*
* getting the count variable and adding 1 in that to check the condition of showing rate activity and adds
*/
add = (Button) findViewById (R.id.bAdd);
add.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cpObj = new Preferences(getApplicationContext());
cpObj.setAddCount(cpObj.getAddCount() + 1);
}
});
}
}
And in your result activity just get the count's value
import android.content.Context;
public class Results extends MainActivity{
Preferences cpObj;
public void onCreate(Bundle savedInstanceState) {
preferences = new Preferences(getApplicationContext());
setContentView(R.layout.results);
final TextView DisplayResults =
(TextView) findViewById(R.id.bAdd);
DisplayResults.setText(cpObj.getAddCount());
}
} }
By this you will get the default value of result as '0' and you can set that in your Preferences class
Use a method like this:
public static void SavePreference(Context context, String key, Integer value) {
SharedPreferences.Editor editor = PreferenceManager
.getSharedPreferences(GAME_PREFERENCES, Context.MODE_PRIVATE)
.edit();
editor.putInt(key, value);
editor.commit();
}
and in you onclick after counter++ add this:
SavePereference(context, "GAME_PREFERENCES_SCORE", counter);