Android studio - How to save data selected on previous activity - java

This is a snippet of my code. The Textview acts as buttons and have Onclicklistner on them. When cpu1000 Textview is clicked it leads to the cpu_g1000 class for which the code is shown below.
public class Game_1000 extends AppCompatActivity implements View.OnClickListener{
private TextView cpu1000, mobo1000;
TextView cpu, mobo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game_1000);
cpu1000 = (TextView) findViewById(R.id.proName_G1);
mobo1000 = (TextView) findViewById(R.id.moboName_G1);
cpu1000.setOnClickListener(this);
mobo1000.setOnClickListener(this);
cpu = (TextView) findViewById(R.id.proNameG1000);
cpu.setText(getIntent().getStringExtra("Processor"));
mobo = (TextView) findViewById(R.id.moboNameG1000);
mobo.setText(getIntent().getStringExtra("Motherboard"));
}
#Override
public void onClick(View v) {
if (v == cpu1000) {
opencpu_g1000();
}
else if (v == mobo1000) {
openmobo_g1000();
}
}
public void opencpu_g1000() {
Intent intent = new Intent(this, cpu_g1000.class);
startActivity(intent);
}
public void openmobo_g1000() {
Intent intent = new Intent(this, mobo_g1000.class);
startActivity(intent);
}
In this class, there are radio buttons. The users choose one of the choices and the choice is changed to strings. The strings are sent back to Game_1000 class. The string then gets substituted with "Choose a processor" to show the new choice. The issue I am having is when I choose a motherboard the processor choice is reverted back to "Choose a processor" and the motherboard choice shows. I need both to show at the same time.
public class cpu_g1000 extends AppCompatActivity {
Button button_save;
RadioGroup rG;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cpu_g1000);
button_save = (Button) findViewById(R.id.Save_G1_cpu);
rG = (RadioGroup) findViewById(R.id.cpu_RadioGrp);
tv = (TextView) findViewById(R.id.proNameG1000);
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_cpu = rG.getCheckedRadioButtonId();
RadioButton selectedRadioButton = (RadioButton) findViewById(selected_cpu);
String radioValue = selectedRadioButton.getText().toString();
Intent intent = new Intent(cpu_g1000.this, Game_1000.class);
intent.putExtra("Processor", radioValue);
startActivity(intent);
}
});
}
Processor is chosen:
Motherboard is chosen:
Example of choices:
The previous choice are not recored and when a new choice is made the previous choice reverts back to "Please choose a processor" but I need both of the information to show. In my original code, I have more than just 2 choices but I shortened it to make it easier to read.

Start your second (Selection) activity for result by calling startActivityForResult(...) and then when user completes the interaction set your selected data in an Intent and pass that intent to method with desired result setResult(...) then call finish on second activity.
After finishing the second activity you will receive intent data in onActivityResult(...) method of first activity, extract that data from intent and then show it to user.
More Description
Example

Try using Shared Preference. Here's a good tutorial.

For your scenario what you have to do is save Processor and Motherboard selection result or send data form one Activity to another Activity. As after processor selection you are returning to Game_1000 Activity you can use startActivityForResult. This method send back the result to calling Activity via Intent. Thats means if you call cpu_g1000 Activity from Game_1000 Activity and after selecting Processor you can send back the result to Game_1000 Activity. Game_1000 Activity will get the result in onActivityResult method.
Example:
Start cpu_g1000 Activity with startActivityForResult from Game_1000 Activity.
public void opencpu_g1000() {
Intent intent = new Intent(this, cpu_g1000.class);
startActivityForResult(intent, PROCESSOR_SELECTION_CODE);
}
In cpu_g1000 Activity set the result to intent and send back to Game_1000 Activity
button_save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int selected_cpu = rG.getCheckedRadioButtonId();
RadioButton selectedRadioButton = (RadioButton) findViewById(selected_cpu);
String radioValue = selectedRadioButton.getText().toString();
Intent resultIntent = new Intent();
// TODO Add data to send back
resultIntent.putExtra("ProcessorSelection", radioValue);
setResult(Activity.RESULT_OK, resultIntent);
// finishing this activity
finish();
}
});
In Game_1000 Activity get the value sent form cpu_g1000 Activity by overriding onActivityResult method.
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode) {
case (PROCESSOR_SELECTION_CODE) : {
if (resultCode == Activity.RESULT_OK) {
// TODO Extract the data returned from the child Activity.
String radioValue = data.getStringExtra("ProcessorSelection");
// save the result value and update UI
}
break;
}
}
}
For mobo_g1000 Activity use same procedure to get the result back in Game_1000 Activity. Start mobo_g1000 Activity with startActivityForResult and get the value in Game_1000 Activity's onActivityResult method. You have to add another case in onActivityResult method for mobo_g1000 Activity.
Check this and this link for better understanding how this work.

