Android : How to save data (Intent's Data) - java

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

Related

Passing data from second activity to third activity

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

How manage data upload sent PutExtra

I am sending the data between activities, through PutExtra. It's working perfectly.
The problem is when you click the back button, give an error and for the activity.
I've already tried to implement the StarActivityForResult option, and I can not get it to work.
Images below. Code "12345" is used as an example, and is sent to the three screens as PutExtra
Code:
Activity1:
public class MainActivity extends AppCompatActivity {
private Button btnIrAct2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnIrAct2 = (Button) findViewById(R.id.btnIrAct2);
btnIrAct2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent2 = new Intent(MainActivity.this, Activity2.class);
intent2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent2.putExtra("id_empresa", "12345");
startActivity(intent2);
}
});
}
}
Activity 2:
public class Activity2 extends AppCompatActivity {
private Button btnIrAct3;
private String mId_Empresa = null;
static final int SERVICO_DETALHES_REQUEST = 1;
private TextView tvResultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
mId_Empresa = getIntent().getExtras().getString("id_empresa");
tvResultado = (TextView) findViewById(R.id.tvAct2);
tvResultado.setText(mId_Empresa);
btnIrAct3 = (Button) findViewById(R.id.btnIrAct3);
btnIrAct3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent3 = new Intent(Activity2.this, Activity3.class);
intent3.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent3.putExtra("id_empresa", "12345");
startActivityForResult(intent3, SERVICO_DETALHES_REQUEST );
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == SERVICO_DETALHES_REQUEST && resultCode == RESULT_OK) {
String resultBack = data.getStringExtra("id_empresa");
}
}
}
Activity 3:
public class Activity3 extends AppCompatActivity {
private String idEmpresa = null;
private TextView resultado;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
/* Recebe id de outra tela*/
idEmpresa = getIntent().getExtras().getString("id_empresa");
resultado = (TextView) findViewById(R.id.tvAct3);
resultado.setText(idEmpresa);
}
#Override
public void finish()
{
Intent data = new Intent();
data.putExtra("id_empresa", "12345");
setResult(Activity.RESULT_OK, data);
super.finish();
}
}
I need to resolve the conflict. Because on my return I need to send a data like PutExtra, at the same time that this Activity already has a piece of code that already receives a PutExtra.
If I understand the issue correctly, you should to use fragments instead of activities and save all the data in main activity but if you want to continue with this way try onBackPressed() method to choose what to do when the user pressed back button.
Insert this code in Activity 2
if(getIntent().getExtras().getString("id_empresa") != null)
{
mId_Empresa = getIntent().getExtras().getString("id_empresa");
}
Checking the data before setting it to the textview is must. If the string you are putting to textview is null, it will generate an error which will lead to crash.
Hope it helps!

How to modify a string array and save it to use for a listview?

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 !

Adding to an array from a separate class

I have made a listView that is populated with an array. I can add data to this listview by entering in data in a textbox called txtinputs and then click a button called btnAdds this all works fine when I have it all in a single class. However what I want to do is have this on 2 separate screens using 2 separate classes, the txtinputs and the btnAdds in a separate class than the listView. When the data is entered into the txtinputs and the btnAdds is selected it will add that data into the listView on a seperate class. I want the listView in a class called ListDeadlines and my textBox and Button in a class called AddDeadline.
I currently add the data into the listView like this.
public ArrayList<String> arrayList;
public ArrayAdapter<String> adapter;
public EditText txtInput;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_deadlines);
final ListView listView = (ListView)findViewById(R.id.listv);
String[] items= {"HCI","ITM","Presentation"};
arrayList=new ArrayList<>(Arrays.asList(items));
adapter=new ArrayAdapter<String>(this,R.layout.list_item,R.id.txtitem,arrayList);
listView.setAdapter(adapter);
txtInput=(EditText)findViewById(R.id.txtinputs);
Button btAdd=(Button)findViewById(R.id.btnAdds);
btAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String newItem=txtInput.getText().toString();
arrayList.add(newItem);
adapter.notifyDataSetChanged();;
}
});
}
I have tried to do it like this in my AddDeadline class like this however I get a runtime on the button click
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_deadline);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ListDeadlines lst= new ListDeadlines();
lst.txtInput=(EditText)findViewById(R.id.txtinput);
Button btAdd=(Button)findViewById(R.id.btnAdd);
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newItem = lst.txtInput.getText().toString();
lst.arrayList.add(newItem);
lst.adapter.notifyDataSetChanged();
}
});
}
I want to achieve something like this
In your ListDeadLinesActivity when a user hit the "+" button you want to start AddDeadlineActivity for a result.
You can put this code inside the onClick of that "+" button.
Intent intent = new Intent(this, AddDeadlineActivity.class);
startActivityForResult(intent, ADD_DEADLINE_REQUEST);
ADD_DEADLINE_REQUEST is the request code, you can declare a static int.
#Override
protected void onCreate(Bundle savedInstanceState) {
// ...
btAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent returnIntent = getIntent();
returnIntent.putExtra("result", yourEditText.getText().toString());
setResult(RESULT_OK,returnIntent);
finish();
}
});
}
In your ListDeadLinesActivity override onActivityResult method,
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == ADD_DEADLINE_REQUEST){
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("result");
arrayList.add(item);
adapter.notifyDataSetChanged();
}
}
}
Getting a Result from an Activity

Execute code after getting back from an Intent

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

Categories

Resources