how to save EditText's value after performing an other activity - java

i have my first activity with two EditText fields with hint's as first name and last name, when ever i go to my second activity and return to my first activity by a widget button the EditText fields in my first activity gets reset.
SIMPLY i want my EditText fields to remain same in my first activity as i re-visit my first activity from my second activity.
MY MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onButton1Click(View v)
{
Intent intent = new Intent (this,MainActivity2.class);
startActivity(intent);
}
}
My MainActivity2.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
}
SOLUTION - i changed my second activity to this. just added reference to my Button and applied an onClickListener with onBackPressed(); code.
setContentView(R.layout.activity_main2);
Button button = (Button)findViewById(R.id.button3); //gave reference of button in second activity
button.setOnClickListener(new View.OnClickListener() { //and applied an onClickListener with code onBackpressed();
public void onClick(View v) {
onBackPressed();
// Code here executes on main thread after user presses button
}
});
}
Really Really thnx to #Narendra Sorathiya for his guidance.

Open secondActivity like below,
Intent i = new Intent(A.this,B.class);
startActivity(i);
finish();
to
Intent i = new Intent(A.this,B.class);
startActivityForResult(i,1);
do not open 1st Activity from 2nd Activity, just need to back press.

try this
declare all variavle at top of activity
public static final String MyPREFERENCES = "MyPrefs" ;
public static final String FNAME = "fname";
public static final String LNAME = "lname";
SharedPreferences sharedpreferences;
write this code when you move to your next activity
sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
// store login data in sharedpreferences
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(FNAME, edittext.getText());
editor.putString(LNAME, edittext2.getText());
editor.commit(); //save data in sharedpreferences
write this code in your oncreate method after you bind your controls
and get data from sharedprefrence like this
String fname= prefs.getString(FNAME, "");
String fname= prefs.getString(LNAME, "");
than set it to your editext like this
editext.setText(fname);
editext2.setText(lname);
let me know in case of any query

Related

Displaying "Happy birthday null" in the second activity of my app

Main Activity
`public class MainActivity extends AppCompatActivity {
private Object Context;
public static final String MSG="com.mp.exampleapp.ORDER";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void createBirthdayCard(View view) {
EditText text = (EditText)findViewById(R.id.nameInput);
String str = text.getText().toString();
Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
getIntent().putExtra(MSG,str);
startActivity(new Intent(this,birthdaygreeting.class)) ;
ImageView image=(ImageView) findViewById(R.id.cake);
image.setImageResource(R.drawable.wish);
}
`Second activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_birthdaygreeting);
Intent intent = getIntent();
String msg = "HAPPY BIRTHDAY "+intent.getStringExtra(MainActivity.MSG);
// receive the value by getStringExtra() method
// and key must be same which is send by first activity
TextView textView= (TextView)findViewById(R.id.textView2);
textView.setText(msg);
}
After running this program - after clicking the button- the message that's getting displayed is "HAPPY BIRTHDAY null". I don't know what's going wrong.
What is wrong?
The place where you are passing the put extra, is in getIntent(). This means that you are giving an intent extra to the previous activity.In this case, when you go back, and then get that extra, you will get it.But not on the next activity. Now you get null because that extra does not exist for that activity. So, it comes null.
How to solve?
Instead of using this
public void createBirthdayCard(View view) {
EditText text = (EditText)findViewById(R.id.nameInput);
String str = text.getText().toString();
Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
getIntent().putExtra(MSG,str);
startActivity(new Intent(this,birthdaygreeting.class)) ;
ImageView image=(ImageView) findViewById(R.id.cake);
image.setImageResource(R.drawable.wish);
}
use this
public void createBirthdayCard(View view) {
EditText text = (EditText)findViewById(R.id.nameInput);
String str = text.getText().toString();
Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
startActivity(new Intent(this,birthdaygreeting.class).putExtra(MSG,str)) ;
ImageView image=(ImageView) findViewById(R.id.cake);
image.setImageResource(R.drawable.wish);
}
How do I know it will help me?
It will help you because here in the new intent which you are giving, there the extra is being given. So, that value is being sent.
Create an intent then add your data in it like the code below.
public void createBirthdayCard(View view) {
EditText text = (EditText)findViewById(R.id.nameInput);
String str = text.getText().toString();
Toast.makeText(this, "Button was clicked "+str,Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,birthdaygreeting.class);
intent.putExtra(MSG,str);
startActivity(intent) ;
ImageView image=(ImageView) findViewById(R.id.cake);
image.setImageResource(R.drawable.wish);
}

How to save Button Text with SharedPreferances set by EditText

I set the Button Text trough editText and a long Button Click. Afterwards the editText is set to an emptyString again. How do i save the Button name in SharedPreferances (as a String i guess) and read it when i restart the app?
package com.example.myapplication;
import ...
public class MainActivity<button1> extends AppCompatActivity {
Button button
EditText editText1
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button3);
button.setOnClickListener(v -> opensecondone());
button.setOnLongClickListener(v -> naming());
editText1 = (EditText) findViewById(R.id.tv_textView);
}
public boolean naming() {
button = this.findViewById(R.id.button3);
button.setText(editText1.getText().toString());
editText1.setText(" ");
return true;
}
public void opensecondone() {
Intent intent = new Intent(this, firmaeins.class);
startActivity(intent);
}
}
first you store your name in naming function
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("yourMessageKey", message);
editor.commit();
then you get the value inside your oncreate of activity :
SharedPreferences sharedPref = getPreferences(Context.MODE_PRIVATE);
String message = sharedPref.getString("yourMessageKey", "");

