Android - Navigate to previous screen - java

I have a problem as explained here. I have a Class A, ClassB. Both have Intents to navigate to Class C. Now, I want to know from Which class i have navigated to Class C so that i will navigate to previous screen either A or B. Calling finish() in Class C doesnt help me because i need to update the data in Class A and Class B differently. Can anybody please help me. How to use Intent here? Can i know from which class i have to navigated to Class C?

you should use startActivityForResult and override the onActivityResult callback. This way you can safetly update your data without know from wich activity you came from.
public class A extends Activity {
private final static int REQUEST_CODE= 1000;
public void onCreate(BUndle b) {
...
Intent intent = new Intent(this, C.class);
startActivityForResult(intent, REQUEST_CODE);
}
#override
void onActivityResult(int requestCode, int resultCode, Intent data) {
// here through data you will receive new data
}
}
public class C extends Activity {
public void onCreate(BUndle b) {
// modify same data
Intent intent = new Intent();
// pute data inside intent
setResult(Activity.RESULT_OK, intent);
finish();
}
}

in your intents in class A and B, put a parameter like a boolean "isclassA" and make tests on it to know.
in intent of classe A :
intent.putExtra("isfromclassA",true);
in intent of class B :
intent.putExtra("isfromclassA",false);
therefor in your class C :
boolean isfromclassA = intent.getBoolExtra("isfromclassA");

Related

Call activity A method from Activity B Android

I'm a new to java and android. I was working on my own app but I'm having a problem in passing a method from Activity A to Activity B.
Here is what I did :
ActivityA has Demo() method.
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
protected void demo() {
// Do something
}
}
I created the below class to access the method of ActivityA to ActivityB:
public class External {
private ActivityA activitya;
private static External instance = null;
public External(ActivityA activitya) {
this.activitya = activitya;
}
static public External getInstance(ActivityA activitya) {
if (instance == null) {
instance = new MyntraExternal(activitya);
return instance;
} else {
return instance;
}
}
}
Now how can I proceed further? I'm having lots of problem in getting the method which is in ActivityA from ActivityB.
Please anybody help.
Edit :
ActivityB is my launcher class and I want some access from ActivityA's method in ActivityB. What to do ?
Since you are new to Android, I will tell you it's a bad practice call methods from Activity A to B or vice versa, you can pass parameters from one activity to another using intents and bundles and if you need to pass parameters from the second activity to the first you need to use the override method onActivityResults
Here are some usefull link about passing parameters from one activity to another:
https://www.dev2qa.com/passing-data-between-activities-android-tutorial/
In this link you can see a example of how things work.
Hope it helps.
--EDIT (if you need to call a function from B to A in case you want to change something in A upon creation this is the best and simplest way to do it):
In Activity B:
Intent intent = new Intent(this, ActivityA.class);
intent.putExtra("Work","doJump");
startActivity(intent);
In Activity A:
onCreate:
String extra = getIntent().getStringExtra("Work");
if(extra != null && extra.equals("doJump")){
jump();
}
make that method public and static and then access it using class name. e.g. In your 2nd activity, use ActivityB.demo()
Try using startActivityForResult
To start activity B from activity A
startActivityForResult(intent, SOME_CODE)
And to be called back on result you will need to add the following code the also in activity A
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when(code){
SOME_CODE -> if (resultCode == Activity.RESULT_OK) doSomething()
}
}
To tell Activity A to call the method, in activity B you can say:
setResult(Activity.RESULT_OK)
finish()
After B is finished, onActivityResult in A will be executed
To go back to A without executing the "doSomething()" method,
setResult(Activity.RESULT_CANCELED)
finish()
Please try this way
public class ActivityA extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void demo() {
// Do something
}
}
public class ActivityB extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActivityA activityA = new ActivityA(); // create object
activityA.demo(); //
}
}

Pass variable value to class (NOT intent) from home activity