Related

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

App Crashes upon receiving data from intent

I have two activities that I would like to send data between. I would like to send two strings from the second activity to the first, where the strings will be manipulated and applied to the code. Here is the intent I have in the second activity to send the strings to the first activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent();
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
}
});
And here is the intent I have in the first acitivity to receive the data:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_messages);
request_code = 1;
FloatingActionButton button = (FloatingActionButton) findViewById(R.id.but);
assert button != null;
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TextMessages.this,Settings.class);
startActivityForResult(intent, request_code);
Intent a = new Intent(TextMessages.this,Settings.class);
startActivityForResult(a, recode);
}
});
Intent pass = getIntent();
String address = pass.getStringExtra("value");
String string2 = pass.getStringExtra("cost");
However, the app always crashes when I start it. So I can not use any of the data. Thanks in advance to any help I may receive.
In the first activity you should get your strings from onActivityResult. You shouldn't use startActivity in second activity.
Checkout this link for more information
https://developer.android.com/training/basics/intents/result.html
In your second activity you should use setResult method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent();
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
setResult(Activity.RESULT_OK,pass);
finish();
}
});
In your first activity you should get Intent data inside the onActivityResult method.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == request_code) {
if(resultCode == Activity.RESULT_OK){
String value=data.getStringExtra("value");
String cost=data.getStringExtra("cost");
//handle value and cost.
}
}
}
I think it's because you missed out to put the target Activity class when you instantiate your intent. It should be like this:
Intent pass = new Intent(TargetActivity.class);
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
Hope it helps.
EDIT: But I agree with Abdullah. Since the first activity started the second activity, use onActivityResult to pass values to the first activity.
My guess is, the app starts into the second code block you posted. There is no value for String address = pass.getStringExtra("value"); or String string2 = pass.getStringExtra("cost"); when you start your app - only when the second activity sends these to the first activity. I would recommend finding a way to determine if its the second activity creating the first activity or creating a method to set these values in the first activity and call it in the second activity. Also, your second activity should be:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
phoneNum = (EditText)findViewById(R.id.phoneNum);
msgCounter = (EditText)findViewById(R.id.msgCount);
apply = (Button)findViewById(R.id.butto);
save = (Button)findViewById(R.id.butt);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent pass = new Intent(SecondActivity.this, FirstActivity.class);
pass.putExtra("value", phoneNum.getText().toString());
pass.putExtra("cost",msgCounter.getText().toString());
startActivity(pass);
}
});

Get EditTexts from referenced Activity

