Save Button | note application - java

I'm having trouble adding a Button to save text input in my editorActivity class, which is an Activity I designated to view, edit, and save a note item.
The class uses the back button (hardware) and app launcher icon to save the key/value pair to a SharedPreferences object. I want to add a Button that will do the same.
I get an error in the console stating:
res\layout\activity_note_editor.xml:18: error: Error: No resource found that matches the given name (at 'text' with value '#string/Save').
I'm not sure what this implies. And would appreciate some guidance as to where I should to fix this error.
This is what I have so far:
private NoteItem note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_editor); // Load custom note edit layout
getSupportActionBar().setDisplayHomeAsUpEnabled(true); // Launcher icon becomes an options button = home
Intent intent = this.getIntent(); // Reference to intent object in first activity
note = new NoteItem();
note.setKey(intent.getStringExtra("key")); // retrieve key and saved in note object
note.setText(intent.getStringExtra("text")); // Retrieve text and save in note object
EditText et = (EditText) findViewById(R.id.noteText);
et.setText(note.getText());
et.setSelection(note.getText().length());
}
private void saveAndFinish() {
EditText et = (EditText) findViewById(R.id.noteText);
String noteText = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("key", note.getKey());
intent.putExtra("text", noteText);
setResult(RESULT_OK, intent);
finish();
}
#Override // launcher icon sends data back to main activity
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
saveAndFinish();
}
return false;
}
#Override // device back button sends data back to main activity
public void onBackPressed() {
saveAndFinish();
}
public void addListenerOnButton(){
Button button = (Button) findViewById(R.id.save);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
saveAndFinish();
}
});
}
}

I'm not sure what this implies.
It implies that you don't have a resource in your strings.xml with the identifier of "Save"
When you use #String, or #anyAndroidResource for that matter, it looks in the corresponding file. So #drawable would look inside the drawables folder for whatever identifier you used.
In values/strings.xml you should have something like
<string name="Save">Save</string>
Resources Docs
Resources Overview Docs

Related

Saving Activity State when switching activities

I'm currently trying to create an activity, which should be creating a new TextView on my main activity, everytime a Button is clicked on the first activity. However, instead of creating a new TextView everytime the button is clicked, it just changes the values of the first created TextView, so that there is always only one TextView. Is there a way to make it so that my first activity will not only create one single textview?
Here's the code from my "NewSubjectActivity":
**public class NewSubjectActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_subject);
Button SaveBtn = findViewById(R.id.SaveBtn);
nsaSaveBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Click();
}
});
}
protected void Click(){
Intent intent = new Intent(NewSubjectActivity.this, MainActivity.class);
Boolean createnewTextView = true;
intent.putExtra("createnewTextView",createnewTextView);
startActivity(intent);
}
}
And here's the (relevant) code from my MainActivity:
protected void ReceiveValue (){
//getting Extras
Intent nsareceivedvalues = getIntent();
boolean createTextView = false;
createTextView = nsareceivedvalues.getExtras().getBoolean("createnewTextView");
//declaring fixed Views
final LinearLayout mainLinearLayout = (LinearLayout)findViewById(R.id.mainLinearLayout);
//Params for TextView
RelativeLayout.LayoutParams Params = new RelativeLayout.LayoutParams(1000, 200);
Params.setMargins(0, 10, 0, 10);
while(createTextView) {
//creating a TextView
TextView newsubject = new TextView(MainActivity.this);
//applying values to the TextView
newsubject.setLayoutParams(Params);
newsubject.setGravity(CENTER);
newsubject.setBackgroundColor(Color.GRAY);
mainLinearLayout.addView(newsubject);
createTextView = false;
}
}
As I said, this only create one text view, everytime I press the button on my "NewSubjectActivity" I think this might be, because the previous text view is not saved and the MainActivity is reset everytime I switch between the activities.
Every help and advise is much appreciated <3
Maybe when you are going back to your main activity you should call to onBackPressed() function, so it will reset nothing at all. Here's the example in kotlin
val back_button:Button = findViewById(R.id.button2)
back_button.setOnClickListener { v -> run {
//Change activity
onBackPressed()
} }
in Java should be:
Button back_button = findViewById(R.id.button2);
back_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Change activity
onBackPressed()
}
});
Let's hope it works!

How to save user input from EditText to a variable to be used on a different Activity

I have an edit text in Android Studio which I want a user to enter a name which can then be stored as a variable. I then want to add this variable to a textview in my main activity.
Right now all a have is a blank activity with an edit text and button to save the user input as a variable.
Edit
Ok, I am going to change my approach. In my main activity, I have two text views. If I changed them to edit texts, then how would I save them from the main activity without a save button so that what the user typed would still be there?
Save it in Shared Preferences and then retrieve it from the other activity.
To save a String in shared preferences, you can create a method like the following:
public static void setUsername(Context context, String username) {
SharedPreferences prefs = context.getSharedPreferences("myAppPackage", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("username", username);
editor.commit();
}
To retreive it :
public static String getUsername(Context context) {
SharedPreferences prefs = context.getSharedPreferences("myAppPackage", 0);
return prefs.getString("username", "");
}
Edited:
In the activity which contains the EditText, you can call the method as follows:
setUsername(this,myEditText.getText().toString());
And in the Activitiy that contains the TextView:
myTextView.setText( getUsername(this) );
you ça use edit.getText().toString() tout get the user input.
To launch new activity and pass the string to it use
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("key", theString);
startActivity(intent);
EDIT
To be more easy you should add a button to your layout so when the user press that button you can launch the next activity with the string.
This should go into your activity
public class BlankActivity implements OnClickListener {
private EditText mEditText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//find editText
mEditText = (EditText) findViewById(R.id.your_edit_text_id);
//listen button
findViewById(R.id.your_button_id).setOnClickListener(this);
}
#Override
public void onClick(View v) {
String theString = mEditText.getText().toString();
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("key", theString);
startActivity(intent);
}
}

