Passing data between activities in onPause - java

i am facing trouble in passing data in activity's onpause() method.when user clicks a button in one activity, 2nd activity starts.in 1st activity's onPasue method i want to pass some data to other activity.i use intent.putExtra() to save data in onpause().in 2nd activity i use bundle.getString() to retrieve data.below is my code
public class FirstActivity extends Activity {
Intent intent;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tola_calculation);
b = (Button) findViewById(R.id.button);
intent = new Intent(Tola_calculation.this, Kaat_calculation.class);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(intent);
}
});
}
#Override
public void onPause() {
super.onPause();
intent.putExtra("key", "i am value");
}}
and
public class secondActivity extends Activity {
int value;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_kaat_calculation);
Bundle extras=new Bundle();
Intent intent=getIntent();
extras=intent.getExtras();
if (extras!=null) {
String value = extras.getString("key");
Toast.makeText(Kaat_calculation.this,value,Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(Kaat_calculation.this,"null problem",Toast.LENGTH_SHORT).show();
}
}}
problem is in 2nd activity intent.getExtras() returns null first time.i press back button 1st activity resumes.then i click again to go to 2nd activity.this time data is retrieved and intent.getextras() does not return null.can somebody explain this strange behaviour.or i am doing something strange as i am new to android programming.i hope i am able to clearly explain problem

This happens because your 2nd Activity is created before the 1st Activity calls onPause().
Solution: put your extra inside the onClick() callback. In other words (as the other answers suggest) you need to attach data to the Intent before calling startActivity() with that Intent.
In 1st Activity's onPause() method I want to pass some data to
other Activity
There's absolutely no need to do so because your 1st Activity is guaranteed to call onPause() as soon as your 2nd Activity becomes visible. So you already know at this point that your 1st Activity has called onPause().
Consult the official docs on Activity lifecycle for more details.

You should add data to Intent before you start the new activity. So this row
intent.putExtra("key", "i am value");
Should go before
startActivity(intent);
All in all, right code
public class FirstActivity extends Activity {
Intent intent;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tola_calculation);
b = (Button) findViewById(R.id.button);
intent = new Intent(Tola_calculation.this, Kaat_calculation.class);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
intent.putExtra("key", "i am value");
startActivity(intent);
}
});
}
#Override
public void onPause() {
super.onPause();
}
}

onPause method does not mean that your Activity is finishing, merely that it is pausing. If the user is pressing the back-button for example it will Pause, but not finish the Activity. better see the Activity lifecycle documentation
and also see this http://developer.android.com/reference/android/app/Activity.html#finish%28%29

It's NOT working the first time because when you are calling startActivity the extra is not set yet. Activity #2 starts before onPause is called.
It is working the second time because you made the intent variable an instance variable and you are not calling finish() after startActivity() call. That makes your first activity instance stay alive. The second time you launch the activity #2 the intent instance is already there and it already has the extra in it.
Solution: you should put the extra right before calling startActivity() and it'll work fine.
There is a great 7 step explanation on how this all works on Android Docs page

Related

Android studio - How to save data selected on previous activity

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.

can write OnClickListener into parceable?

Hello I have a trouble with OnClickListener
View.OnClickListener listener= new View.OnClickListener()
{
#Override
public void onClick(View view)
{
Toast.makeText(Conversations.this, "click on MSG",
Toast.LENGTH_SHORT).show();
}
};
========================================================================
I Need put this listener into Fragment which will parceable.
I not parceableing listener but after readvalue is null and when click app crasher because it's reference on null object.
now I need find some methods which can use for save and read object (View.OnClickListener) if parceable or something similar.
Without this I need rebuild my project :(
Please Help me.
Thanks
_______________________________________________________--
I haven't have fragment in fragment I want all fragment put into "extra" and in other activity read from extra..
Intent i= new Intent(Conversations.this,MessagesSingleFragmentActivity.cla‌​ss); i.putExtra("Fragment1", (Parcelable) recycleMessage); startActivity(i);
and in other activity have
Intent extras = getIntent(); Fragment fragment = (Fragment) extras.getParcelableExtra("Fragment1"); fm.beginTransaction().replace(R.id.fragment_container, fragment).commit();
No you cannot pass OnClickListener as Parcelable but , if you want to observe click from one fragment to another , then you have to implement the onclick in second fragment.
FragA.java:// who have onClickListener
Runnable run;
public void setClick(Runnable run){
this.run = run;
}
view.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// do something in onclick
if(run!=null){run.run();}
}
});
FragB.java:
((FragA)getParentFragment()).setClick(
new Runnable() {
#Override
public void run() {
// do something in other fragment
}
}
)
Updated:
If you want to perform something onClick of ActivityA on ActivityB , then EventBus are best options for that use Otto or EventBus by GreenBot
It is recommended to interact between fragments via Activity.. or more generally by interface which Activity conforms to.
One more thing: If you have common functionality in both fragments, maybe it is better to extract it to Activity?

Causing an exception when setting 2 onClickListener() on buttons located on 2 different layout

