Change & Save Button Text onLongClick using sharedpreferences - android

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"));

Related

How do I create a button dynamically based on user input?

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);
}
}

Sharedprefrences not saving?

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"));

How to present different UI on first vs subsequent app use?

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);
}

Defined method is never called

I am creating a method to validate my login fields (user name and password). I have created a method and call it on click event but it is not working.
package com.boyzcorn.android.fyp;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
/** Called when the activity is first created. */
public class login extends Activity {
EditText eText = (EditText)findViewById(R.id.uid);
EditText eText2 = (EditText)findViewById(R.id.editText2);
Button btnSubmit = (Button)findViewById(R.id.sbtn);
Button btnSignup = (Button)findViewById(R.id.signupbtn);
/* I think there is some problem with my method definition but i am not
getting it. */
public void validation(EditText username,EditText pass) {
if (username.getText().toString().equals("") ||
pass.getText().toString().equals("")) {
Toast.makeText(
getApplicationContext(),
"Fill Empty Fields",Toast.LENGTH_SHORT
).show();
} else {
Intent i = new Intent(login.this,order_pushing.class);
startActivity(i);
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
btnSubmit.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
validation(eText,eText2);
}
});
btnSignup.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(login.this,signup.class);
startActivity(i);
}
});
}
}
Put this code under Activity{
EditText eText;
EditText eText2;
Button btnSubmit;
Button btnSignup;
and initialize it in OnCreate after setContentView(R.layout.login);
eText = (EditText)findViewById(R.id.uid);
eText2 = (EditText)findViewById(R.id.editText2);
btnSubmit = (Button)findViewById(R.id.sbtn);
btnSignup = (Button)findViewById(R.id.signupbtn);
Hope This will work
You are defining your buttons before setting the content view. Move the following lines into the onCreate(), after setContentView(R.layout.login):
EditText eText = (EditText)findViewById(R.id.uid);
EditText eText2 = (EditText)findViewById(R.id.editText2);
Button btnSubmit = (Button)findViewById(R.id.sbtn);
Button btnSignup = (Button)findViewById(R.id.signupbtn);

I want to display seperate alerts for name and pass fields

Here is my code:
package com.example.userpage;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class UserPage extends Activity {
AlertDialog.Builder builder;
private final static int EMPTY_TEXT_ALERT = 0;
#Override
public Dialog onCreateDialog(int id) {
switch(id) {
case EMPTY_TEXT_ALERT: {
builder = new AlertDialog.Builder(this);
builder.setMessage("Message:Fields Empty!!!")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
return builder.create();
}
}
return null;
}
String tv,tv1;
EditText name,pass;
TextView x,y;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button = (Button) findViewById(R.id.widget44);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent obj = new Intent(UserPage.this,UserPage.class);
startActivity(obj);
}
});
x = (TextView) findViewById(R.id.widget46);
y = (TextView) findViewById(R.id.widget47);
name = (EditText)findViewById(R.id.widget41);
pass = (EditText)findViewById(R.id.widget43);
Button button1 = (Button) findViewById(R.id.widget45);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//tv= name.getText().toString();
//tv1 = pass.getText().toString();
x.setText(tv);
y.setText(tv1);
tv = name.getText().toString();
if(tv.trim().equals("")) {
// text is empty
showDialog(EMPTY_TEXT_ALERT);
}
tv1 = pass.getText().toString();
if (tv1.trim().equals(""))
{
showDialog(EMPTY_TEXT_ALERT);
}
}
});
}
}
What is happening when you try to run it? Which part are you having a problem with?
From what I can tell your code is not going to display any dialogs because you've never called the dialog.show() method. You'd have to do something like this for the way you have it set up:
showDialog(EMPTY_TEXT_ALERT).show();
If you are trying to make it two separate dialogs, one for name, and one for pass then all you'd have to do is make another id variable and add a case: for it inside the switch statement that inside your showDialog(id) method.
You should also really consider using descriptive names for your variables. Your code would be easier to understand if you didn't use names like x,y, and widget#.

Categories

Resources