In this program I have three activities Main, Second and Third. When the app opens there is a blank textview and button. Selecting that button will bring you to the second activity where the user can enter a name, phone number, and email address. Once those forms are filled out the user will hit a button to store that information and bring them back to the main activity. When brought back to the main activity the user will see that the name they entered is displayed in the once blank textview. They may then select that textview which will bring them to the third activity displaying the name, phone number and email address they entered in the second activity.
I have everything working expect passing the data from the second activity to the third. I have done some research and I see a lot can be done with bundles and shared prefs. I am not too familiar with them, as this is very new to me. I did try implementing them, but have not had any luck. Anyways the code is below and any help, feedback or guidance would be highly appreciated. Thank you in advance!
Main Activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void onClick(View view){
startActivityForResult(new Intent(getApplicationContext(),SecondActivity.class),999);
}
public void onClickText(View v)
{
startActivityForResult(new Intent(getApplicationContext(),ThirdActivity.class),999);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 999 && resultCode == RESULT_OK)
{ TextView contactView = (TextView) findViewById(R.id.contactDisplay);
contactView.setText(data.getStringExtra("Name"));
}
}}
Second Activity:
public class SecondActivity extends AppCompatActivity {
public String textName;
public String emailAddress;
public int phoneNumber;
private TextView textNameView2;
EditText textPersonName;
EditText number;
EditText textEmailAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
public void onClickTwo(View view)
{
textPersonName = (EditText) findViewById(R.id.name);
number = (EditText) findViewById(R.id.number);
textEmailAddress = (EditText) findViewById(R.id.email);
textName = textPersonName.getText().toString();
emailAddress = textEmailAddress.getText().toString();
phoneNumber = Integer.valueOf(number.getText().toString());
showToast(textName +"added");
Intent backMain = new Intent(this, MainActivity.class);
// Intent backMain = new Intent();
backMain.putExtra("Name",textName);
// backMain.putExtra("Email", emailAddress);
// backMain.putExtra("Phone", phoneNumber);
setResult(RESULT_OK, backMain);
Intent thirdMain = new Intent(this, ThirdActivity.class);
thirdMain.putExtra("Name",textName);
thirdMain.putExtra("Email",emailAddress);
thirdMain.putExtra("Phone",phoneNumber);
setResult(RESULT_OK,thirdMain);
finish();
}
private void showToast(String text)
{
Toast.makeText(this,text, Toast.LENGTH_LONG).show();
}}
Third Activity:
public class ThirdActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 999 && resultCode == RESULT_OK) {
TextView contact = (TextView) findViewById(R.id.contactNameView);
contact.setText(data.getStringExtra("Name"));
TextView phone = (TextView) findViewById(R.id.phoneView);
phone.setText(data.getStringExtra("Phone"));
TextView email = (TextView) findViewById(R.id.emailView);
email.setText(data.getStringExtra("Email"));
}
}
}
Follow this thread on passing data between activities using intent:
How do I pass data between Activities in Android application?
However, if you want to pass data using shared preference, Use this code snippet:
public class SharedPreferenceManager {
private static final String PREFS_NAME = Config.SHARED_PREF_NAME;
/**
* #param context
* #param key
* #param value
* #return
*/
public static boolean saveToPreference(Context context, String key, String value) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString(key, value);
return editor.commit();
}
/**
* #param context
* #param key
* #return
*/
public static String loadFromPreference(Context context, String key) {
SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
return settings.getString(key, "");
}
}
To save to preference you pass in the application context, The key and the String you want to save. To load the saved string from SharedPreference you pass in the Context and the Key in the activity lets say i wan to save a string email to my shared preference in one activity and load it in another, this is how i would do it:
//Save to shared Preference in Activity A
SharedPreferenceManager.saveToPreference(this, "email", emailAddress.getText().toString());
//Load from shared preference in activity b
String emailAddress = SharedPreferenceManager.loadFromPreference(this, "email");
Related
I want to make a basic app in which I offer the user to add a trackers of various things like water etc. and then he can store how many glasses he has drank so far. However I want it to have saved the information even after the app closes. Please provide a solution.
This is what I've tried so far:-
public class MainActivity extends AppCompatActivity {
Button btnAddTracker;
//public static final String MY_PREFS_NAME = "MyCounter";
ImageView ivWater;
TextView tvWaterCount;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
btnAddTracker=findViewById(R.id.btnAddTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterCount=findViewById(R.id.tvWaterCount);
btnAddTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,TrackerListActivity.class);
startActivity(intent);
}
});
editor.putInt("waterCount", 8);
editor.apply();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(pref.getBoolean("WaterStatus",false)){
ivWater.setVisibility(View.VISIBLE);
tvWaterCount.setVisibility(View.VISIBLE);
tvWaterCount.setText(pref.getInt("waterCount",0));
}
}
}
}
public class TrackerListActivity extends AppCompatActivity {
Button btnAddWaterTracker;
ImageView ivReturn,ivWater;
TextView tvWaterStatus;
boolean WaterStatus;
SharedPreferences pref;
SharedPreferences.Editor editor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracker_list);
ivReturn=findViewById(R.id.ivReturn);
btnAddWaterTracker=findViewById(R.id.btnAddWaterTracker);
ivWater=findViewById(R.id.ivWater);
tvWaterStatus=findViewById(R.id.tvWaterStatus);
pref = PreferenceManager.getDefaultSharedPreferences(this);
editor = pref.edit();
WaterStatus=pref.getBoolean("waterStatus",false);
ivReturn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2=new Intent();
intent2.putExtra("waterStatus",WaterStatus);
setResult(RESULT_OK,intent2);
if(btnAddWaterTracker.getVisibility()==View.GONE) {
editor.putBoolean("waterStatus",true);
editor.apply();
}
TrackerListActivity.this.finish();
//Intent intent1=new Intent(TrackerListActivity.this,MainActivity.class);
//startActivity(intent1);
}
});
btnAddWaterTracker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
WaterStatus=true;
btnAddWaterTracker.setVisibility(View.GONE);
tvWaterStatus.setVisibility(View.VISIBLE);
//editor.putBoolean("waterStatus",true);
//editor.apply();
}
});
}
}
There are many ways of saving informations locally, you could save it on a file using the Json or XML format, you could also use SQLite which are supported by all recent smartphones.
Unfortunately you won't get anyone to code for you on this website, check this link
public class MainActivity extends AppCompatActivity {
private Button addcar;
String[]foods={"carone","cartwo","carthree"};
#Override
protected void onCreate(Bundle savedInstanceState) {
if(savedInstanceState!=null){ <----- Here is where I thought I could get the updated array to be added to the listview.
String [] foods = savedInstanceState.getStringArray("foods");
ListAdapter myadapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,foods);
ListView mylistview = (ListView)findViewById(R.id.list);
mylistview.setAdapter(myadapter);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addcar = (Button) findViewById(R.id.button);
addcar.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent myintent = new Intent("com.example.husse.profilesalgortihm.Main2Activity");
startActivity(myintent);
}
}
);
ListAdapter myadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,foods);
ListView mylistview = (ListView)findViewById(R.id.list);
mylistview.setAdapter(myadapter);
mylistview.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (id == 0) {
Toast.makeText(MainActivity.this, foods[0], Toast.LENGTH_SHORT).show();
}
}
}
);
}
}
My Second activity
public class Main2Activity extends MainActivity {
public int number = 0;
public EditText Model;
public EditText Body;
public EditText color;
public String M;
public String B;
public String C;
private final String tag = "Main2activity";
private Button add;
Car_information[] cars = new Car_information[10];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Model = (EditText)findViewById(R.id.editText);
Body = (EditText)findViewById(R.id.editText2);
color = (EditText)findViewById(R.id.editText3);
add = (Button)findViewById(R.id.button2);
M = Model.getText().toString();
B = Body.getText().toString();
C = color.getText().toString();
// may run into issues with the final
add.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) { <--- Here is where I tried to save the information about the car but for the listview purpose I only wanted the name to be added to the Listview in the previous activity.
cars[number] = new Car_information();
cars[number].Model = M;
cars[number].Body = B;
cars[number].Color = C;
foods[number]= M;<----- Updating the array with the name the of the vehicle the user put in
number ++;
Intent intent = new
Intent(Main2Activity.this,MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
);
}
#Override
public void onSaveInstanceState(Bundle outState) { <----- where I tried to save the new updated array to be used in the listview, so the user could see the new listview when the user goes back to the firstactivity.
super.onSaveInstanceState(outState);
outState.putStringArray("foods",foods);
}
What I am trying to do is when the user goes to the second activity he/she will enter in the information about his/her vehicle, but when they click the add button it will take them back to the previous activity and it will save the name of the car that they entered, and display it on the listview. But the list isn't being updated when they go back to the firstactivity.
You can use startActivityForResult() function to implement your task.
Example: You are in Activity1 and want to get data from Activity2.
In Activity1, call intent to start Activity2 with specific request
static final int PICK_CONTACT_REQUEST = 1; // The request code
...
private void pickContact() {
Intent pickContactIntent = new Intent(this, Activity2.class);
pickContactIntent.putExtra(...) <-- put some data to send to Activity2
startActivityForResult(pickContactIntent, PICK_CONTACT_REQUEST);
}
then override onActivityResult like
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == PICK_CONTACT_REQUEST) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// get data sent from Activity2 via data parameter
}
}
}
In Activity2, when you're done with process, send data back to Activity1 by flow
setResult (int resultCode, Intent data) > finish()
this data will send to onActivityResult above
Hope it help !
There is an example code that passed data by using Intent below the three Activity codes.
Activity A
public class A extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_A);
}
public void onButton1Clicked(View v) {
Intent intent = new Intent(getApplicationContext(), B.class);
startActivity(intent);
}
Activity B
public class B extends AppCompatActivity {
TextView tv;
ImageButton ib;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_B);
tv = (TextView) findViewById(R.id.textView);
ib = (ImageButton) findViewById(R.id.imageButton);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(B.this, C.class);
startActivityForResult(intent, 2);
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
if (data != null) {
String message = data.getStringExtra("DATA");
tv.setText(message);
}
}
}
public void onButton2Clicked(View v) {
Intent intent = new Intent(getApplicationContext(), C.class);
startActivity(intent);
}
Activity C
public class C extends AppCompatActivity {
EditText et;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_C);
et = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = et.getText().toString();
Intent intent = new Intent();
intent.putExtra("DATA", data);
setResult(2, intent);
finish();
}
});
}
The order of activity is A - B - C.
In A, there is a Button that can move to B, and in B there are a Button(can move to C) and TextView. In C, a Button(can move to B again) and EditText.
For example, Using 'startActivityForResult' I have output as TextView(B) that received a text which was input by EditText in C. But after moving B into A(Back), an insertion of TextView gets disappeared when entering to B again. In addition, even if entering into C, there is no insertion of EditText, too.
I would really need and know 'Save code' into variable by inputting as EditText when pressing a button in C.
In this case, HOW can I add ‘Code’ the remain the insertion value either the insertion value remains by quitting the application or moves to Activity that received DATA like A?
Thanks for your cooperation and concern.
To maintain the state of your activity, you have to override onSaveInstanceState method. Store the value of your TextViews and EditText in this method. For example, let's talk about Activity B. In activity B you would do something like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
String text = tv.getText().toString();
savedInstanceState.putString("mytext", text);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
Then in your onCreate do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState); // Always call the superclass first
// Set Content View and initialize the views
// Check whether we're recreating a previously destroyed instance
if (savedInstanceState != null) {
// Restore value of members from saved state
String mytext = savedInstanceState.getString("mytext");
tv.setText(mytext);
} else {
// Probably initialize members with default values for a new instance
}
...
}
You can read more about Recreating an Activity.
You can store intent's data using following way..
Your example seems confusing on how you passing the data and you have two methods in ActivityB handing the Intent. (onButtonClicked and StartActivityForResult())
Here's simple example
Define unique string to save your Intent's data in
- ActivityA
public final static String EXTRA_MESSAGE ="myMessage";
below method will open the ShowMessage Activity showing the message you type in EditText view.
public void sendMessage(){
Intent intent = new Intent(this, ShowMessage.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
Here's how you can retrieve that data in ShowMessage activity.
-ActivityB.
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
//EXTRA_MESSAGE is a unique string that holds the message typed in TextView
TextView receiveMessage = findViewById(R.id.sentMessage);
receiveMessage.setText(message); //would set the message typed in ActivityA
Now when you get back and if you still want your EditText to have the previous string entered, you can do as the answer given by Eric B.
//Saving the value
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
String myMessage = editText.getText().toString();
outState.putString("myMessage", myMessage);
}
in onCreate(), you can retrieve as follows
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null){
String myMessage = savedInstanceState.getString("myMessage","");
editText.setText(myMessage);
}
Also one thing recommended is resultCode == RESULT_OK for validation of intent.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2 && resultCode == RESULT_OK) {
if (data != null) {
String message = data.getStringExtra("DATA");
tv.setText(message);
}
}
This is the write activity. In here I want to write a text and after clicking a button I want this text to appear in a new activity called read activity.
public class Write extends Activity implements OnClickListener
{
EditText text; TextView retrive1;
public static String filename="Mysharedstring" ;
SharedPreferences someData;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.write);
setupVariables();
someData = getSharedPreferences(filename, 0);
}
private void setupVariables()
{
Button sav= (Button) findViewById(R.id.save);
Button ret= (Button) findViewById(R.id.retrive);
text= (EditText) findViewById(R.id.txtText);
retrive1= (TextView) findViewById(R.id.textview);
ret.setOnClickListener(this);
sav.setOnClickListener(this);
}
public void onClick(View v)
{
String stringdata= text.getText().toString();
SharedPreferences.Editor editor = someData.edit();
editor.putString("sharedString", stringdata);
editor.commit();
}
}
I don't know what to write in the read activity.
public void onClick(View v)
{
//???
}
The most simple way that I can think of is this first Activity
Intent intent= new Intent(this, theOtherActivity.class);
intent.putExtra(Key, "Value");
startActivity(intent);
And on theOtherActivity
String receivedData=getIntent().getExtras().getKey(Key);
public void onClick(View v)
{
// get the shared string from the SharedPreference
SharedPreferences sp = getSharedPreferences("Mysharedstring",0);
String s = sp.getString("sharedString","Nothing found.");
// display the shared string
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
Sources for SharedPreferences:
How to save app settings?
How to keep information about an app in Android?
Shared Preferences | Android Developers
I have a TextView in my main activity.
pressing a button i open another activity and get to the options where i can rename my
TextView
btnSet.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, Options.class);
startActivity(intent);
}
});
In my Options activity i rename my TextView like this
public class Options extends MainActivity{
public static Boolean isRenamed;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
String lblName = ("Counter 1");
Button btnOk = (Button) findViewById(R.id.btn_ok);
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent backToMain = new Intent(Options.this, MainActivity.class);
EditText labelName = (EditText) findViewById(R.id.set_name);
String lblName = labelName.getText().toString();
backToMain.putExtra(LABEL_NAME, lblName);
isRenamed = true;
startActivity(backToMain);
finish();
}
});
}
}
I am using the boolean isRenamed and i set it to true after clicking ok
And in my main activity i've set this
if (Options.isRenamed == true) {
// Get the message from the intent
Intent backToMain = getIntent();
String lblName = backToMain.getStringExtra(Options.LABEL_NAME);
// Edit the text view
TextView label = (TextView) findViewById(R.id.label1);
label.setText(lblName);
}
For now it's force closing, but is there some more elegant way to see if i've renamed the file and then execute that piece of code to set it?
Context.startActivityForResult();
do all your renaming and other stuff there. return a simple integer to know what happened. That way when you call finish() in your second activity it will return to your first without creating a new instance.
Use startActivityForResult() instead of startActivity(). In the Options Activity:
public static final int RENAMED = 100;
btnOk.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent backToMain = new Intent(Options.this, MainActivity.class);
EditText labelName = (EditText) findViewById(R.id.set_name);
String lblName = labelName.getText().toString();
backToMain.putExtra(LABEL_NAME, lblName);
isRenamed = true;
setResult(RENAMED);
finish();
}
});
In MainActiviy, override onActivityResult() and
when it is fired check if resultCode paramter is equals to RENAMED .
for this senario you need to use
startActivityForResult(intent, requestCode)
instead of startActivity(intent)
in your Options Activity you ca setResult(resultCode, data) and call finish.
and in MainActivity you can use data in
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
you can use
startActivityForResult(intent, intentsData.REQUEST_CODE);
and then change your TextView when activity is resumed
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
/**
* change your TextView
*/
super.onActivityResult(requestCode, resultCode, data);
}