I have a problem and I can't seem to set 2 onClickListener for 2 separate buttons located on 2 different layout, when running the program, it cause an exception to occur.
btnClickToSecondPage button is located in activity_main.xml layout and btnObjClickToGoToFirstPage button is located at second_activity.xml layout.
The java code for my program is located below here
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(getWindow().FEATURE_NO_TITLE);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
Button btnObjClickToGoToSecondPage = (Button) findViewById(R.id.btnClickToSecondPage);
Button btnObjClickToGoToFirstPage = (Button) findViewById(R.id.btnChangetoFirstPage);
btnObjClickToGoToFirstPage.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick (View v)
{
setContentView(R.layout.second_activity);
}
}
);
btnObjClickToGoToSecondPage.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick (View v)
{
setContentView(R.layout.activity_main);
}
}
);
} }
Please help me rectified the problem thanks.
Please implement the View.Onclick listener not Button.onclick listener
btnObjClickToGoToFirstPage.setOnClickListener(
new View.OnClickListener(){
#Override
public void onClick (View v)
{
setContentView(R.layout.second_activity);
}
}
);
It is not a proper way switching pages in Android. Use two activities for switching pages with intents.
Intent newPage = new Intent (this, YourActivityNameForNewPage.class);
startActivity(newPage);
Put above code in your button's onClick().
If you want to show a new page you either start a new activity or start a new fragment.
Changing the contentView is not the correct way to approach this and should not be done.
You refer to the documentation on activities here.
Assuming you have another Activity called SecondActivity here is how you would start it:
btnObjClickToGoToSecondPage.setOnClickListener(
new Button.OnClickListener(){
#Override
public void onClick (View v)
{
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
startActivity(intent);
}
}
);
And then you define the layout in the XML of the new activity, that is second_activity.xml
If they all have similar layouts using a fragment is also a good option.
Basically you start a new activity or fragment to show anything new or change the data dynamically say on your button's onClick().
This question may further clear your doubts:
What is setContentView(R.layout.main)?

How to check which button is Clicked with android?

I have 2 activities, the first activity include two buttons and the second activity also include 2 buttons. I need when I click on the first button of the first activity, the second activity started and the first button of the second activity become "invisible" and the second button "visible". again if the user back to the first activity and click the second button, then the second activity started where the second button become "invisible" and first one "visible".
I just need to know how to decide that which button from the first activity is pressed by the user. is there any specific method , or if any way?
I tried doing it by set a variable (int i) as a global variable in the first activity and if the user click the first button then this (i) changes to 1 (Same Thing to Second Button), and I set a condition in the second activity that call this (i) variable as:
MainActivity a=new MainActivity();
if(a.i==0){
//do this
}
else if(a.i==1){
//do this
}
but this doesn't work and the second activity always get this (i) as it's equal to (0).
You should start your second activity by using an Intent. For this Intent you can put some Arguments.
In your First Activity:
Button b1 = (Button)findViewById(R.id.button1);
Button b2 = (Button)findViewById(R.id.button2);
// Set OnClickListeners
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Start Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("buttontohide", 0); // Hide Button 0
startActivity(intent);
}
});
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// Start Activity
Intent intent = new Intent(this, Activity2.class);
intent.putExtra("buttontohide", 1); // Hide Button 1
startActivity(intent);
}
});
In your Second Activity:
Intent myIntent = getIntent();
int i = myIntent.getExtras().getInt("buttontohide");
You can pass parameters into extra before starting second activity. Use it to tell to second activity which button is clicked. In onCreate() method of second activity analyze extra to define which button must be hidden.
MainActivity a = new MainActivity();
You're initializing the Activity again. But in your case, take a static variable instead.
Do something like this.
In your MainActivity.java declare a static variable
public class MainActivity extends Activity {
public static int a = 0;
// Rest of your code
}
Now from the second activity check whether the value is 0 or 1 like this
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
if(MainActivity.a == 0) { /*Do something*/ }
else { /*Do something*/ }
}
}
I assumed that you know all the code how to make a button visible and invisible. first declare an int variable in your first activity and pass it to second activity using getIntent, after that using if else logic capture your variable value and put your code to make the button invisible.
You could use a Bundle to pass data from Activity A to Activity B:
In Activity A:
... onClick() {
...
Intent intent = new Intent(this, ActivityB.class);
intent.putExtra("ButtonNR", iButtonNR);
startActivity(intent);
}
In Activity B:
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
...
Bundle bundle = getIntent().getExtras();
int iButtonNR = bundle.getInt("ButtonNR");
switch (iButtonNR) {
case 0:
//do something...
break;
case 1:
//do another thing...
break;
}
}
}

How do I create a custom preference that uses an existing activity that returns a result?

The Preference class allows for an Intent to be set, to have a preference activate another activity when clicked, but I'm unable to find a way to handle the result from an activity using this method. There's also the DialogPreference where I can provide a custom view, but I don't have direct access to the view I want to use, only an activity.
Digging a bit further, it looks like the RingtonePreference uses a few package internal methods on PreferenceManager to receive results from a started sub-activity, but as these are package internal I am unable to do the same.
Is there any other way of handling a custom preference with an activity that returns a result (where the result is to be saved as the value of the preference)?
I have also noticed PreferenceActivity does not return onActivityResult. That being said, is there a reason your SubActivity couldn't save the preference directly? If you need to check the value of it, you could check it at onResume of your PreferenceActivity as a workaround..
//SubActivity onCreate
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btn = (Button) findViewById(R.id.Button01);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences prefs = getSharedPreferences(TestPreferenceActivity.PREFS_FILE, MODE_WORLD_READABLE);
prefs.edit().putString("mykey", "someValue").commit();
finish();
}});
}
//PreferenceActivity onResume
#Override
protected void onResume() {
Log.d(TAG, "Preferences Resumed");
//Check for new Preference Values
SharedPreferences prefs = getSharedPreferences(PREFS_FILE, MODE_WORLD_READABLE);
String value = prefs.getString("mykey", "defValue");
Log.d(TAG, "Current value is: " + value);
super.onResume();
}

Categories