in my application I have an Activity A which has a reference to an Activity B. Now I am trying to get all EditTexts from Activity B in Activity A. In Pseudocode the code looks like:
public class A extends Activity{
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BActivity B = BActivity.safeGetInstance();
/**
* Get EditTexts of Activity B here
*/
}
}
I have no further information about Activity B since it does not belong to my Application. The only thing I know is that BActivity extends Activity. Is it possible to get the Edittexts of B?
Thanks in Advance
Tobi
There is no reason you should try this.
If the goal is to get the values inside of those EditTexts, you should store them somewhere in a database/preferences or maybe return them in onActivityResult().
Understand that Android gives no guarantees that the memory of other Activities is still valid. Activities get destroyed (and recreated) left and right.
If the goal is to communicate between applications (as you indicate), then this BActivity should make these values available, for example through a content provider.
Forget about solving this at GUI level.
Assume, you are in Activity A, and calling Activity B,
public void startNextActivity() {
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, SOME_UNIQUE_INTEGER_REQUEST_CODE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
boolean showEditText = data.getBooleanExtra("show", false);
if (showEditText) {
// handle your edit text visibility.
}
}
In Activity B, somewhere when user leaves, (ex: onBackPressed)
Intent intent=new Intent();
intent.putExtra("show", trueOrFalse);
setResult(SAME_UNIQUE_INTEGER_REQUEST_CODE_YOU_SPECIFIED,intent);
finish();//finishing activity
Now, when finished, onActivityResult will be fired in Activity A. Handle your UI state there.
When you are using activity A (that is launcher), activity B does not exist yet. If you want to get data from activity B, use startActivityForResult method. It gives you back data after you destroyed B. So you cant get something from A when B hasn't created.
Activity B
public class ActivityB extends Activity implements View.OnClickListener {
TextView yourView;
Button startA;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
yourView = (TextView) findViewById(R.id.tvName);
startA = (Button) findViewById(R.id.start_button);
startA.setOnClickListener(this);
}
// start A on click
#Override
public void onClick(View v) {
Intent intent = new Intent(this, ActivityA.class);
startActivityForResult(intent, 1);
}
/**
*
* #param requestCode
* #param resultCode
* #param data - resultData from A
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
int dataFromA = data.getIntExtra("result",1);
if(dataFromA == 0){
yourView.setFocusable(false);
}else{
yourView.setFocusable(true);
}
}
}
Activity A
public class ActivityA extends Activity implements View.OnClickListener {
EditText etName;
Button btnOK;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etName = (EditText) findViewById(R.id.etName);
btnOK = (Button) findViewById(R.id.btnOK);
btnOK.setOnClickListener(this);
}
//finished activity A and return to B with result
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("result", 0);
setResult(RESULT_OK, intent);
finish();
}
}

Android: onActivityResult() local data is missing

I have two activities(Activity1 and Activity2). Activity1 starts Activity2 for get some data. Whenever I back to Activity1 onCreate method is runing before the onActivityResult().And all data is gone. Why onCreate method is runing second time and data is missing?
You can check example code at below to see sample scenario. In this case a value of var1 should be 5 in onActivityResult method but its 0.
public class MainActivity1 extends ActionBarActivity
{
TextView textView1;
Button button1;
int var1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity1);
textView1 = (TextView) findViewById(R.id.textView1);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
var1 = 5;
Intent intent = new Intent(MainActivity1.this, MainActivity2.class);
startActivityForResult(intent, 2);// Activity is started with requestCode 2
}
});
}
// Call Back method to get the Message form other Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
String message = data.getStringExtra("MESSAGE");
textView1.setText("value =" + var1);
}
}
}
public class MainActivity2 extends ActionBarActivity {
EditText editText1;
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity2);
editText1=(EditText)findViewById(R.id.editText1);
button1=(Button)findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String message=editText1.getText().toString();
Intent intent=new Intent();
intent.putExtra("MESSAGE",message);
setResult(2,intent);
finish();//finishing activity
}
});
}
}
You're doing it wrong. You're saving a String in the intent.
Then in the onActivityResult method you retrieve the String from the intent, and then set the TextView's text to "value =" var1, but you didn't load var1 from the Intent.
You should save the value var1 in the intent in MainActivity2, and then retrieve it from the intent in the onActivityResult method.
In Settings > Developer Options there is a setting called "Don't keep activities". Make sure this isn't enabled, or the activity would be destroyed as soon as you start the second activity, and you would be recreating the first activity upon returning to it.

Creating a button intent to save information

I am creating an android application that uses data from buttons clicked to generate an answer stored in the shared preferences. I am having trouble finding the necessary intent code to save the information when the user clicked on the button so it can be used to calculate the answer. As you can see from the code when the user clicks the button it will generate the next activity.Thanks!
Button button18 = (Button) findViewById(R.id.button18);
button18.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//I need to store the results then move to the next activity shown below?
Intent i = new Intent(EnterAgeActivity.this, EnterWeightActivity.class);
startActivity(i);
// TODO Auto-generated method stub
}
});
`
Send the data with the intent.
#Override
public void onClick(View v) {
//I need to store the results then move to the next activity shown below?
Bundle data = new Bundle();
data.putString(key, value);
data.putInt(key, value);
Intent i = new Intent(EnterAgeActivity.this, EnterWeightActivity.class);
i.putExtra("data", data);
startActivity(i);
}
EnterWeightActivity oncreate:
#Override
public void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent.hasExtras) {
Bundle data = intent.getExtras();
// Your data
}
}

Categories