I need to update a variable (via setter, I think) in a class that is not the intent class of a button. I need to set c to a given value in Creator from the Home activity. The chosen activity will then use Item Creator.
Home Activity:
int c;
public void setC(int c) {
this.c = c;
}
public void one(View view) {
setC(1);
Intent intent = new Intent(this, One.class);
startActivity(intent);
}
public void two(View view) {
setC(2);
Intent intent = new Intent(this, Two.class);
startActivity(intent);
}
public void three(View view) {
setC(3);
Intent intent = new Intent(this, Three.class);
startActivity(intent);
}
public void four(View view) {
setC(4);
Intent intent = new Intent(this, Four.class);
startActivity(intent);
}
public int getC() {
return c;
}
}
Class I am trying to pass c to:
public class Creator{
HomeActivity home = new HomeScreenActivity();
private int c = home.getC();
If I manually change c's value...
int c = 3;
... the class I want to receive it gets it fine. The issue seems to be getting the buttons to setC().
Thank you for any advice!
As far as your original question, I'd suggest using intents:
What's the best way to share data between activities?
cricket_007 is correct: use startActivity(), not "new HomeScreenActivity()":
https://developer.android.com/training/basics/firstapp/starting-activity.html

Refreshing parent activity from child?

guys, I'm pretty new to java android programming (that's the first app I'm making) and I have this question:
How can i refresh my Main Activity from another activity, which is called from the Main one?
I would also appreciate if you give me some examples, because I'm still not very orientated...
You can use startActivityForResult() for that purpose, instead of context.startActivity() call context.startActivityForResult() and then set result in launched activity before finishing it.
Here is the documentation for Context.startActivityForResult()
Sample code:
// Activity A
public class ActivityA extends Activity {
private static final int REQUEST_CODE_ACTIVITY_B_FOR_RESULT = 1; // or other int value
// sample code which starts Activity B
private void onSomeButtonClick() {
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, REQUEST_CODE_ACTIVITY_B_FOR_RESULT);
}
// this method will be called when started activity finished
// and returned some result of its work
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultData) {
super.onActivityResult(requestCode, resultCode, resultData);
if (requestCode == REQUEST_CODE_ACTIVITY_B_FOR_RESULT) {
if (resultCode == RESULT_OK) {
// handle result ok and resultData here
} else {
// handle result canceled or other resultCode and its resultData here
}
}
}
}
// Activity B
public class ActivityB extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setResult(RESULT_CANCELED); // by default result of starting activity is negative
}
// some code which doing some action and setting result as ok
private void doSomething() {
Intent resultData = new Intent();
resultData.putExtra("SOME_EXTRA", "did it"); // or other result data
setResult(RESULT_OK, resultData);
finish(); // finishing this activity, result code and result data will be accessible in previous activity
}
}
How to call main activity from the sub activity. Use an interface.
1. Creata a public interface in the sub-activity
public class MapSettings extends DialogFragment implements
OnCheckedChangeListener {
public interface BestRidesSettingsDialogListener {
void onMapSettingsChange(int mapType);
}
2. Implement the interface in the main activity note right click on errors and select add imports add reference add unimplemented methods.
public class KmlReader extends ActionBarActivity implements
BestRidesSettingsDialogListener {
3. when the sub activity starts in the sub activity cast getActivity to the public interface
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// the activity may be null if this is called without implementing the
// BestRidesSettingsDialogListener (The settings object saves the
// setting so the
// call back may not be needed.
activity = (BestRidesSettingsDialogListener) getActivity();
4. Then in the sub activity when a button is clicked or some event happens call through to the interface method.
#Override
public void onCheckedChanged(RadioGroup rg, int checkId) {
// TODO Auto-generated method stub
int mapType = 0;
switch (checkId) {
case R.id.RDORoad:
mapType = GoogleMap.MAP_TYPE_NORMAL;
break;
case R.id.RDOHybrid:
mapType = GoogleMap.MAP_TYPE_HYBRID;
break;
case R.id.RDOSatelite:
mapType = GoogleMap.MAP_TYPE_SATELLITE;
break;
case R.id.RDOTerrain:
mapType = GoogleMap.MAP_TYPE_TERRAIN;
break;
}
// run the activity onchange
// if the activity is null there is no listener to take action on the
// settings
if (activity != null) {
activity.onMapSettingsChange(mapType);
}
5. if you've filled in the unimplemented methods stubs in your main activity your executing code directly in the main activity from the sub activity.
#Override
public void onMapSettingsChange(int mapType) {
if (mMap != null) {
mMap.setMapType(mapType);
}
}
sidebar for comments: The interface has always been my favorite part of java. You might call it a listener or a call back. Just right click on the errors and select add reference, add unimplemented methods there really are not too many keystrokes to do this. The interface is perhaps the easiest way to coordinate a team effort on making the next big thing.

Call a method of an Activity from another Activity

I have two Activities A and B. B has a method searchDevices. I want to access that method from A 's onCreate method. How can I do it with Intent?
I tried this :
public void onCreate(Bundle savedInstanceState)
{
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MY_UUID= UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//Function enbling Bluetooth
enableBluetooth();
///Function to initialize components
init();
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
}catch(Exception e){Toast.makeText(getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();}
}
You can also create a base activity that both ActivityA and ActivityB extends and put searchDevices() method in it.
For ex:
public class BaseActivity extends Activity{
public void searchDevices(){
}
}
public class ActivityB extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
public class ActivityA extends BaseActivity{
onCreate..
{
...
searchDevices();
}
}
if ActivityA is in a class called class1 make a method in class1 like this
public static void method1(){
}
then in activity 2 call the method by doing this ActivityA.method1()
Why don't use StartActivityForResult.
As per my understanding You can start AvailableDevices Activity for result with Intent having extra data and call searchDevice to get AvailableDevices and return the result to calling Activity.
[Edit]
In Class A
//Calling AvailableDevices class's method searchDevice to get AvailableDevices
Intent intent=new Intent(this,AvailableDevices.class);
int x=10;
intent.putExtra("A", x);
startActivityForResult(intent , searchDevicesRequestCode); //searchDevicesRequestCode = 100
Also override onActivityResult()
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Check which request we're responding to
if (requestCode == searchDevicesRequestCode) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// Manipulate searchDevicesResult from Intent data
}
}
}
In Class B
#override
onCreate()
{
//call searchDevices()
String result = searchDevices(); // save result to send in any form
// Create intent to deliver some kind of result data
Intent intentResult = new Intent("RESULT_ACTION");
intentResult.putExtra("key",result);
setResult(Activity.RESULT_OK, intentResult);
finish();
}