stopping toast android in other actvity

my problem is this:
I make a toast "welcome" in the Activity Main for the first time that you open the home, and it's ok,but when another page to return to the home via the back button, how can I make the toast "welcome" does not appear anymore?
the code of main activity is:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
MyActivity actvi1;
int cont=0;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnabout=(Button)findViewById(R.id.about);
//click
btnabout.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// definisco l'intenzione di aprire l'Activity "aboutme.java"
Intent aboutmejava= new Intent(MyActivity.this,aboutme.class);
startActivity(aboutmejava);
}
}
);
//toast
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
code of aboutme.java
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.aboutme);
Button btnback=(Button)findViewById(R.id.scritta);
btnback.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
Intent main = new Intent(aboutme.this,MyActivity.class);
startActivity(main);
If you want it to only show the very first time the application runs, put a boolean flag in SharedPreferences and check here. There are tons of examples but here is one
If you want it to show *every time the Activity is first run when the app starts, simply replace your onClick() code with onBackPressed(). This way it won't start a new instance of your MyActivity and since the Toast code is in onCreate() and not onResume(), it won't run when you go back by clicking the back button.
SharedPreferences
This works.
SharedPreferences sp = getPreferences(Context.MODE_PRIVATE);
int show = sp.getInt("firstlaunch", 0);
if(show == 0) {
Toast.makeText(getApplicationContext(), "WELCOME", Toast.LENGTH_LONG).show();
sp.edit().putInt("firstlaunch", 1).apply();
}
Place it in your home activities onCreate method.'
A shared preference is a "setting" of sort. It's a xml file that is loaded which contains all of your settings. When we first run "sp.getInt" you can see that i have a 0 after the "key - fistlaunch". The 0 is specifying what to give our Int SHOW if it can't find any shared preference with that key. Next if the int show is equal to 0 we run our Toast and then change the shared preference value to 1 so next time you run it doesn't show...
boolean b = false;
if(!b) {
Toast toast = Toast.makeText(getApplicationContext(),
"Welcome", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER_HORIZONTAL, 20, 0);
toast.show();
b = true
}
kind of like that?
Are you another instance of MainActivity?
In order to return to your Main activity you should send an Intent with the flag FLAG_ACTIVITY_CLEAR_TOP (or set android:launchMode="singleTop" in launchMode in AndroidManifest.xml)
Intent main = new Intent(aboutme.this,MyActivity.class);
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
By doing so, your main activity will be restored, instead of creating a new instance of MainActivity

How to make a button permanently unclickable

I am making a log-in system on Android. And I want the register Button to be unclickable when it has been clicked. I am using this code:
final Button register = (Button) findViewById(R.id.register);
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
This is working great, but I want the Button to remain unclickable even when the application or phone has been restarted. Does anyone know a way to make the Button unclickable permanently even when the application has been shut down?
As I already said in the comments section something like this may work:
public class MyActivity extends Activity {
private static final String KEY_IS_BUTTON_CLICKABLE = "key_clickable";
#Override
public void onCreate(Bundle savedInstanceState) {
...
final Button register = (Button) findViewById(R.id.register);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
boolean isClickable = sharedPreferences.getBoolean(KEY_IS_BUTTON_CLICKABLE, true);
register.setEnabled(isClickable);
if(isClickable) {
register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
register.setEnabled(false);
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).edit()
.putBoolean(KEY_IS_BUTTON_CLICKABLE, false);
Intent register = new Intent(getApplicationContext(), register.class);
startActivity(register);
}
});
}
}
...
}
In this case you could take a pessimistic approach and disable the button in the layout (by default) with android:clickable="false" and enable it in the condition where registration is required.

How to assign a numerical value to a check RadioButton and pass this onto the next activity (similar to a questionnaire app)

I am new to Android development and I am trying to design a simple questionnaire-type app. Each question has set answers within a RadioGroup. I would like to assign a numerical value to the checked RadioButton so I can then send this to the next activity where eventually it will be used to total the scores and produce a message.
I have been able to create a toast; for testing, to show which RadioButton is checked. But I am having trouble with assigning a value to each RadioButton once checked. I know that I will need to use a IF statement but not sure how. Can anyone help or send me a link to a good tutorial?
Here's some sample code within one of my .java file;
public class Diabetes_Question_1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.diabetes_question_1);
Button btnBack = (Button) findViewById(R.id.btnBack1);
btnBack.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Diabetes_Question_1.this, Diabetes_Question_2.class));
}
});
final RadioGroup radioDQ1Group = (RadioGroup) findViewById(R.id.radioDQ1Group1);
Button btnNext = (Button) findViewById(R.id.btnNext1);
btnNext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(Diabetes_Question_1.this, Diabetes_Question_3.class));
int selectedId = radioDQ1Group.getCheckedRadioButtonId();
RadioButton rb1 = (RadioButton) findViewById(selectedId);
Toast.makeText(Diabetes_Question_1.this, rb1.getText(), Toast.LENGTH_SHORT).show();
}
});
}
};
Every view has a tag- an object that can hold whatever data you want. Use it to hold the integer value- you can do that via setTag() and getTag(). Then when you start the new activity, add it to the extras bundle of the intent you launch. The new activity should then read that value from the incoming intent.

Categories

Resources