Sending data to Listview of another activity

After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView. This is my code:
MainActivity:
public class MainActivity extends AppCompatActivity {
Button button;
ListView listView;
String name;
private static final int REQUEST_CODE = 1;
ArrayAdapter<String> adapter;
ArrayList<String> nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button2);
listView = findViewById(R.id.CarList);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(MainActivity.this, SecondActivity.class);
startActivityForResult(i, REQUEST_CODE);
}
});
nameList = new ArrayList<String>();
nameList.addAll(Arrays.asList(name));
adapter = new ArrayAdapter<String>(this, R.layout.element, nameList);
listView.setAdapter(adapter);
}
protected void onActivityResult(int requestCode, int resultCode, Intent i){
if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) {
name = i.getStringExtra("name");
}
}
}
And this is my SecondActivity:
public class SecondActivity extends AppCompatActivity {
EditText editText;
Button button2;
String name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
editText = findViewById(R.id.editText);
button2 = findViewById(R.id.button);
}
public void finish() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
super.finish();
}
}
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
After pressing the button I would like to go to the second activity, enter the data in the second activity and then return to the main activity, but having data in ListView.
What could I change to make the application work? Because now I only get the message that: app has stopped, but I don't receive information about any error.
This is simply because you've incorrectly thinking that Activity.finish() is always called whenever you close the activity. But it never be called by the Android. Take a look for this Lifecyle picture from Activity-lifecycle concepts:
you can see that only onStop() then onDestroy() is called when activity is closed.
You need to call the finish() method manually to send your intent. Or, the better way, create a method that only build and set the intent for the result. Something like this:
private void prepareResult(String name) {
Intent i = new Intent();
i.putExtra("name", name);
setResult(RESULT_OK, i);
}
then call it whenever you want to close your activity:
String name = editText.getText().toString();
prepareResult(name);
finish();
Or you can override the onBackPressed() to also handing the back pressed, like the following:
#Override
public void onBackPressed() {
Intent i = new Intent();
name = editText.getText().toString();
i.putExtra("name", name);
setResult(RESULT_OK, i);
// The default implementation simply finishes the current activity
// see the documentation.
super.onBackPressed();
}

Pressing the back button goes back to first launched activity

I have an activity which starts when my app is first launched(Only once).The activity lets the users select the topics.Then when they press done, I finish() the activity.This leads the user to the MainActivity.But when the user press the back button it goes back to the activity which was first launched(the activity which I closed using finish()).But what i want is that the app should close when the user presses the back button from the MainActivity(always).I overrided onBackPressed in both the classes.
My onBackPressed method in both the classes looks like this:
#Override
public void onBackPressed() {
finish();
}
MainActivity(Relevant part of code):
public class MainActivity extends AppCompatActivity
{
TopicAdapter adapter;
private AdView mAdView ;
//-------GLOBAL VARIABLES-------------------
AdRequest adRequest;
ArrayList<Sections> gameList = new ArrayList<>();
String json;
//-------------------------------------------
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences sharedPreferences =
getSharedPreferences("ShaPreferences", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
boolean firstTime=sharedPreferences.getBoolean("first", true);
//Launch the topics selection activity for the first time
if(firstTime)
{
editor.putBoolean("first",false);
editor.commit();
Intent intent = new Intent(MainActivity.this, channels_activity.class);
intent.putExtra("isFirst",true);
startActivity(intent);
}
}
#Override
public void onBackPressed()
{
finish();
}
}
You just need to call finish()
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
And Set android:noHistory="true" on the activity in your manifest
See here

Reload SharedPreferences

I'm quite new to Android Prorgramming and have a problem understandig SharedPreferences.
I have a Main Activity and a Settings Activity.
I want to be able to change a SharedPreference (here called firstWaitTime) in the Settings Activity and work with it in the Main Activity.
I can Set the new value in the settings, but in the Main Activity i only see the new value when i close and reopen the app.
I Think i would need a OnPrefrenceChanged Listender but i have no idea how to implement it...
The Main one looks like this:
public class MainActivity extends ActionBarActivity {
//Radio Button
private int stufe;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences settings = this.getSharedPreferences("settings", Context.MODE_PRIVATE);
int firstWaitTime = settings.getInt("firstWaitTime", 12);
int secondWaitTime = settings.getInt("secondWaitTime", 8);
int thirdWaitTime = settings.getInt("thirdWaitTime", 6);
//TEST
final TextView test = (TextView) findViewById(R.id.test);
test.setText("" + firstWaitTime);
}
The Settings Activity looks like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
final SharedPreferences settings = this.getSharedPreferences("settings", MODE_PRIVATE);
//BUTTON
final EditText edit1 = (EditText) findViewById(R.id.edit1);
Button save=(Button) findViewById(R.id.savebtn);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//prefs = getSharedPreferences(prefName, MODE_PRIVATE);
//SharedPreferences.Editor editor = prefs.edit();
SharedPreferences.Editor editor = settings.edit();
//---save the values in the EditText view to preferences---
editor.putInt("firstWaitTime", Integer.parseInt(edit1.getText().toString()));
//---saves the values---
editor.commit();
Toast.makeText(getBaseContext(), "Saved", Toast.LENGTH_SHORT).show();
}
});
}
What is the best way to achieve this?
onCreate() will not be called as Android hasn't killed the Activity. Try putting your code in onResume() instead. For more info read up on the Android Activity lifecycle.

Categories