Roboguice (1.1 and 1.2 Snapshot) injecting the wrong context in onActivityResult

onActivityResult() is a standard Android function that is called after a child Activity closes. However, it doesn't seem to close all the way.
After my child activity finishes, onActivityResult() is called in the parent. At this point, my action is to inject a context (through a provider, non-assisted) in a new class the parent is creating, using the parcelable information that the child has just given back to me for an #Assisted parameter in that new class.
However, despite finish() being called on the child, the context that is injected is not the parent--it is the child! This kills the program.
How do I get around this?
Here's some code that gives you an idea of what I'm doing.
In the parent:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_NEW_EXERCISE)
{
if (resultCode == RESULT_OK)
{
EntityExercise exercise = (EntityExercise)data.getExtras().get("exercise");
addNewRoutineExerciseDetail(exercise);
//Toast.makeText(this, exercise.getName(), Toast.LENGTH_LONG).show();
}
}
}
public RoutineExerciseDetail addNewRoutineExerciseDetail(EntityExercise exercise)
{
RoutineExerciseDetail detail = detailFactory.create(exercise);
detail.setOnClickRelativeLayoutListener(mEditParamsOnClickListener);
return detail;
}
In the child:
View.OnClickListener mListenerReturnExercise = new View.OnClickListener()
{
#Override
public void onClick(View v) {
Intent resultIntent = new Intent();
resultIntent.putExtra("exercise", (EntityExercise)v.getTag()); //Assuming it's the tag
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
};
RoutineExerciseDetail's constructor's parameters:
#Inject
public RoutineExerciseDetail(ActivityBaseRoboOrm<DatabaseHelper> context, List<RoutineExerciseDetail> list,
#AddEditExercise TableLayout layout, #Assisted EntityExercise exercise)
Yes, this will fail on RoboGuice 1.1. Activity.onActivityResult() is a somewhat unusual method in that it executes before the activity's onResume() is called, thus RoboGuice doesn't know to switch the context back to the caller activity.
One of the main changes in RoboGuice 1.2 is to fix this behavior. If you switch to 1.2 and replace any providers with ContextScopedProviders per these instructions, you should be good to go.
If you need to stay with RoboGuice 1.1, you should be able to scope your context manually the following way:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
scope.enter(this);
try {
...
} finally {
scope.exit(this);
}
}
In ActivityForResult method in Android your requestcode should be same in both the Activity.then and only then your code will work. I hope it will help you.

Categories